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

systemd / systemd / 20286914613

16 Dec 2025 11:25PM UTC coverage: 72.736% (+0.03%) from 72.703%
20286914613

push

github

web-flow
core/exec-credential: fix credentials plain dir exchanging (#40108)

Follow-ups for #39637

Split out from #40093

45 of 72 new or added lines in 3 files covered. (62.5%)

2104 existing lines in 43 files now uncovered.

309764 of 425877 relevant lines covered (72.74%)

1155086.73 hits per line

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

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

3
#include <fcntl.h>
4
#include <linux/if.h>
5
#include <linux/if_arp.h>
6
#include <mqueue.h>
7
#include <net/if.h>
8
#include <netdb.h>
9
#include <netinet/ip.h>
10
#include <poll.h>
11
#include <stdio.h>
12
#include <sys/ioctl.h>
13
#include <unistd.h>
14

15
#include "alloc-util.h"
16
#include "errno-util.h"
17
#include "escape.h"
18
#include "fd-util.h"
19
#include "format-ifname.h"
20
#include "format-util.h"
21
#include "in-addr-util.h"
22
#include "io-util.h"
23
#include "log.h"
24
#include "memory-util.h"
25
#include "parse-util.h"
26
#include "path-util.h"
27
#include "pidref.h"
28
#include "process-util.h"
29
#include "random-util.h"
30
#include "socket-util.h"
31
#include "sparse-endian.h"
32
#include "string-table.h"
33
#include "string-util.h"
34
#include "strv.h"
35
#include "sysctl-util.h"
36

37
#if ENABLE_IDN
38
#  define IDN_FLAGS NI_IDN
39
#else
40
#  define IDN_FLAGS 0
41
#endif
42

43
static const char* const socket_address_type_table[] = {
44
        [SOCK_STREAM] =    "Stream",
45
        [SOCK_DGRAM] =     "Datagram",
46
        [SOCK_RAW] =       "Raw",
47
        [SOCK_RDM] =       "ReliableDatagram",
48
        [SOCK_SEQPACKET] = "SequentialPacket",
49
        [SOCK_DCCP] =      "DatagramCongestionControl",
50
};
51

52
DEFINE_STRING_TABLE_LOOKUP(socket_address_type, int);
×
53

54
int socket_address_verify(const SocketAddress *a, bool strict) {
9,294✔
55
        assert(a);
9,294✔
56

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

60
        switch (socket_address_family(a)) {
9,294✔
61

62
        case AF_INET:
27✔
63
                if (a->size != sizeof(struct sockaddr_in))
27✔
64
                        return -EINVAL;
65

66
                if (a->sockaddr.in.sin_port == 0)
27✔
67
                        return -EINVAL;
68

69
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
27✔
70
                        return -EINVAL;
1✔
71

72
                return 0;
73

74
        case AF_INET6:
31✔
75
                if (a->size != sizeof(struct sockaddr_in6))
31✔
76
                        return -EINVAL;
77

78
                if (a->sockaddr.in6.sin6_port == 0)
31✔
79
                        return -EINVAL;
80

81
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
31✔
82
                        return -EINVAL;
×
83

84
                return 0;
85

86
        case AF_UNIX:
8,762✔
87
                if (a->size < offsetof(struct sockaddr_un, sun_path))
8,762✔
88
                        return -EINVAL;
89
                if (a->size > sizeof(struct sockaddr_un) + !strict)
8,762✔
90
                        /* If !strict, allow one extra byte, since getsockname() on Linux will append
91
                         * a NUL byte if we have path sockets that are above sun_path's full size. */
92
                        return -EINVAL;
93

94
                if (a->size > offsetof(struct sockaddr_un, sun_path) &&
8,762✔
95
                    a->sockaddr.un.sun_path[0] != 0 &&
8,762✔
96
                    strict) {
97
                        /* Only validate file system sockets here, and only in strict mode */
98
                        const char *e;
3,485✔
99

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

115
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET))
8,762✔
116
                        return -EINVAL;
×
117

118
                return 0;
119

120
        case AF_NETLINK:
382✔
121

122
                if (a->size != sizeof(struct sockaddr_nl))
382✔
123
                        return -EINVAL;
124

125
                if (!IN_SET(a->type, 0, SOCK_RAW, SOCK_DGRAM))
382✔
126
                        return -EINVAL;
×
127

128
                return 0;
129

130
        case AF_VSOCK:
75✔
131
                if (a->size != sizeof(struct sockaddr_vm))
75✔
132
                        return -EINVAL;
133

134
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
75✔
135
                        return -EINVAL;
×
136

137
                return 0;
138

139
        default:
140
                return -EAFNOSUPPORT;
141
        }
142
}
143

144
int socket_address_print(const SocketAddress *a, char **ret) {
1,946✔
145
        int r;
1,946✔
146

147
        assert(a);
1,946✔
148
        assert(ret);
1,946✔
149

150
        r = socket_address_verify(a, false); /* We do non-strict validation, because we want to be
1,946✔
151
                                              * able to pretty-print any socket the kernel considers
152
                                              * valid. We still need to do validation to know if we
153
                                              * can meaningfully print the address. */
154
        if (r < 0)
1,946✔
155
                return r;
156

157
        if (socket_address_family(a) == AF_NETLINK) {
1,946✔
158
                _cleanup_free_ char *sfamily = NULL;
127✔
159

160
                r = netlink_family_to_string_alloc(a->protocol, &sfamily);
127✔
161
                if (r < 0)
127✔
162
                        return r;
163

164
                r = asprintf(ret, "%s %u", sfamily, a->sockaddr.nl.nl_groups);
127✔
165
                if (r < 0)
127✔
166
                        return -ENOMEM;
167

168
                return 0;
127✔
169
        }
170

171
        return sockaddr_pretty(&a->sockaddr.sa, a->size, false, true, ret);
1,819✔
172
}
173

174
bool socket_address_can_accept(const SocketAddress *a) {
6,628✔
175
        assert(a);
6,628✔
176

177
        return
6,628✔
178
                IN_SET(a->type, SOCK_STREAM, SOCK_SEQPACKET);
6,628✔
179
}
180

181
bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) {
1,865✔
182
        assert(a);
1,865✔
183
        assert(b);
1,865✔
184

185
        /* Invalid addresses are unequal to all */
186
        if (socket_address_verify(a, false) < 0 ||
3,730✔
187
            socket_address_verify(b, false) < 0)
1,865✔
188
                return false;
189

190
        if (a->type != b->type)
1,864✔
191
                return false;
192

193
        if (socket_address_family(a) != socket_address_family(b))
1,863✔
194
                return false;
195

196
        switch (socket_address_family(a)) {
1,861✔
197

198
        case AF_INET:
6✔
199
                if (a->sockaddr.in.sin_addr.s_addr != b->sockaddr.in.sin_addr.s_addr)
6✔
200
                        return false;
201

202
                if (a->sockaddr.in.sin_port != b->sockaddr.in.sin_port)
5✔
203
                        return false;
1✔
204

205
                break;
206

207
        case AF_INET6:
2✔
208
                if (memcmp(&a->sockaddr.in6.sin6_addr, &b->sockaddr.in6.sin6_addr, sizeof(a->sockaddr.in6.sin6_addr)) != 0)
2✔
209
                        return false;
210

211
                if (a->sockaddr.in6.sin6_port != b->sockaddr.in6.sin6_port)
2✔
212
                        return false;
×
213

214
                break;
215

216
        case AF_UNIX:
1,744✔
217
                if (a->size <= offsetof(struct sockaddr_un, sun_path) ||
1,744✔
218
                    b->size <= offsetof(struct sockaddr_un, sun_path))
1,744✔
219
                        return false;
220

221
                if ((a->sockaddr.un.sun_path[0] == 0) != (b->sockaddr.un.sun_path[0] == 0))
1,744✔
222
                        return false;
223

224
                if (a->sockaddr.un.sun_path[0]) {
1,589✔
225
                        if (!path_equal_or_inode_same(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, 0))
1,587✔
226
                                return false;
248✔
227
                } else {
228
                        if (a->size != b->size)
2✔
229
                                return false;
230

231
                        if (memcmp(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, a->size) != 0)
2✔
232
                                return false;
×
233
                }
234

235
                break;
236

237
        case AF_NETLINK:
88✔
238
                if (a->protocol != b->protocol)
88✔
239
                        return false;
240

241
                if (a->sockaddr.nl.nl_groups != b->sockaddr.nl.nl_groups)
88✔
242
                        return false;
1✔
243

244
                break;
245

246
        case AF_VSOCK:
21✔
247
                if (a->sockaddr.vm.svm_cid != b->sockaddr.vm.svm_cid)
21✔
248
                        return false;
249

250
                if (a->sockaddr.vm.svm_port != b->sockaddr.vm.svm_port)
20✔
251
                        return false;
1✔
252

253
                break;
254

255
        default:
256
                /* Cannot compare, so we assume the addresses are different */
257
                return false;
258
        }
259

260
        return true;
261
}
262

263
const char* socket_address_get_path(const SocketAddress *a) {
15,056✔
264
        assert(a);
15,056✔
265

266
        if (socket_address_family(a) != AF_UNIX)
15,056✔
267
                return NULL;
268

269
        if (a->sockaddr.un.sun_path[0] == 0)
14,498✔
270
                return NULL;
271

272
        /* Note that this is only safe because we know that there's an extra NUL byte after the sockaddr_un
273
         * structure. On Linux AF_UNIX file system socket addresses don't have to be NUL terminated if they take up the
274
         * full sun_path space. */
275
        assert_cc(sizeof(union sockaddr_union) >= sizeof(struct sockaddr_un)+1);
14,497✔
276
        return a->sockaddr.un.sun_path;
14,497✔
277
}
278

279
bool socket_ipv6_is_supported(void) {
153,655✔
280
        static int cached = -1;
153,655✔
281

282
        if (cached < 0) {
153,655✔
283

284
                if (access("/proc/net/if_inet6", F_OK) < 0) {
1,141✔
285

286
                        if (errno != ENOENT) {
×
287
                                log_debug_errno(errno, "Unexpected error when checking whether /proc/net/if_inet6 exists: %m");
×
288
                                return false;
×
289
                        }
290

291
                        cached = false;
×
292
                } else
293
                        cached = true;
1,141✔
294
        }
295

296
        return cached;
153,655✔
297
}
298

299
bool socket_ipv6_is_enabled(void) {
114,096✔
300
        _cleanup_free_ char *v = NULL;
114,096✔
301
        int r;
114,096✔
302

303
        /* Much like socket_ipv6_is_supported(), but also checks that the sysctl that disables IPv6 on all
304
         * interfaces isn't turned on */
305

306
        if (!socket_ipv6_is_supported())
114,096✔
307
                return false;
308

309
        r = sysctl_read_ip_property(AF_INET6, "all", "disable_ipv6", &v);
114,096✔
310
        if (r < 0) {
114,096✔
311
                log_debug_errno(r, "Unexpected error reading 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
×
312
                return true;
×
313
        }
314

315
        r = parse_boolean(v);
114,096✔
316
        if (r < 0) {
114,096✔
317
                log_debug_errno(r, "Failed to pare 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
×
318
                return true;
×
319
        }
320

321
        return !r;
114,096✔
322
}
323

324
bool socket_address_matches_fd(const SocketAddress *a, int fd) {
516✔
325
        SocketAddress b;
516✔
326
        socklen_t solen;
516✔
327

328
        assert(a);
516✔
329
        assert(fd >= 0);
516✔
330

331
        b.size = sizeof(b.sockaddr);
516✔
332
        if (getsockname(fd, &b.sockaddr.sa, &b.size) < 0)
516✔
333
                return false;
516✔
334

335
        if (b.sockaddr.sa.sa_family != a->sockaddr.sa.sa_family)
516✔
336
                return false;
337

338
        solen = sizeof(b.type);
466✔
339
        if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &b.type, &solen) < 0)
466✔
340
                return false;
341

342
        if (b.type != a->type)
466✔
343
                return false;
344

345
        if (a->protocol != 0)  {
403✔
346
                solen = sizeof(b.protocol);
×
347
                if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &b.protocol, &solen) < 0)
×
348
                        return false;
349

350
                if (b.protocol != a->protocol)
×
351
                        return false;
352
        }
353

354
        return socket_address_equal(a, &b);
403✔
355
}
356

357
int sockaddr_port(const struct sockaddr *_sa, unsigned *ret_port) {
×
358
        const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
×
359

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

362
        assert(sa);
×
363

364
        switch (sa->sa.sa_family) {
×
365

366
        case AF_INET:
×
367
                *ret_port = be16toh(sa->in.sin_port);
×
368
                return 0;
×
369

370
        case AF_INET6:
×
371
                *ret_port = be16toh(sa->in6.sin6_port);
×
372
                return 0;
×
373

374
        case AF_VSOCK:
×
375
                *ret_port = sa->vm.svm_port;
×
376
                return 0;
×
377

378
        default:
379
                return -EAFNOSUPPORT;
380
        }
381
}
382

383
const union in_addr_union *sockaddr_in_addr(const struct sockaddr *_sa) {
322✔
384
        const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
322✔
385

386
        if (!sa)
322✔
387
                return NULL;
388

389
        switch (sa->sa.sa_family) {
322✔
390

391
        case AF_INET:
266✔
392
                return (const union in_addr_union*) &sa->in.sin_addr;
266✔
393

394
        case AF_INET6:
56✔
395
                return (const union in_addr_union*) &sa->in6.sin6_addr;
56✔
396

397
        default:
398
                return NULL;
399
        }
400
}
401

402
int sockaddr_set_in_addr(
894✔
403
                union sockaddr_union *u,
404
                int family,
405
                const union in_addr_union *a,
406
                uint16_t port) {
407

408
        assert(u);
894✔
409
        assert(a);
894✔
410

411
        switch (family) {
894✔
412

413
        case AF_INET:
878✔
414
                u->in = (struct sockaddr_in) {
878✔
415
                        .sin_family = AF_INET,
416
                        .sin_addr = a->in,
878✔
417
                        .sin_port = htobe16(port),
878✔
418
                };
419

420
                return 0;
878✔
421

422
        case AF_INET6:
16✔
423
                u->in6 = (struct sockaddr_in6) {
16✔
424
                        .sin6_family = AF_INET6,
425
                        .sin6_addr = a->in6,
16✔
426
                        .sin6_port = htobe16(port),
16✔
427
                };
428

429
                return 0;
16✔
430

431
        default:
432
                return -EAFNOSUPPORT;
433

434
        }
435
}
436

437
int sockaddr_pretty(
8,835✔
438
                const struct sockaddr *_sa,
439
                socklen_t salen,
440
                bool translate_ipv6,
441
                bool include_port,
442
                char **ret) {
443

444
        union sockaddr_union *sa = (union sockaddr_union*) _sa;
8,835✔
445
        char *p;
8,835✔
446
        int r;
8,835✔
447

448
        assert(sa);
8,835✔
449
        assert(salen >= sizeof(sa->sa.sa_family));
8,835✔
450
        assert(ret);
8,835✔
451

452
        switch (sa->sa.sa_family) {
8,835✔
453

454
        case AF_INET: {
146✔
455
                uint32_t a;
146✔
456

457
                a = be32toh(sa->in.sin_addr.s_addr);
146✔
458

459
                if (include_port)
146✔
460
                        r = asprintf(&p,
146✔
461
                                     "%u.%u.%u.%u:%u",
462
                                     a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
463
                                     be16toh(sa->in.sin_port));
146✔
464
                else
465
                        r = asprintf(&p,
×
466
                                     "%u.%u.%u.%u",
467
                                     a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF);
468
                if (r < 0)
146✔
469
                        return -ENOMEM;
8,835✔
470
                break;
471
        }
472

473
        case AF_INET6: {
18✔
474
                static const unsigned char ipv4_prefix[] = {
18✔
475
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
476
                };
477

478
                if (translate_ipv6 &&
18✔
479
                    memcmp(&sa->in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
9✔
480
                        const uint8_t *a = sa->in6.sin6_addr.s6_addr+12;
×
481
                        if (include_port)
×
482
                                r = asprintf(&p,
×
483
                                             "%u.%u.%u.%u:%u",
484
                                             a[0], a[1], a[2], a[3],
×
485
                                             be16toh(sa->in6.sin6_port));
×
486
                        else
487
                                r = asprintf(&p,
×
488
                                             "%u.%u.%u.%u",
489
                                             a[0], a[1], a[2], a[3]);
×
490
                        if (r < 0)
×
491
                                return -ENOMEM;
492
                } else {
493
                        const char *a = IN6_ADDR_TO_STRING(&sa->in6.sin6_addr);
18✔
494

495
                        if (include_port) {
18✔
496
                                if (asprintf(&p,
17✔
497
                                             "[%s]:%u%s%s",
498
                                             a,
499
                                             be16toh(sa->in6.sin6_port),
17✔
500
                                             sa->in6.sin6_scope_id != 0 ? "%" : "",
17✔
501
                                             FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX)) < 0)
17✔
502
                                        return -ENOMEM;
×
503
                        } else {
504
                                if (sa->in6.sin6_scope_id != 0)
1✔
505
                                        p = strjoin(a, "%", FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX));
×
506
                                else
507
                                        p = strdup(a);
1✔
508
                                if (!p)
1✔
509
                                        return -ENOMEM;
510
                        }
511
                }
512

513
                break;
514
        }
515

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

529
                        if (path[0] == 0) {
8,554✔
530
                                /* Abstract socket. When parsing address information from, we
531
                                 * explicitly reject overly long paths and paths with embedded NULs.
532
                                 * But we might get such a socket from the outside. Let's return
533
                                 * something meaningful and printable in this case. */
534

535
                                _cleanup_free_ char *e = NULL;
8✔
536

537
                                e = cescape_length(path + 1, path_len - 1);
8✔
538
                                if (!e)
8✔
539
                                        return -ENOMEM;
×
540

541
                                p = strjoin("@", e);
8✔
542
                        } else {
543
                                if (path[path_len - 1] == '\0')
8,546✔
544
                                        /* We expect a terminating NUL and don't print it */
545
                                        path_len--;
8,545✔
546

547
                                p = cescape_length(path, path_len);
8,546✔
548
                        }
549
                }
550
                if (!p)
8,647✔
551
                        return -ENOMEM;
552

553
                break;
554

555
        case AF_VSOCK:
24✔
556
                if (include_port) {
24✔
557
                        if (sa->vm.svm_cid == VMADDR_CID_ANY)
24✔
558
                                r = asprintf(&p, "vsock::%u", sa->vm.svm_port);
21✔
559
                        else
560
                                r = asprintf(&p, "vsock:%u:%u", sa->vm.svm_cid, sa->vm.svm_port);
3✔
561
                } else
562
                        r = asprintf(&p, "vsock:%u", sa->vm.svm_cid);
×
563
                if (r < 0)
24✔
564
                        return -ENOMEM;
565
                break;
566

567
        default:
568
                return -EOPNOTSUPP;
569
        }
570

571
        *ret = p;
8,835✔
572
        return 0;
8,835✔
573
}
574

575
int getpeername_pretty(int fd, bool include_port, char **ret) {
92✔
576
        union sockaddr_union sa;
92✔
577
        socklen_t salen = sizeof(sa);
92✔
578
        int r;
92✔
579

580
        assert(fd >= 0);
92✔
581
        assert(ret);
92✔
582

583
        if (getpeername(fd, &sa.sa, &salen) < 0)
92✔
584
                return -errno;
×
585

586
        if (sa.sa.sa_family == AF_UNIX) {
92✔
587
                struct ucred ucred = UCRED_INVALID;
91✔
588

589
                /* UNIX connection sockets are anonymous, so let's use
590
                 * PID/UID as pretty credentials instead */
591

592
                r = getpeercred(fd, &ucred);
91✔
593
                if (r < 0)
91✔
594
                        return r;
91✔
595

596
                if (asprintf(ret, "PID "PID_FMT"/UID "UID_FMT, ucred.pid, ucred.uid) < 0)
91✔
597
                        return -ENOMEM;
598

599
                return 0;
91✔
600
        }
601

602
        /* For remote sockets we translate IPv6 addresses back to IPv4
603
         * if applicable, since that's nicer. */
604

605
        return sockaddr_pretty(&sa.sa, salen, true, include_port, ret);
1✔
606
}
607

608
int getsockname_pretty(int fd, char **ret) {
2✔
609
        union sockaddr_union sa;
2✔
610
        socklen_t salen = sizeof(sa);
2✔
611

612
        assert(fd >= 0);
2✔
613
        assert(ret);
2✔
614

615
        if (getsockname(fd, &sa.sa, &salen) < 0)
2✔
616
                return -errno;
×
617

618
        /* For local sockets we do not translate IPv6 addresses back
619
         * to IPv6 if applicable, since this is usually used for
620
         * listening sockets where the difference between IPv4 and
621
         * IPv6 matters. */
622

623
        return sockaddr_pretty(&sa.sa, salen, false, true, ret);
2✔
624
}
625

626
int socknameinfo_pretty(const struct sockaddr *sa, socklen_t salen, char **ret) {
×
627
        char host[NI_MAXHOST];
×
628
        int r;
×
629

630
        assert(sa);
×
631
        assert(salen >= sizeof(sa_family_t));
×
632
        assert(ret);
×
633

634
        r = getnameinfo(sa, salen, host, sizeof(host), /* service= */ NULL, /* service_len= */ 0, IDN_FLAGS);
×
635
        if (r != 0) {
×
636
                if (r == EAI_MEMORY)
×
637
                        return log_oom_debug();
×
638
                if (r == EAI_SYSTEM)
×
639
                        log_debug_errno(errno, "getnameinfo() failed, ignoring: %m");
×
640
                else
641
                        log_debug("getnameinfo() failed, ignoring: %s", gai_strerror(r));
×
642

643
                return sockaddr_pretty(sa, salen, /* translate_ipv6= */ true, /* include_port= */ true, ret);
×
644
        }
645

646
        return strdup_to(ret, host);
×
647
}
648

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

670
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
565✔
671

672
bool sockaddr_equal(const union sockaddr_union *a, const union sockaddr_union *b) {
659✔
673
        assert(a);
659✔
674
        assert(b);
659✔
675

676
        if (a->sa.sa_family != b->sa.sa_family)
659✔
677
                return false;
678

679
        if (a->sa.sa_family == AF_INET)
658✔
680
                return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
4✔
681

682
        if (a->sa.sa_family == AF_INET6)
654✔
683
                return memcmp(&a->in6.sin6_addr, &b->in6.sin6_addr, sizeof(a->in6.sin6_addr)) == 0;
1✔
684

685
        if (a->sa.sa_family == AF_VSOCK)
653✔
686
                return a->vm.svm_cid == b->vm.svm_cid;
1✔
687

688
        return false;
689
}
690

691
int fd_set_sndbuf(int fd, size_t n, bool increase) {
414,604✔
692
        int r, value;
414,604✔
693
        socklen_t l = sizeof(value);
414,604✔
694

695
        if (n > INT_MAX)
414,604✔
696
                return -ERANGE;
414,604✔
697

698
        r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
414,604✔
699
        if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
414,604✔
700
                return 0;
701

702
        /* First, try to set the buffer size with SO_SNDBUF. */
703
        r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUF, n);
414,604✔
704
        if (r < 0)
414,604✔
705
                return r;
706

707
        /* SO_SNDBUF above may set to the kernel limit, instead of the requested size.
708
         * So, we need to check the actual buffer size here. */
709
        l = sizeof(value);
414,604✔
710
        r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
414,604✔
711
        if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
414,604✔
712
                return 1;
713

714
        /* If we have the privileges we will ignore the kernel limit. */
715
        r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUFFORCE, n);
414,604✔
716
        if (r < 0)
414,604✔
717
                return r;
28,963✔
718

719
        return 1;
720
}
721

722
int fd_set_rcvbuf(int fd, size_t n, bool increase) {
31,737✔
723
        int r, value;
31,737✔
724
        socklen_t l = sizeof(value);
31,737✔
725

726
        if (n > INT_MAX)
31,737✔
727
                return -ERANGE;
31,737✔
728

729
        r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
31,737✔
730
        if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
31,737✔
731
                return 0;
732

733
        /* First, try to set the buffer size with SO_RCVBUF. */
734
        r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUF, n);
31,736✔
735
        if (r < 0)
31,736✔
736
                return r;
737

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

745
        /* If we have the privileges we will ignore the kernel limit. */
746
        r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUFFORCE, n);
31,736✔
747
        if (r < 0)
31,736✔
748
                return r;
5,683✔
749

750
        return 1;
751
}
752

753
static const char* const ip_tos_table[] = {
754
        [IPTOS_LOWDELAY]    = "low-delay",
755
        [IPTOS_THROUGHPUT]  = "throughput",
756
        [IPTOS_RELIABILITY] = "reliability",
757
        [IPTOS_LOWCOST]     = "low-cost",
758
};
759

760
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
5✔
761

762
bool ifname_valid_char(char a) {
508,915✔
763
        if ((unsigned char) a >= 127U)
508,915✔
764
                return false;
765

766
        if ((unsigned char) a <= 32U)
508,915✔
767
                return false;
768

769
        if (IN_SET(a,
508,911✔
770
                   ':',  /* colons are used by the legacy "alias" interface logic */
771
                   '/',  /* slashes cannot work, since we need to use network interfaces in sysfs paths, and in paths slashes are separators */
772
                   '%')) /* %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 */
773
                return false;
10✔
774

775
        return true;
776
}
777

778
bool ifname_valid_full(const char *p, IfnameValidFlags flags) {
145,272✔
779
        bool numeric = true;
145,272✔
780

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

785
        assert(!(flags & ~_IFNAME_VALID_ALL));
145,272✔
786

787
        if (isempty(p))
145,272✔
788
                return false;
789

790
        /* A valid ifindex? If so, it's valid iff IFNAME_VALID_NUMERIC is set */
791
        if (parse_ifindex(p) >= 0)
140,186✔
792
                return flags & IFNAME_VALID_NUMERIC;
57✔
793

794
        if (flags & IFNAME_VALID_ALTERNATIVE) {
140,129✔
795
                if (strlen(p) >= ALTIFNAMSIZ)
14,343✔
796
                        return false;
797
        } else {
798
                if (strlen(p) >= IFNAMSIZ)
125,786✔
799
                        return false;
800
        }
801

802
        if (dot_or_dot_dot(p))
140,122✔
803
                return false;
804

805
        /* Let's refuse "all" and "default" as interface name, to avoid collisions with the special sysctl
806
         * directories /proc/sys/net/{ipv4,ipv6}/conf/{all,default} */
807
        if (!FLAGS_SET(flags, IFNAME_VALID_SPECIAL) && STR_IN_SET(p, "all", "default"))
140,120✔
808
                return false;
×
809

810
        for (const char *t = p; *t; t++) {
641,455✔
811
                if (!ifname_valid_char(*t))
501,349✔
812
                        return false;
813

814
                numeric = numeric && ascii_isdigit(*t);
641,445✔
815
        }
816

817
        /* It's fully numeric but didn't parse as valid ifindex above? if so, it must be too large or zero or
818
         * so, let's refuse that. */
819
        if (numeric)
140,106✔
820
                return false;
2✔
821

822
        return true;
823
}
824

825
bool address_label_valid(const char *p) {
68✔
826

827
        if (isempty(p))
68✔
828
                return false;
829

830
        if (strlen(p) >= IFNAMSIZ)
68✔
831
                return false;
832

833
        while (*p) {
568✔
834
                if ((uint8_t) *p >= 127U)
500✔
835
                        return false;
836

837
                if ((uint8_t) *p <= 31U)
500✔
838
                        return false;
839
                p++;
500✔
840
        }
841

842
        return true;
843
}
844

845
int getpeercred(int fd, struct ucred *ucred) {
88,302✔
846
        socklen_t n = sizeof(struct ucred);
88,302✔
847
        struct ucred u;
88,302✔
848

849
        assert(fd >= 0);
88,302✔
850
        assert(ucred);
88,302✔
851

852
        if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n) < 0)
88,302✔
853
                return -errno;
×
854

855
        if (n != sizeof(struct ucred))
88,302✔
856
                return -EIO;
857

858
        /* Check if the data is actually useful and not suppressed due to namespacing issues */
859
        if (!pid_is_valid(u.pid))
88,302✔
860
                return -ENODATA;
861

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

865
        *ucred = u;
88,302✔
866
        return 0;
88,302✔
867
}
868

869
int getpeersec(int fd, char **ret) {
19,151✔
870
        _cleanup_free_ char *s = NULL;
38,302✔
871
        socklen_t n = 64;
19,151✔
872

873
        assert(fd >= 0);
19,151✔
874
        assert(ret);
19,151✔
875

876
        for (;;) {
19,151✔
877
                s = new0(char, n+1);
19,151✔
878
                if (!s)
19,151✔
879
                        return -ENOMEM;
880

881
                if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n) >= 0) {
19,151✔
882
                        s[n] = 0;
7,633✔
883
                        break;
7,633✔
884
                }
885

886
                if (errno != ERANGE)
11,518✔
887
                        return -errno;
11,518✔
888

889
                s = mfree(s);
×
890
        }
891

892
        if (isempty(s))
7,633✔
893
                return -EOPNOTSUPP;
894

895
        *ret = TAKE_PTR(s);
7,633✔
896

897
        return 0;
7,633✔
898
}
899

900
int getpeergroups(int fd, gid_t **ret) {
19,152✔
901
        socklen_t n = sizeof(gid_t) * 64U;
19,152✔
902
        _cleanup_free_ gid_t *d = NULL;
19,152✔
903

904
        assert(fd >= 0);
19,152✔
905
        assert(ret);
19,152✔
906

907
        long ngroups_max = sysconf(_SC_NGROUPS_MAX);
19,152✔
908
        if (ngroups_max > 0)
19,152✔
909
                n = MAX(n, sizeof(gid_t) * (socklen_t) ngroups_max);
19,152✔
910

911
        for (;;) {
19,152✔
912
                d = malloc(n);
19,152✔
913
                if (!d)
19,152✔
914
                        return -ENOMEM;
915

916
                if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
19,152✔
917
                        break;
918

919
                if (errno != ERANGE)
×
920
                        return -errno;
×
921

922
                d = mfree(d);
×
923
        }
924

925
        assert_se(n % sizeof(gid_t) == 0);
19,152✔
926
        n /= sizeof(gid_t);
19,152✔
927

928
        if (n > INT_MAX)
19,152✔
929
                return -E2BIG;
930

931
        *ret = TAKE_PTR(d);
19,152✔
932

933
        return (int) n;
19,152✔
934
}
935

936
int getpeerpidfd(int fd) {
19,665✔
937
        socklen_t n = sizeof(int);
19,665✔
938
        int pidfd = -EBADF;
19,665✔
939

940
        assert(fd >= 0);
19,665✔
941

942
        if (getsockopt(fd, SOL_SOCKET, SO_PEERPIDFD, &pidfd, &n) < 0)
19,665✔
UNCOV
943
                return -errno;
×
944

945
        if (n != sizeof(int))
19,665✔
946
                return -EIO;
947

948
        return pidfd;
19,665✔
949
}
950

951
int getpeerpidref(int fd, PidRef *ret) {
4✔
952
        int r;
4✔
953

954
        assert(fd >= 0);
4✔
955
        assert(ret);
4✔
956

957
        int pidfd = getpeerpidfd(fd);
4✔
958
        if (pidfd < 0) {
4✔
959
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(pidfd))
×
960
                        return pidfd;
×
961

962
                struct ucred ucred;
×
963
                r = getpeercred(fd, &ucred);
×
964
                if (r < 0)
×
965
                        return r;
966

967
                return pidref_set_pid(ret, ucred.pid);
×
968
        }
969

970
        return pidref_set_pidfd_consume(ret, pidfd);
4✔
971
}
972

973
ssize_t send_many_fds_iov_sa(
1✔
974
                int transport_fd,
975
                int *fds_array, size_t n_fds_array,
976
                const struct iovec *iov, size_t iovlen,
977
                const struct sockaddr *sa, socklen_t len,
978
                int flags) {
979

980
        _cleanup_free_ struct cmsghdr *cmsg = NULL;
1✔
981
        struct msghdr mh = {
1✔
982
                .msg_name = (struct sockaddr*) sa,
983
                .msg_namelen = len,
984
                .msg_iov = (struct iovec *)iov,
985
                .msg_iovlen = iovlen,
986
        };
987
        ssize_t k;
1✔
988

989
        assert(transport_fd >= 0);
1✔
990
        assert(fds_array || n_fds_array == 0);
1✔
991

992
        /* The kernel will reject sending more than SCM_MAX_FD FDs at once */
993
        if (n_fds_array > SCM_MAX_FD)
1✔
994
                return -E2BIG;
995

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

1000
        if (n_fds_array > 0) {
1✔
1001
                mh.msg_controllen = CMSG_SPACE(sizeof(int) * n_fds_array);
1✔
1002
                mh.msg_control = cmsg = malloc(mh.msg_controllen);
1✔
1003
                if (!cmsg)
1✔
1004
                        return -ENOMEM;
1005

1006
                *cmsg = (struct cmsghdr) {
1✔
1007
                        .cmsg_len = CMSG_LEN(sizeof(int) * n_fds_array),
1✔
1008
                        .cmsg_level = SOL_SOCKET,
1009
                        .cmsg_type = SCM_RIGHTS,
1010
                };
1011
                memcpy(CMSG_DATA(cmsg), fds_array, sizeof(int) * n_fds_array);
1✔
1012
        }
1013
        k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
1✔
1014
        if (k < 0)
1✔
1015
                return (ssize_t) -errno;
×
1016

1017
        return k;
1018
}
1019

1020
ssize_t send_one_fd_iov_sa(
884✔
1021
                int transport_fd,
1022
                int fd,
1023
                const struct iovec *iov, size_t iovlen,
1024
                const struct sockaddr *sa, socklen_t len,
1025
                int flags) {
1026

1027
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control = {};
884✔
1028
        struct msghdr mh = {
884✔
1029
                .msg_name = (struct sockaddr*) sa,
1030
                .msg_namelen = len,
1031
                .msg_iov = (struct iovec *)iov,
1032
                .msg_iovlen = iovlen,
1033
        };
1034
        ssize_t k;
884✔
1035

1036
        assert(transport_fd >= 0);
884✔
1037

1038
        /*
1039
         * We need either an FD or data to send.
1040
         * If there's nothing, return an error.
1041
         */
1042
        if (fd < 0 && !iov)
884✔
1043
                return -EINVAL;
884✔
1044

1045
        if (fd >= 0) {
883✔
1046
                struct cmsghdr *cmsg;
881✔
1047

1048
                mh.msg_control = &control;
881✔
1049
                mh.msg_controllen = sizeof(control);
881✔
1050

1051
                cmsg = CMSG_FIRSTHDR(&mh);
881✔
1052
                cmsg->cmsg_level = SOL_SOCKET;
881✔
1053
                cmsg->cmsg_type = SCM_RIGHTS;
881✔
1054
                cmsg->cmsg_len = CMSG_LEN(sizeof(int));
881✔
1055
                memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
881✔
1056
        }
1057
        k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
883✔
1058
        if (k < 0)
883✔
1059
                return (ssize_t) -errno;
×
1060

1061
        return k;
1062
}
1063

1064
int send_one_fd_sa(
7✔
1065
                int transport_fd,
1066
                int fd,
1067
                const struct sockaddr *sa, socklen_t len,
1068
                int flags) {
1069

1070
        assert(fd >= 0);
7✔
1071

1072
        return (int) send_one_fd_iov_sa(transport_fd, fd, NULL, 0, sa, len, flags);
7✔
1073
}
1074

1075
ssize_t receive_many_fds_iov(
1✔
1076
                int transport_fd,
1077
                struct iovec *iov, size_t iovlen,
1078
                int **ret_fds_array, size_t *ret_n_fds_array,
1079
                int flags) {
1080

1081
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * SCM_MAX_FD)) control;
1✔
1082
        struct msghdr mh = {
1✔
1083
                .msg_control = &control,
1084
                .msg_controllen = sizeof(control),
1085
                .msg_iov = iov,
1086
                .msg_iovlen = iovlen,
1087
        };
1088
        _cleanup_free_ int *fds_array = NULL;
1✔
1089
        size_t n_fds_array = 0;
1✔
1090
        struct cmsghdr *cmsg;
1✔
1091
        ssize_t k;
1✔
1092

1093
        assert(transport_fd >= 0);
1✔
1094
        assert(ret_fds_array);
1✔
1095
        assert(ret_n_fds_array);
1✔
1096

1097
        /*
1098
         * Receive many FDs via @transport_fd. We don't care for the transport-type. We retrieve all the FDs
1099
         * at once. This is best used in combination with send_many_fds().
1100
         */
1101

1102
        k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
1✔
1103
        if (k < 0)
1✔
1104
                return k;
1105

1106
        CMSG_FOREACH(cmsg, &mh)
4✔
1107
                if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1✔
1108
                        size_t n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1✔
1109

1110
                        if (!GREEDY_REALLOC_APPEND(fds_array, n_fds_array, CMSG_TYPED_DATA(cmsg, int), n)) {
1✔
1111
                                cmsg_close_all(&mh);
×
1112
                                return -ENOMEM;
1113
                        }
1114
                }
1115

1116
        if (n_fds_array == 0) {
1✔
1117
                cmsg_close_all(&mh);
×
1118

1119
                /* If didn't receive an FD or any data, return an error. */
1120
                if (k == 0)
×
1121
                        return -EIO;
1122
        }
1123

1124
        *ret_fds_array = TAKE_PTR(fds_array);
1✔
1125
        *ret_n_fds_array = n_fds_array;
1✔
1126

1127
        return k;
1✔
1128
}
1129

1130
int receive_many_fds(int transport_fd, int **ret_fds_array, size_t *ret_n_fds_array, int flags) {
×
1131
        ssize_t k;
×
1132

1133
        k = receive_many_fds_iov(transport_fd, NULL, 0, ret_fds_array, ret_n_fds_array, flags);
×
1134
        if (k == 0)
×
1135
                return 0;
1136

1137
        /* k must be negative, since receive_many_fds_iov() only returns a positive value if data was received
1138
         * through the iov. */
1139
        assert(k < 0);
×
1140
        return (int) k;
×
1141
}
1142

1143
ssize_t receive_one_fd_iov(
5,333✔
1144
                int transport_fd,
1145
                struct iovec *iov, size_t iovlen,
1146
                int flags,
1147
                int *ret_fd) {
1148

1149
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
5,333✔
1150
        struct msghdr mh = {
5,333✔
1151
                .msg_control = &control,
1152
                .msg_controllen = sizeof(control),
1153
                .msg_iov = iov,
1154
                .msg_iovlen = iovlen,
1155
        };
1156
        struct cmsghdr *found;
5,333✔
1157
        ssize_t k;
5,333✔
1158

1159
        assert(transport_fd >= 0);
5,333✔
1160
        assert(ret_fd);
5,333✔
1161

1162
        /*
1163
         * Receive a single FD via @transport_fd. We don't care for
1164
         * the transport-type. We retrieve a single FD at most, so for
1165
         * packet-based transports, the caller must ensure to send
1166
         * only a single FD per packet.  This is best used in
1167
         * combination with send_one_fd().
1168
         */
1169

1170
        k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
5,333✔
1171
        if (k < 0)
5,333✔
1172
                return k;
5,333✔
1173

1174
        found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
5,165✔
1175
        if (!found) {
5,165✔
1176
                cmsg_close_all(&mh);
1,542✔
1177

1178
                /* If didn't receive an FD or any data, return an error. */
1179
                if (k == 0)
1,542✔
1180
                        return -EIO;
1181
        }
1182

1183
        if (found)
3,624✔
1184
                *ret_fd = *CMSG_TYPED_DATA(found, int);
3,623✔
1185
        else
1186
                *ret_fd = -EBADF;
1✔
1187

1188
        return k;
1189
}
1190

1191
int receive_one_fd(int transport_fd, int flags) {
839✔
1192
        int fd;
839✔
1193
        ssize_t k;
839✔
1194

1195
        k = receive_one_fd_iov(transport_fd, NULL, 0, flags, &fd);
839✔
1196
        if (k == 0)
839✔
1197
                return fd;
758✔
1198

1199
        /* k must be negative, since receive_one_fd_iov() only returns
1200
         * a positive value if data was received through the iov. */
1201
        assert(k < 0);
81✔
1202
        return (int) k;
81✔
1203
}
1204

1205
ssize_t next_datagram_size_fd(int fd) {
202,582✔
1206
        ssize_t l;
202,582✔
1207
        int k;
202,582✔
1208

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

1215
        l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
202,582✔
1216
        if (l < 0) {
202,582✔
1217
                if (IN_SET(errno, EOPNOTSUPP, EFAULT))
629✔
1218
                        goto fallback;
×
1219

1220
                return -errno;
629✔
1221
        }
1222
        if (l == 0)
201,953✔
1223
                goto fallback;
71✔
1224

1225
        return l;
1226

1227
fallback:
71✔
1228
        k = 0;
71✔
1229

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

1233
        if (ioctl(fd, FIONREAD, &k) < 0)
71✔
1234
                return -errno;
×
1235

1236
        return (ssize_t) k;
71✔
1237
}
1238

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

1243
int flush_accept(int fd) {
12✔
1244

1245
        int r, b;
12✔
1246
        socklen_t l = sizeof(b);
12✔
1247

1248
        /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1249
         * them. */
1250

1251
        if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
12✔
1252
                return -errno;
×
1253

1254
        assert(l == sizeof(b));
12✔
1255
        if (!b) /* Let's check if this socket accepts connections before calling accept(). accept4() can
12✔
1256
                 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
1257
                 * error, or in case the incoming TCP connection triggered a network issue, which we want to
1258
                 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
1259
                 * we can loop safely on transient errors below. */
1260
                return -ENOTTY;
1261

1262
        for (unsigned iteration = 0;; iteration++) {
2✔
1263
                int cfd;
6✔
1264

1265
                r = fd_wait_for_event(fd, POLLIN, 0);
6✔
1266
                if (r == -EINTR)
6✔
1267
                        continue;
×
1268
                if (r < 0)
6✔
1269
                        return r;
1270
                if (r == 0)
6✔
1271
                        return 0;
1272

1273
                if (iteration >= MAX_FLUSH_ITERATIONS)
2✔
1274
                        return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
×
1275
                                               "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS) " iterations.");
1276

1277
                cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
2✔
1278
                if (cfd < 0) {
2✔
1279
                        if (errno == EAGAIN)
×
1280
                                return 0;
1281

1282
                        if (ERRNO_IS_ACCEPT_AGAIN(errno))
×
1283
                                continue;
×
1284

1285
                        return -errno;
×
1286
                }
1287

1288
                safe_close(cfd);
2✔
1289
        }
1290
}
1291

1292
ssize_t flush_mqueue(int fd) {
×
1293
        _cleanup_free_ char *buf = NULL;
×
1294
        struct mq_attr attr;
×
1295
        ssize_t count = 0;
×
1296
        int r;
×
1297

1298
        assert(fd >= 0);
×
1299

1300
        /* Similar to flush_fd() but flushes all messages from a POSIX message queue. */
1301

1302
        for (;;) {
×
1303
                ssize_t l;
×
1304

1305
                r = fd_wait_for_event(fd, POLLIN, /* timeout= */ 0);
×
1306
                if (r == -EINTR)
×
1307
                        continue;
×
1308
                if (r < 0)
×
1309
                        return r;
×
1310
                if (r == 0)
×
1311
                        return count;
1312

1313
                if (!buf) {
×
1314
                        /* Buffer must be at least as large as mq_msgsize. */
1315
                        if (mq_getattr(fd, &attr) < 0)
×
1316
                                return -errno;
×
1317

1318
                        buf = malloc(attr.mq_msgsize);
×
1319
                        if (!buf)
×
1320
                                return -ENOMEM;
1321
                }
1322

1323
                l = mq_receive(fd, buf, attr.mq_msgsize, /* msg_prio= */ NULL);
×
1324
                if (l < 0) {
×
1325
                        if (errno == EINTR)
×
1326
                                continue;
×
1327

1328
                        if (errno == EAGAIN)
×
1329
                                return count;
1330

1331
                        return -errno;
×
1332
                }
1333

1334
                count += l;
×
1335
        }
1336
}
1337

1338
struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
404,698✔
1339
        struct cmsghdr *cmsg;
404,698✔
1340

1341
        assert(mh);
404,698✔
1342

1343
        CMSG_FOREACH(cmsg, mh)
810,014✔
1344
                if (cmsg->cmsg_level == level &&
364,160✔
1345
                    cmsg->cmsg_type == type &&
363,851✔
1346
                    (length == (socklen_t) -1 || length == cmsg->cmsg_len))
363,263✔
1347
                        return cmsg;
1348

1349
        return NULL;
1350
}
1351

1352
void* cmsg_find_and_copy_data(struct msghdr *mh, int level, int type, void *buf, size_t buf_len) {
347✔
1353
        struct cmsghdr *cmsg;
347✔
1354

1355
        assert(mh);
347✔
1356
        assert(buf);
347✔
1357
        assert(buf_len > 0);
347✔
1358

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

1363
        cmsg = cmsg_find(mh, level, type, CMSG_LEN(buf_len));
347✔
1364
        if (!cmsg)
347✔
1365
                return NULL;
1366

1367
        return memcpy_safe(buf, CMSG_DATA(cmsg), buf_len);
340✔
1368
}
1369

1370
size_t sockaddr_ll_len(const struct sockaddr_ll *sa) {
359✔
1371
        /* Certain hardware address types (e.g Infiniband) do not fit into sll_addr
1372
         * (8 bytes) and run over the structure. This function returns the correct size that
1373
         * must be passed to kernel. */
1374

1375
        assert(sa->sll_family == AF_PACKET);
359✔
1376

1377
        size_t mac_len = sizeof(sa->sll_addr);
359✔
1378

1379
        if (be16toh(sa->sll_hatype) == ARPHRD_ETHER)
359✔
1380
                mac_len = MAX(mac_len, (size_t) ETH_ALEN);
359✔
1381
        if (be16toh(sa->sll_hatype) == ARPHRD_INFINIBAND)
359✔
1382
                mac_len = MAX(mac_len, (size_t) INFINIBAND_ALEN);
×
1383

1384
        return offsetof(struct sockaddr_ll, sll_addr) + mac_len;
359✔
1385
}
1386

1387
size_t sockaddr_un_len(const struct sockaddr_un *sa) {
2,636✔
1388
        /* Covers only file system and abstract AF_UNIX socket addresses, but not unnamed socket addresses. */
1389

1390
        assert(sa->sun_family == AF_UNIX);
2,636✔
1391

1392
        return offsetof(struct sockaddr_un, sun_path) +
7,908✔
1393
                (sa->sun_path[0] == 0 ?
2,636✔
1394
                        1 + strnlen(sa->sun_path+1, sizeof(sa->sun_path)-1) :
686✔
1395
                        strnlen(sa->sun_path, sizeof(sa->sun_path))+1);
1,950✔
1396
}
1397

1398
size_t sockaddr_len(const union sockaddr_union *sa) {
206✔
1399
        switch (sa->sa.sa_family) {
206✔
1400
        case AF_INET:
1401
                return sizeof(struct sockaddr_in);
1402
        case AF_INET6:
56✔
1403
                return sizeof(struct sockaddr_in6);
56✔
1404
        case AF_UNIX:
3✔
1405
                return sockaddr_un_len(&sa->un);
3✔
1406
        case AF_PACKET:
×
1407
                return sockaddr_ll_len(&sa->ll);
×
1408
        case AF_NETLINK:
×
1409
                return sizeof(struct sockaddr_nl);
×
1410
        case AF_VSOCK:
1411
                return sizeof(struct sockaddr_vm);
1412
        default:
×
1413
                assert_not_reached();
×
1414
        }
1415
}
1416

1417
int socket_ioctl_fd(void) {
5,160✔
1418
        int fd;
5,160✔
1419

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

1425
        fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5,160✔
1426
        if (fd < 0)
5,160✔
1427
                fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
×
1428
        if (fd < 0)
×
1429
                return -errno;
×
1430

1431
        return fd;
1432
}
1433

1434
int sockaddr_un_unlink(const struct sockaddr_un *sa) {
1,492✔
1435
        const char *p, * nul;
1,492✔
1436

1437
        assert(sa);
1,492✔
1438

1439
        if (sa->sun_family != AF_UNIX)
1,492✔
1440
                return -EPROTOTYPE;
1441

1442
        if (sa->sun_path[0] == 0) /* Nothing to do for abstract sockets */
1,492✔
1443
                return 0;
1444

1445
        /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1446
        nul = memchr(sa->sun_path, 0, sizeof(sa->sun_path));
1,492✔
1447
        if (nul)
1,492✔
1448
                p = sa->sun_path;
1449
        else
1450
                p = memdupa_suffix0(sa->sun_path, sizeof(sa->sun_path));
×
1451

1452
        if (unlink(p) < 0)
1,492✔
1453
                return -errno;
1,128✔
1454

1455
        return 1;
1456
}
1457

1458
int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path) {
415,735✔
1459
        size_t l;
415,735✔
1460

1461
        assert(ret);
415,735✔
1462
        assert(path);
415,735✔
1463

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

1469
        l = strlen(path);
415,735✔
1470
        if (l < 2)
415,735✔
1471
                return -EINVAL;
1472
        if (!IN_SET(path[0], '/', '@'))
415,734✔
1473
                return -EINVAL;
1474

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

1485
        *ret = (struct sockaddr_un) {
415,732✔
1486
                .sun_family = AF_UNIX,
1487
        };
1488

1489
        if (path[0] == '@') {
415,732✔
1490
                /* Abstract namespace socket */
1491
                memcpy(ret->sun_path + 1, path + 1, l); /* copy *with* trailing NUL byte */
211,368✔
1492
                return (int) (offsetof(struct sockaddr_un, sun_path) + l); /* 🔥 *don't* 🔥 include trailing NUL in size */
211,368✔
1493

1494
        } else {
1495
                assert(path[0] == '/');
204,364✔
1496

1497
                /* File system socket */
1498
                memcpy(ret->sun_path, path, l + 1); /* copy *with* trailing NUL byte */
204,364✔
1499
                return (int) (offsetof(struct sockaddr_un, sun_path) + l + 1); /* include trailing NUL in size */
204,364✔
1500
        }
1501
}
1502

1503
int getsockopt_int(int fd, int level, int optname, int *ret) {
15,492✔
1504
        int v;
15,492✔
1505
        socklen_t sl = sizeof(v);
15,492✔
1506

1507
        assert(fd >= 0);
15,492✔
1508
        assert(ret);
15,492✔
1509

1510
        if (getsockopt(fd, level, optname, &v, &sl) < 0)
15,492✔
1511
                return negative_errno();
58✔
1512
        if (sl != sizeof(v))
15,434✔
1513
                return -EIO;
1514

1515
        *ret = v;
15,434✔
1516
        return 0;
15,434✔
1517
}
1518

1519
int socket_bind_to_ifname(int fd, const char *ifname) {
1✔
1520
        assert(fd >= 0);
1✔
1521

1522
        /* Call with NULL to drop binding */
1523

1524
        return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen_ptr(ifname)));
2✔
1525
}
1526

1527
int socket_bind_to_ifindex(int fd, int ifindex) {
843✔
1528
        assert(fd >= 0);
843✔
1529

1530
        if (ifindex <= 0)
843✔
1531
                /* Drop binding */
1532
                return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, NULL, 0));
58✔
1533

1534
        return setsockopt_int(fd, SOL_SOCKET, SO_BINDTOIFINDEX, ifindex);
785✔
1535
}
1536

1537
int socket_autobind(int fd, char **ret_name) {
260✔
1538
        _cleanup_free_ char *name = NULL;
260✔
1539
        uint64_t random;
260✔
1540
        int r;
260✔
1541

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

1545
        assert(fd >= 0);
260✔
1546

1547
        random = random_u64();
260✔
1548

1549
        if (asprintf(&name, "@%" PRIu64, random) < 0)
260✔
1550
                return -ENOMEM;
1551

1552
        union sockaddr_union sa;
260✔
1553
        assert_cc(DECIMAL_STR_MAX(uint64_t) < sizeof(sa.un.sun_path));
260✔
1554

1555
        r = sockaddr_un_set_path(&sa.un, name);
260✔
1556
        if (r < 0)
260✔
1557
                return r;
1558

1559
        if (bind(fd, &sa.sa, r) < 0)
260✔
1560
                return -errno;
×
1561

1562
        if (ret_name)
260✔
1563
                *ret_name = TAKE_PTR(name);
258✔
1564
        return 0;
1565
}
1566

1567
ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags) {
3,563,988✔
1568
        ssize_t n;
3,563,988✔
1569

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

1575
        assert(sockfd >= 0);
3,563,988✔
1576
        assert(msg);
3,563,988✔
1577

1578
        n = recvmsg(sockfd, msg, flags);
3,563,988✔
1579
        if (n < 0)
3,563,988✔
1580
                return -errno;
347,691✔
1581

1582
        if (FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ||
3,216,297✔
1583
            (!FLAGS_SET(flags, MSG_PEEK) && FLAGS_SET(msg->msg_flags, MSG_TRUNC))) {
3,216,297✔
1584
                cmsg_close_all(msg);
×
1585
                return FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ? -ECHRNG : -EXFULL;
×
1586
        }
1587

1588
        return n;
1589
}
1590

1591
int socket_get_family(int fd) {
121,734✔
1592
        int af;
121,734✔
1593
        socklen_t sl = sizeof(af);
121,734✔
1594

1595
        if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &af, &sl) < 0)
121,734✔
1596
                return -errno;
×
1597

1598
        if (sl != sizeof(af))
121,734✔
1599
                return -EINVAL;
1600

1601
        return af;
121,734✔
1602
}
1603

1604
int socket_set_recvpktinfo(int fd, int af, bool b) {
13,410✔
1605

1606
        if (af == AF_UNSPEC) {
13,410✔
1607
                af = socket_get_family(fd);
×
1608
                if (af < 0)
×
1609
                        return af;
1610
        }
1611

1612
        switch (af) {
13,410✔
1613

1614
        case AF_INET:
7,127✔
1615
                return setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, b);
7,127✔
1616

1617
        case AF_INET6:
6,234✔
1618
                return setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, b);
6,234✔
1619

1620
        case AF_NETLINK:
49✔
1621
                return setsockopt_int(fd, SOL_NETLINK, NETLINK_PKTINFO, b);
49✔
1622

1623
        case AF_PACKET:
×
1624
                return setsockopt_int(fd, SOL_PACKET, PACKET_AUXDATA, b);
×
1625

1626
        default:
1627
                return -EAFNOSUPPORT;
1628
        }
1629
}
1630

1631
int socket_set_unicast_if(int fd, int af, int ifi) {
120✔
1632
        be32_t ifindex_be = htobe32(ifi);
120✔
1633

1634
        if (af == AF_UNSPEC) {
120✔
1635
                af = socket_get_family(fd);
×
1636
                if (af < 0)
×
1637
                        return af;
120✔
1638
        }
1639

1640
        switch (af) {
120✔
1641

1642
        case AF_INET:
86✔
1643
                return RET_NERRNO(setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
86✔
1644

1645
        case AF_INET6:
34✔
1646
                return RET_NERRNO(setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
34✔
1647

1648
        default:
1649
                return -EAFNOSUPPORT;
1650
        }
1651
}
1652

1653
int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val) {
26,565✔
1654
        if (af == AF_UNSPEC) {
26,565✔
1655
                af = socket_get_family(fd);
×
1656
                if (af < 0)
×
1657
                        return af;
1658
        }
1659

1660
        switch (af) {
26,565✔
1661

1662
        case AF_INET:
14,090✔
1663
                return setsockopt_int(fd, IPPROTO_IP, opt_ipv4, val);
14,090✔
1664

1665
        case AF_INET6:
12,475✔
1666
                return setsockopt_int(fd, IPPROTO_IPV6, opt_ipv6, val);
12,475✔
1667

1668
        default:
1669
                return -EAFNOSUPPORT;
1670
        }
1671
}
1672

1673
int socket_get_mtu(int fd, int af, size_t *ret) {
818✔
1674
        int mtu, r;
818✔
1675

1676
        if (af == AF_UNSPEC) {
818✔
1677
                af = socket_get_family(fd);
×
1678
                if (af < 0)
×
1679
                        return af;
818✔
1680
        }
1681

1682
        switch (af) {
818✔
1683

1684
        case AF_INET:
359✔
1685
                r = getsockopt_int(fd, IPPROTO_IP, IP_MTU, &mtu);
359✔
1686
                break;
1687

1688
        case AF_INET6:
459✔
1689
                r = getsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, &mtu);
459✔
1690
                break;
1691

1692
        default:
1693
                return -EAFNOSUPPORT;
1694
        }
1695

1696
        if (r < 0)
818✔
1697
                return r;
1698
        if (mtu <= 0)
760✔
1699
                return -EINVAL;
1700

1701
        *ret = (size_t) mtu;
760✔
1702
        return 0;
760✔
1703
}
1704

1705
static int connect_unix_path_simple(int fd, const char *path) {
178,465✔
1706
        union sockaddr_union sa = {
178,465✔
1707
                .un.sun_family = AF_UNIX,
1708
        };
1709
        size_t l;
178,465✔
1710

1711
        assert(fd >= 0);
178,465✔
1712
        assert(path);
178,465✔
1713

1714
        l = strlen(path);
178,465✔
1715
        assert(l > 0);
178,465✔
1716
        assert(l < sizeof(sa.un.sun_path));
178,465✔
1717

1718
        memcpy(sa.un.sun_path, path, l + 1);
178,465✔
1719
        return RET_NERRNO(connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + l + 1));
178,465✔
1720
}
1721

1722
static int connect_unix_inode(int fd, int inode_fd) {
14✔
1723
        assert(fd >= 0);
14✔
1724
        assert(inode_fd >= 0);
14✔
1725

1726
        return connect_unix_path_simple(fd, FORMAT_PROC_FD_PATH(inode_fd));
14✔
1727
}
1728

1729
int connect_unix_path(int fd, int dir_fd, const char *path) {
178,465✔
1730
        _cleanup_close_ int inode_fd = -EBADF;
178,465✔
1731

1732
        assert(fd >= 0);
178,465✔
1733
        assert(dir_fd == AT_FDCWD || dir_fd >= 0);
178,465✔
1734

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

1738
        if (!path)
178,465✔
1739
                return connect_unix_inode(fd, dir_fd); /* If no path is specified, then dir_fd refers to the socket inode to connect to. */
1✔
1740

1741
        /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
1742
         * namespace path, since first char is NUL */
1743
        if (isempty(path))
356,929✔
1744
                return -EINVAL;
1745

1746
        /* Shortcut for the simple case */
1747
        if (dir_fd == AT_FDCWD && strlen(path) < sizeof_field(struct sockaddr_un, sun_path))
178,464✔
1748
                return connect_unix_path_simple(fd, path);
178,451✔
1749

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

1754
        inode_fd = openat(dir_fd, path, O_PATH|O_CLOEXEC);
13✔
1755
        if (inode_fd < 0)
13✔
1756
                return -errno;
×
1757

1758
        return connect_unix_inode(fd, inode_fd);
13✔
1759
}
1760

1761
int socket_address_parse_unix(SocketAddress *ret_address, const char *s) {
220,224✔
1762
        struct sockaddr_un un;
220,224✔
1763
        int r;
220,224✔
1764

1765
        assert(ret_address);
220,224✔
1766
        assert(s);
220,224✔
1767

1768
        if (!IN_SET(*s, '/', '@'))
220,224✔
1769
                return -EPROTO;
220,224✔
1770

1771
        r = sockaddr_un_set_path(&un, s);
219,718✔
1772
        if (r < 0)
219,718✔
1773
                return r;
1774

1775
        *ret_address = (SocketAddress) {
219,716✔
1776
                .sockaddr.un = un,
1777
                .size = r,
1778
        };
1779

1780
        return 0;
219,716✔
1781
}
1782

1783
int socket_address_equal_unix(const char *a, const char *b) {
652✔
1784
        SocketAddress socket_a, socket_b;
652✔
1785
        int r;
652✔
1786

1787
        assert(a);
652✔
1788
        assert(b);
652✔
1789

1790
        r = socket_address_parse_unix(&socket_a, a);
652✔
1791
        if (r < 0)
652✔
1792
                return r;
652✔
1793

1794
        r = socket_address_parse_unix(&socket_b, b);
652✔
1795
        if (r < 0)
652✔
1796
                return r;
1797

1798
        return sockaddr_equal(&socket_a.sockaddr, &socket_b.sockaddr);
652✔
1799
}
1800

1801
int vsock_parse_port(const char *s, unsigned *ret) {
435✔
1802
        int r;
435✔
1803

1804
        assert(ret);
435✔
1805

1806
        if (!s)
435✔
1807
                return -EINVAL;
435✔
1808

1809
        unsigned u;
435✔
1810
        r = safe_atou(s, &u);
435✔
1811
        if (r < 0)
435✔
1812
                return r;
1813

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

1817
        if (u == VMADDR_PORT_ANY)
432✔
1818
                return -EINVAL;
1819

1820
        *ret = u;
432✔
1821
        return 0;
432✔
1822
}
1823

1824
int vsock_parse_cid(const char *s, unsigned *ret) {
390✔
1825
        assert(ret);
390✔
1826

1827
        if (!s)
390✔
1828
                return -EINVAL;
1829

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

1833
        if (streq(s, "hypervisor"))
390✔
1834
                *ret = VMADDR_CID_HYPERVISOR;
×
1835
        else if (streq(s, "local"))
390✔
1836
                *ret = VMADDR_CID_LOCAL;
×
1837
        else if (streq(s, "host"))
390✔
1838
                *ret = VMADDR_CID_HOST;
×
1839
        else
1840
                return safe_atou(s, ret);
390✔
1841

1842
        return 0;
1843
}
1844

1845
int socket_address_parse_vsock(SocketAddress *ret_address, const char *s) {
506✔
1846
        /* AF_VSOCK socket in vsock:cid:port notation */
1847
        _cleanup_free_ char *n = NULL;
506✔
1848
        const char *e, *cid_start;
506✔
1849
        unsigned port, cid;
506✔
1850
        int type, r;
506✔
1851

1852
        assert(ret_address);
506✔
1853
        assert(s);
506✔
1854

1855
        if ((cid_start = startswith(s, "vsock:")))
506✔
1856
                type = 0;
1857
        else if ((cid_start = startswith(s, "vsock-dgram:")))
449✔
1858
                type = SOCK_DGRAM;
1859
        else if ((cid_start = startswith(s, "vsock-seqpacket:")))
449✔
1860
                type = SOCK_SEQPACKET;
1861
        else if ((cid_start = startswith(s, "vsock-stream:")))
449✔
1862
                type = SOCK_STREAM;
1863
        else
1864
                return -EPROTO;
1865

1866
        e = strchr(cid_start, ':');
437✔
1867
        if (!e)
437✔
1868
                return -EINVAL;
1869

1870
        r = vsock_parse_port(e+1, &port);
435✔
1871
        if (r < 0)
435✔
1872
                return r;
1873

1874
        n = strndup(cid_start, e - cid_start);
432✔
1875
        if (!n)
432✔
1876
                return -ENOMEM;
1877

1878
        if (isempty(n))
432✔
1879
                cid = VMADDR_CID_ANY;
42✔
1880
        else {
1881
                r = vsock_parse_cid(n, &cid);
390✔
1882
                if (r < 0)
390✔
1883
                        return r;
1884
        }
1885

1886
        *ret_address = (SocketAddress) {
429✔
1887
                .sockaddr.vm = {
1888
                        .svm_family = AF_VSOCK,
1889
                        .svm_cid = cid,
1890
                        .svm_port = port,
1891
                },
1892
                .type = type,
1893
                .size = sizeof(struct sockaddr_vm),
1894
        };
1895

1896
        return 0;
429✔
1897
}
1898

1899
int vsock_get_local_cid(unsigned *ret) {
84✔
1900
        _cleanup_close_ int vsock_fd = -EBADF;
84✔
1901

1902
        vsock_fd = open("/dev/vsock", O_RDONLY|O_CLOEXEC);
84✔
1903
        if (vsock_fd < 0)
84✔
1904
                return log_debug_errno(errno, "Failed to open %s: %m", "/dev/vsock");
16✔
1905

1906
        unsigned tmp;
68✔
1907
        if (ioctl(vsock_fd, IOCTL_VM_SOCKETS_GET_LOCAL_CID, &tmp) < 0)
68✔
1908
                return log_debug_errno(errno, "Failed to query local AF_VSOCK CID: %m");
×
1909
        log_debug("Local AF_VSOCK CID: %u", tmp);
68✔
1910

1911
        /* If ret == NULL, we're just want to check if AF_VSOCK is available, so accept
1912
         * any address. Otherwise, filter out special addresses that are cannot be used
1913
         * to identify _this_ machine from the outside. */
1914
        if (ret && IN_SET(tmp, VMADDR_CID_LOCAL, VMADDR_CID_HOST))
68✔
1915
                return log_debug_errno(SYNTHETIC_ERRNO(EADDRNOTAVAIL),
×
1916
                                       "IOCTL_VM_SOCKETS_GET_LOCAL_CID returned special value (%u), ignoring.", tmp);
1917

1918
        if (ret)
65✔
1919
                *ret = tmp;
65✔
1920
        return 0;
1921
}
1922

1923
int netlink_socket_get_multicast_groups(int fd, size_t *ret_len, uint32_t **ret_groups) {
14,674✔
1924
        _cleanup_free_ uint32_t *groups = NULL;
29,348✔
1925
        socklen_t len = 0, old_len;
14,674✔
1926

1927
        assert(fd >= 0);
14,674✔
1928

1929
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, NULL, &len) < 0)
14,674✔
1930
                return -errno;
×
1931

1932
        if (len == 0)
14,674✔
1933
                goto finalize;
14,202✔
1934

1935
        groups = new0(uint32_t, len);
472✔
1936
        if (!groups)
472✔
1937
                return -ENOMEM;
1938

1939
        old_len = len;
472✔
1940

1941
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, groups, &len) < 0)
472✔
1942
                return -errno;
×
1943

1944
        if (old_len != len)
472✔
1945
                return -EIO;
1946

1947
finalize:
472✔
1948
        if (ret_len)
14,674✔
1949
                *ret_len = len;
14,674✔
1950
        if (ret_groups)
14,674✔
1951
                *ret_groups = TAKE_PTR(groups);
14,674✔
1952

1953
        return 0;
1954
}
1955

1956
int socket_get_cookie(int fd, uint64_t *ret) {
391✔
1957
        assert(fd >= 0);
391✔
1958

1959
        uint64_t cookie = 0;
391✔
1960
        socklen_t cookie_len = sizeof(cookie);
391✔
1961
        if (getsockopt(fd, SOL_SOCKET, SO_COOKIE, &cookie, &cookie_len) < 0)
391✔
1962
                return -errno;
×
1963

1964
        assert(cookie_len == sizeof(cookie));
391✔
1965
        if (ret)
391✔
1966
                *ret = cookie;
391✔
1967

1968
        return 0;
1969
}
1970

1971
void cmsg_close_all(struct msghdr *mh) {
104,256✔
1972
        assert(mh);
104,256✔
1973

1974
        struct cmsghdr *cmsg;
104,256✔
1975
        CMSG_FOREACH(cmsg, mh) {
338,326✔
1976
                if (cmsg->cmsg_level != SOL_SOCKET)
64,907✔
1977
                        continue;
×
1978

1979
                if (cmsg->cmsg_type == SCM_RIGHTS)
64,907✔
1980
                        close_many(CMSG_TYPED_DATA(cmsg, int),
×
1981
                                   (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
×
1982
                else if (cmsg->cmsg_type == SCM_PIDFD) {
64,907✔
1983
                        assert(cmsg->cmsg_len == CMSG_LEN(sizeof(int)));
×
1984
                        safe_close(*CMSG_TYPED_DATA(cmsg, int));
×
1985
                }
1986
        }
1987
}
104,256✔
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