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

systemd / systemd / 27483642751

13 Jun 2026 05:24PM UTC coverage: 73.015% (+0.1%) from 72.886%
27483642751

push

github

web-flow
Assorted fixes (#40987)

5 of 10 new or added lines in 5 files covered. (50.0%)

98 existing lines in 29 files now uncovered.

337718 of 462535 relevant lines covered (73.01%)

1289337.57 hits per line

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

83.25
/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 <linux/if_ether.h>
7
#include <linux/if_infiniband.h>
8
#include <linux/pkt_sched.h>
9
#include <mqueue.h>
10
#include <net/if.h>
11
#include <netdb.h>
12
#include <netinet/ip.h>
13
#include <poll.h>
14
#include <stdio.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 "format-ifname.h"
23
#include "format-util.h"
24
#include "in-addr-util.h"
25
#include "io-util.h"
26
#include "log.h"
27
#include "memory-util.h"
28
#include "parse-util.h"
29
#include "path-util.h"
30
#include "pidref.h"
31
#include "process-util.h"
32
#include "random-util.h"
33
#include "socket-util.h"
34
#include "sparse-endian.h"
35
#include "string-table.h"
36
#include "string-util.h"
37
#include "strv.h"
38
#include "sysctl-util.h"
39

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

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

55
DEFINE_STRING_TABLE_LOOKUP(socket_address_type, int);
1✔
56

57
int socket_address_verify(const SocketAddress *a, bool strict) {
24,666✔
58
        assert(a);
24,666✔
59

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

63
        switch (socket_address_family(a)) {
24,666✔
64

65
        case AF_INET:
27✔
66
                if (a->size != sizeof(struct sockaddr_in))
27✔
67
                        return -EINVAL;
68

69
                if (a->sockaddr.in.sin_port == 0)
27✔
70
                        return -EINVAL;
71

72
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
27✔
73
                        return -EINVAL;
1✔
74

75
                return 0;
76

77
        case AF_INET6:
33✔
78
                if (a->size != sizeof(struct sockaddr_in6))
33✔
79
                        return -EINVAL;
80

81
                if (a->sockaddr.in6.sin6_port == 0)
33✔
82
                        return -EINVAL;
83

84
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
33✔
85
                        return -EINVAL;
×
86

87
                return 0;
88

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

97
                if (a->size > offsetof(struct sockaddr_un, sun_path) &&
23,746✔
98
                    a->sockaddr.un.sun_path[0] != 0 &&
23,746✔
99
                    strict) {
100
                        /* Only validate file system sockets here, and only in strict mode */
101
                        const char *e;
4,188✔
102

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

118
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET))
23,746✔
119
                        return -EINVAL;
×
120

121
                return 0;
122

123
        case AF_NETLINK:
764✔
124

125
                if (a->size != sizeof(struct sockaddr_nl))
764✔
126
                        return -EINVAL;
127

128
                if (!IN_SET(a->type, 0, SOCK_RAW, SOCK_DGRAM))
764✔
129
                        return -EINVAL;
×
130

131
                return 0;
132

133
        case AF_VSOCK:
79✔
134
                if (a->size != sizeof(struct sockaddr_vm))
79✔
135
                        return -EINVAL;
136

137
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
79✔
138
                        return -EINVAL;
×
139

140
                return 0;
141

142
        default:
143
                return -EAFNOSUPPORT;
144
        }
145
}
146

147
int socket_address_print(const SocketAddress *a, char **ret) {
6,990✔
148
        int r;
6,990✔
149

150
        assert(a);
6,990✔
151
        assert(ret);
6,990✔
152

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

160
        if (socket_address_family(a) == AF_NETLINK) {
6,990✔
161
                _cleanup_free_ char *sfamily = NULL;
278✔
162

163
                r = netlink_family_to_string_alloc(a->protocol, &sfamily);
278✔
164
                if (r < 0)
278✔
165
                        return r;
166

167
                r = asprintf(ret, "%s %u", sfamily, a->sockaddr.nl.nl_groups);
278✔
168
                if (r < 0)
278✔
169
                        return -ENOMEM;
170

171
                return 0;
278✔
172
        }
173

174
        return sockaddr_pretty(&a->sockaddr.sa, a->size, false, true, ret);
6,712✔
175
}
176

177
bool socket_address_can_accept(const SocketAddress *a) {
13,836✔
178
        assert(a);
13,836✔
179

180
        return
13,836✔
181
                IN_SET(a->type, SOCK_STREAM, SOCK_SEQPACKET);
13,836✔
182
}
183

184
bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) {
6,674✔
185
        assert(a);
6,674✔
186
        assert(b);
6,674✔
187

188
        /* Invalid addresses are unequal to all */
189
        if (socket_address_verify(a, false) < 0 ||
13,348✔
190
            socket_address_verify(b, false) < 0)
6,674✔
191
                return false;
192

193
        if (a->type != b->type)
6,673✔
194
                return false;
195

196
        if (socket_address_family(a) != socket_address_family(b))
6,672✔
197
                return false;
198

199
        switch (socket_address_family(a)) {
6,670✔
200

201
        case AF_INET:
6✔
202
                if (a->sockaddr.in.sin_addr.s_addr != b->sockaddr.in.sin_addr.s_addr)
6✔
203
                        return false;
204

205
                if (a->sockaddr.in.sin_port != b->sockaddr.in.sin_port)
5✔
206
                        return false;
1✔
207

208
                break;
209

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

214
                if (a->sockaddr.in6.sin6_port != b->sockaddr.in6.sin6_port)
2✔
215
                        return false;
×
216

217
                break;
218

219
        case AF_UNIX:
6,439✔
220
                if (a->size <= offsetof(struct sockaddr_un, sun_path) ||
6,439✔
221
                    b->size <= offsetof(struct sockaddr_un, sun_path))
6,439✔
222
                        return false;
223

224
                if ((a->sockaddr.un.sun_path[0] == 0) != (b->sockaddr.un.sun_path[0] == 0))
6,439✔
225
                        return false;
226

227
                if (a->sockaddr.un.sun_path[0]) {
6,154✔
228
                        if (!path_equal_or_inode_same(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, 0))
6,115✔
229
                                return false;
508✔
230
                } else {
231
                        if (a->size != b->size)
39✔
232
                                return false;
233

234
                        if (memcmp(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, a->size) != 0)
39✔
235
                                return false;
×
236
                }
237

238
                break;
239

240
        case AF_NETLINK:
202✔
241
                if (a->protocol != b->protocol)
202✔
242
                        return false;
243

244
                if (a->sockaddr.nl.nl_groups != b->sockaddr.nl.nl_groups)
202✔
245
                        return false;
1✔
246

247
                break;
248

249
        case AF_VSOCK:
21✔
250
                if (a->sockaddr.vm.svm_cid != b->sockaddr.vm.svm_cid)
21✔
251
                        return false;
252

253
                if (a->sockaddr.vm.svm_port != b->sockaddr.vm.svm_port)
20✔
254
                        return false;
1✔
255

256
                break;
257

258
        default:
259
                /* Cannot compare, so we assume the addresses are different */
260
                return false;
261
        }
262

263
        return true;
264
}
265

266
const char* socket_address_get_path(const SocketAddress *a) {
28,576✔
267
        assert(a);
28,576✔
268

269
        if (socket_address_family(a) != AF_UNIX)
28,576✔
270
                return NULL;
271

272
        if (a->sockaddr.un.sun_path[0] == 0)
27,658✔
273
                return NULL;
274

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

282
bool socket_ipv6_is_supported(void) {
120,032✔
283
        static int cached = -1;
120,032✔
284

285
        if (cached < 0) {
120,032✔
286

287
                if (access("/proc/net/if_inet6", F_OK) < 0) {
1,168✔
288

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

294
                        cached = false;
×
295
                } else
296
                        cached = true;
1,168✔
297
        }
298

299
        return cached;
120,032✔
300
}
301

302
bool socket_ipv6_is_enabled(void) {
74,510✔
303
        _cleanup_free_ char *v = NULL;
74,510✔
304
        int r;
74,510✔
305

306
        /* Much like socket_ipv6_is_supported(), but also checks that the sysctl that disables IPv6 on all
307
         * interfaces isn't turned on */
308

309
        if (!socket_ipv6_is_supported())
74,510✔
310
                return false;
311

312
        r = sysctl_read_ip_property(AF_INET6, "all", "disable_ipv6", &v);
74,510✔
313
        if (r < 0) {
74,510✔
314
                log_debug_errno(r, "Unexpected error reading 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
×
315
                return true;
316
        }
317

318
        r = parse_boolean(v);
74,510✔
319
        if (r < 0) {
74,510✔
320
                log_debug_errno(r, "Failed to pare 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
74,510✔
321
                return true;
322
        }
323

324
        return !r;
74,510✔
325
}
326

327
bool socket_address_matches_fd(const SocketAddress *a, int fd) {
1,025✔
328
        SocketAddress b;
1,025✔
329
        socklen_t solen;
1,025✔
330

331
        assert(a);
1,025✔
332
        assert(fd >= 0);
1,025✔
333

334
        b.size = sizeof(b.sockaddr);
1,025✔
335
        if (getsockname(fd, &b.sockaddr.sa, &b.size) < 0)
1,025✔
336
                return false;
1,025✔
337

338
        if (b.sockaddr.sa.sa_family != a->sockaddr.sa.sa_family)
1,025✔
339
                return false;
340

341
        solen = sizeof(b.type);
917✔
342
        if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &b.type, &solen) < 0)
917✔
343
                return false;
344

345
        if (b.type != a->type)
917✔
346
                return false;
347

348
        if (a->protocol != 0)  {
793✔
349
                solen = sizeof(b.protocol);
×
350
                if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &b.protocol, &solen) < 0)
×
351
                        return false;
352

353
                if (b.protocol != a->protocol)
×
354
                        return false;
355
        }
356

357
        return socket_address_equal(a, &b);
793✔
358
}
359

360
int sockaddr_port(const struct sockaddr *_sa, unsigned *ret_port) {
×
361
        const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
×
362

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

365
        assert(sa);
×
366
        assert(ret_port);
×
367

368
        switch (sa->sa.sa_family) {
×
369

370
        case AF_INET:
×
371
                *ret_port = be16toh(sa->in.sin_port);
×
372
                return 0;
×
373

374
        case AF_INET6:
×
375
                *ret_port = be16toh(sa->in6.sin6_port);
×
376
                return 0;
×
377

378
        case AF_VSOCK:
×
379
                *ret_port = sa->vm.svm_port;
×
380
                return 0;
×
381

382
        default:
383
                return -EAFNOSUPPORT;
384
        }
385
}
386

387
const union in_addr_union *sockaddr_in_addr(const struct sockaddr *_sa) {
360✔
388
        const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
360✔
389

390
        if (!sa)
360✔
391
                return NULL;
392

393
        switch (sa->sa.sa_family) {
360✔
394

395
        case AF_INET:
283✔
396
                return (const union in_addr_union*) &sa->in.sin_addr;
283✔
397

398
        case AF_INET6:
77✔
399
                return (const union in_addr_union*) &sa->in6.sin6_addr;
77✔
400

401
        default:
402
                return NULL;
403
        }
404
}
405

406
int sockaddr_set_in_addr(
1,149✔
407
                union sockaddr_union *u,
408
                int family,
409
                const union in_addr_union *a,
410
                uint16_t port) {
411

412
        assert(u);
1,149✔
413
        assert(a);
1,149✔
414

415
        switch (family) {
1,149✔
416

417
        case AF_INET:
418
                u->in = (struct sockaddr_in) {
1,056✔
419
                        .sin_family = AF_INET,
420
                        .sin_addr = a->in,
1,056✔
421
                        .sin_port = htobe16(port),
1,056✔
422
                };
423

424
                return 0;
1,056✔
425

426
        case AF_INET6:
427
                u->in6 = (struct sockaddr_in6) {
93✔
428
                        .sin6_family = AF_INET6,
429
                        .sin6_addr = a->in6,
93✔
430
                        .sin6_port = htobe16(port),
93✔
431
                };
432

433
                return 0;
93✔
434

435
        default:
436
                return -EAFNOSUPPORT;
437

438
        }
439
}
440

441
int sockaddr_pretty(
15,205✔
442
                const struct sockaddr *_sa,
443
                socklen_t salen,
444
                bool translate_ipv6,
445
                bool include_port,
446
                char **ret) {
447

448
        union sockaddr_union *sa = (union sockaddr_union*) _sa;
15,205✔
449
        char *p;
15,205✔
450
        int r;
15,205✔
451

452
        assert(sa);
15,205✔
453
        assert(salen >= sizeof(sa->sa.sa_family));
15,205✔
454
        assert(ret);
15,205✔
455

456
        switch (sa->sa.sa_family) {
15,205✔
457

458
        case AF_INET: {
92✔
459
                uint32_t a;
92✔
460

461
                a = be32toh(sa->in.sin_addr.s_addr);
92✔
462

463
                if (include_port)
92✔
464
                        r = asprintf(&p,
92✔
465
                                     "%u.%u.%u.%u:%u",
466
                                     a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
467
                                     be16toh(sa->in.sin_port));
92✔
468
                else
469
                        r = asprintf(&p,
×
470
                                     "%u.%u.%u.%u",
471
                                     a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF);
472
                if (r < 0)
92✔
473
                        return -ENOMEM;
15,205✔
474
                break;
475
        }
476

477
        case AF_INET6: {
20✔
478
                static const unsigned char ipv4_prefix[] = {
20✔
479
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
480
                };
481

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

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

517
                break;
518
        }
519

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

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

539
                                _cleanup_free_ char *e = NULL;
46✔
540

541
                                e = cescape_length(path + 1, path_len - 1);
46✔
542
                                if (!e)
46✔
543
                                        return -ENOMEM;
×
544

545
                                p = strjoin("@", e);
46✔
546
                        } else {
547
                                if (path[path_len - 1] == '\0')
14,846✔
548
                                        /* We expect a terminating NUL and don't print it */
549
                                        path_len--;
14,845✔
550

551
                                p = cescape_length(path, path_len);
14,846✔
552
                        }
553
                }
554
                if (!p)
15,067✔
555
                        return -ENOMEM;
556

557
                break;
558

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

571
        default:
572
                return -EOPNOTSUPP;
573
        }
574

575
        *ret = p;
15,205✔
576
        return 0;
15,205✔
577
}
578

579
int getpeername_pretty(int fd, bool include_port, char **ret) {
175✔
580
        union sockaddr_union sa;
175✔
581
        socklen_t salen = sizeof(sa);
175✔
582
        int r;
175✔
583

584
        assert(fd >= 0);
175✔
585
        assert(ret);
175✔
586

587
        if (getpeername(fd, &sa.sa, &salen) < 0)
175✔
588
                return -errno;
×
589

590
        if (sa.sa.sa_family == AF_UNIX) {
175✔
591
                struct ucred ucred = UCRED_INVALID;
173✔
592

593
                /* UNIX connection sockets are anonymous, so let's use
594
                 * PID/UID as pretty credentials instead */
595

596
                r = getpeercred(fd, &ucred);
173✔
597
                if (r < 0)
173✔
598
                        return r;
173✔
599

600
                if (asprintf(ret, "PID "PID_FMT"/UID "UID_FMT, ucred.pid, ucred.uid) < 0)
173✔
601
                        return -ENOMEM;
602

603
                return 0;
173✔
604
        }
605

606
        /* For remote sockets we translate IPv6 addresses back to IPv4
607
         * if applicable, since that's nicer. */
608

609
        return sockaddr_pretty(&sa.sa, salen, true, include_port, ret);
2✔
610
}
611

612
int getsockname_pretty(int fd, char **ret) {
4✔
613
        union sockaddr_union sa;
4✔
614
        socklen_t salen = sizeof(sa);
4✔
615

616
        assert(fd >= 0);
4✔
617
        assert(ret);
4✔
618

619
        if (getsockname(fd, &sa.sa, &salen) < 0)
4✔
620
                return -errno;
×
621

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

627
        return sockaddr_pretty(&sa.sa, salen, false, true, ret);
4✔
628
}
629

630
int socknameinfo_pretty(const struct sockaddr *sa, socklen_t salen, char **ret) {
×
631
        char host[NI_MAXHOST];
×
632
        int r;
×
633

634
        assert(sa);
×
635
        assert(salen >= sizeof(sa_family_t));
×
636
        assert(ret);
×
637

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

647
                return sockaddr_pretty(sa, salen, /* translate_ipv6= */ true, /* include_port= */ true, ret);
×
648
        }
649

650
        return strdup_to(ret, host);
×
651
}
652

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

674
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
1,169✔
675

676
bool sockaddr_equal(const union sockaddr_union *a, const union sockaddr_union *b) {
1,714✔
677
        assert(a);
1,714✔
678
        assert(b);
1,714✔
679

680
        if (a->sa.sa_family != b->sa.sa_family)
1,714✔
681
                return false;
682

683
        if (a->sa.sa_family == AF_INET)
1,713✔
684
                return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
4✔
685

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

689
        if (a->sa.sa_family == AF_VSOCK)
1,708✔
690
                return a->vm.svm_cid == b->vm.svm_cid;
1✔
691

692
        return false;
693
}
694

695
int fd_set_sndbuf(int fd, size_t n, bool increase) {
433,941✔
696
        int r, value;
433,941✔
697
        socklen_t l = sizeof(value);
433,941✔
698

699
        if (n > INT_MAX)
433,941✔
700
                return -ERANGE;
433,941✔
701

702
        r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
433,941✔
703
        if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
433,941✔
704
                return 0;
705

706
        /* First, try to set the buffer size with SO_SNDBUF. */
707
        r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUF, n);
433,941✔
708
        if (r < 0)
433,941✔
709
                return r;
710

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

718
        /* If we have the privileges we will ignore the kernel limit. */
719
        r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUFFORCE, n);
433,101✔
720
        if (r < 0)
433,101✔
721
                return r;
33,295✔
722

723
        return 1;
724
}
725

726
int fd_set_rcvbuf(int fd, size_t n, bool increase) {
42,301✔
727
        int r, value;
42,301✔
728
        socklen_t l = sizeof(value);
42,301✔
729

730
        if (n > INT_MAX)
42,301✔
731
                return -ERANGE;
42,301✔
732

733
        r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
42,301✔
734
        if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
42,301✔
735
                return 0;
736

737
        /* First, try to set the buffer size with SO_RCVBUF. */
738
        r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUF, n);
42,300✔
739
        if (r < 0)
42,300✔
740
                return r;
741

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

749
        /* If we have the privileges we will ignore the kernel limit. */
750
        r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUFFORCE, n);
41,460✔
751
        if (r < 0)
41,460✔
752
                return r;
6,019✔
753

754
        return 1;
755
}
756

757
static const char* const ip_tos_table[] = {
758
        [IPTOS_LOWDELAY]    = "low-delay",
759
        [IPTOS_THROUGHPUT]  = "throughput",
760
        [IPTOS_RELIABILITY] = "reliability",
761
        [IPTOS_LOWCOST]     = "low-cost",
762
};
763

764
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
5✔
765

766
bool ifname_valid_char(char a) {
382,105✔
767
        if ((unsigned char) a >= 127U)
382,105✔
768
                return false;
769

770
        if ((unsigned char) a <= 32U)
382,105✔
771
                return false;
772

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

779
        return true;
780
}
781

782
bool ifname_valid_full(const char *p, IfnameValidFlags flags) {
103,203✔
783
        bool numeric = true;
103,203✔
784

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

789
        assert(!(flags & ~_IFNAME_VALID_ALL));
103,203✔
790

791
        if (isempty(p))
103,203✔
792
                return false;
793

794
        /* A valid ifindex? If so, it's valid iff IFNAME_VALID_NUMERIC is set */
795
        if (parse_ifindex(p) >= 0)
99,461✔
796
                return flags & IFNAME_VALID_NUMERIC;
57✔
797

798
        if (flags & IFNAME_VALID_ALTERNATIVE) {
99,404✔
799
                if (strlen(p) >= ALTIFNAMSIZ)
13,576✔
800
                        return false;
801
        } else {
802
                if (strlen(p) >= IFNAMSIZ)
85,828✔
803
                        return false;
804
        }
805

806
        if (dot_or_dot_dot(p))
99,397✔
807
                return false;
808

809
        /* Let's refuse "all" and "default" as interface name, to avoid collisions with the special sysctl
810
         * directories /proc/sys/net/{ipv4,ipv6}/conf/{all,default} */
811
        if (!FLAGS_SET(flags, IFNAME_VALID_SPECIAL) && STR_IN_SET(p, "all", "default"))
99,395✔
812
                return false;
×
813

814
        for (const char *t = p; *t; t++) {
475,217✔
815
                if (!ifname_valid_char(*t))
375,836✔
816
                        return false;
817

818
                numeric = numeric && ascii_isdigit(*t);
475,207✔
819
        }
820

821
        /* It's fully numeric but didn't parse as valid ifindex above? if so, it must be too large or zero or
822
         * so, let's refuse that. */
823
        if (numeric)
99,381✔
824
                return false;
2✔
825

826
        return true;
827
}
828

829
bool address_label_valid(const char *p) {
44✔
830

831
        POINTER_MAY_BE_NULL(p);
44✔
832

833
        if (isempty(p))
44✔
834
                return false;
835

836
        if (strlen(p) >= IFNAMSIZ)
44✔
837
                return false;
838

839
        while (*p) {
376✔
840
                if ((uint8_t) *p >= 127U)
332✔
841
                        return false;
842

843
                if ((uint8_t) *p <= 31U)
332✔
844
                        return false;
845
                p++;
332✔
846
        }
847

848
        return true;
849
}
850

851
int getpeercred(int fd, struct ucred *ucred) {
110,150✔
852
        socklen_t n = sizeof(struct ucred);
110,150✔
853
        struct ucred u;
110,150✔
854

855
        assert(fd >= 0);
110,150✔
856
        assert(ucred);
110,150✔
857

858
        if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n) < 0)
110,150✔
859
                return -errno;
×
860

861
        if (n != sizeof(struct ucred))
110,150✔
862
                return -EIO;
863

864
        /* Check if the data is actually useful and not suppressed due to namespacing issues */
865
        if (!pid_is_valid(u.pid))
110,150✔
866
                return -ENODATA;
867

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

871
        *ucred = u;
110,150✔
872
        return 0;
110,150✔
873
}
874

875
int getpeersec(int fd, char **ret) {
28,796✔
876
        _cleanup_free_ char *s = NULL;
57,592✔
877
        socklen_t n = 64;
28,796✔
878

879
        assert(fd >= 0);
28,796✔
880
        assert(ret);
28,796✔
881

882
        for (;;) {
28,796✔
883
                s = new0(char, n+1);
28,796✔
884
                if (!s)
28,796✔
885
                        return -ENOMEM;
886

887
                if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n) >= 0) {
28,796✔
888
                        s[n] = 0;
18,275✔
889
                        break;
18,275✔
890
                }
891

892
                if (errno != ERANGE)
10,521✔
893
                        return -errno;
10,521✔
894

895
                s = mfree(s);
×
896
        }
897

898
        if (isempty(s))
18,275✔
899
                return -EOPNOTSUPP;
900

901
        *ret = TAKE_PTR(s);
18,275✔
902

903
        return 0;
18,275✔
904
}
905

906
int getpeergroups(int fd, gid_t **ret) {
28,797✔
907
        socklen_t n = sizeof(gid_t) * 64U;
28,797✔
908
        _cleanup_free_ gid_t *d = NULL;
28,797✔
909

910
        assert(fd >= 0);
28,797✔
911
        assert(ret);
28,797✔
912

913
        long ngroups_max = sysconf(_SC_NGROUPS_MAX);
28,797✔
914
        if (ngroups_max > 0)
28,797✔
915
                n = MAX(n, sizeof(gid_t) * (socklen_t) ngroups_max);
28,797✔
916

917
        for (;;) {
28,797✔
918
                d = malloc(n);
28,797✔
919
                if (!d)
28,797✔
920
                        return -ENOMEM;
921

922
                if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
28,797✔
923
                        break;
924

925
                if (errno != ERANGE)
×
926
                        return -errno;
×
927

928
                d = mfree(d);
×
929
        }
930

931
        assert_se(n % sizeof(gid_t) == 0);
28,797✔
932
        n /= sizeof(gid_t);
28,797✔
933

934
        if (n > INT_MAX)
28,797✔
935
                return -E2BIG;
936

937
        *ret = TAKE_PTR(d);
28,797✔
938

939
        return (int) n;
28,797✔
940
}
941

942
int getpeerpidfd(int fd) {
29,615✔
943
        socklen_t n = sizeof(int);
29,615✔
944
        int pidfd = -EBADF;
29,615✔
945

946
        assert(fd >= 0);
29,615✔
947

948
        if (getsockopt(fd, SOL_SOCKET, SO_PEERPIDFD, &pidfd, &n) < 0)
29,615✔
949
                return -errno;
×
950

951
        if (n != sizeof(int))
29,615✔
952
                return -EIO;
953

954
        return pidfd;
29,615✔
955
}
956

957
int getpeerpidref(int fd, PidRef *ret) {
4✔
958
        int r;
4✔
959

960
        assert(fd >= 0);
4✔
961
        assert(ret);
4✔
962

963
        int pidfd = getpeerpidfd(fd);
4✔
964
        if (pidfd < 0) {
4✔
965
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(pidfd))
×
966
                        return pidfd;
×
967

968
                struct ucred ucred;
×
969
                r = getpeercred(fd, &ucred);
×
970
                if (r < 0)
×
971
                        return r;
972

973
                return pidref_set_pid(ret, ucred.pid);
×
974
        }
975

976
        return pidref_set_pidfd_consume(ret, pidfd);
4✔
977
}
978

979
ssize_t send_one_fd_iov_sa(
1,068✔
980
                int transport_fd,
981
                int fd,
982
                const struct iovec *iov, size_t iovlen,
983
                const struct sockaddr *sa, socklen_t len,
984
                int flags) {
985

986
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control = {};
1,068✔
987
        struct msghdr mh = {
1,068✔
988
                .msg_name = (struct sockaddr*) sa,
989
                .msg_namelen = len,
990
                .msg_iov = (struct iovec *)iov,
991
                .msg_iovlen = iovlen,
992
        };
993
        ssize_t k;
1,068✔
994

995
        assert(transport_fd >= 0);
1,068✔
996

997
        /*
998
         * We need either an FD or data to send.
999
         * If there's nothing, return an error.
1000
         */
1001
        if (fd < 0 && !iov)
1,068✔
1002
                return -EINVAL;
1,068✔
1003

1004
        if (fd >= 0) {
1,067✔
1005
                struct cmsghdr *cmsg;
1,064✔
1006

1007
                mh.msg_control = &control;
1,064✔
1008
                mh.msg_controllen = sizeof(control);
1,064✔
1009

1010
                cmsg = CMSG_FIRSTHDR(&mh);
1,064✔
1011
                cmsg->cmsg_level = SOL_SOCKET;
1,064✔
1012
                cmsg->cmsg_type = SCM_RIGHTS;
1,064✔
1013
                cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1,064✔
1014
                memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
1,064✔
1015
        }
1016
        k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
1,067✔
1017
        if (k < 0)
1,067✔
1018
                return (ssize_t) -errno;
×
1019

1020
        return k;
1021
}
1022

1023
int send_one_fd_sa(
4✔
1024
                int transport_fd,
1025
                int fd,
1026
                const struct sockaddr *sa, socklen_t len,
1027
                int flags) {
1028

1029
        assert(fd >= 0);
4✔
1030

1031
        return (int) send_one_fd_iov_sa(transport_fd, fd, NULL, 0, sa, len, flags);
4✔
1032
}
1033

1034
ssize_t receive_one_fd_iov(
6,996✔
1035
                int transport_fd,
1036
                struct iovec *iov, size_t iovlen,
1037
                int flags,
1038
                int *ret_fd) {
1039

1040
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
6,996✔
1041
        struct msghdr mh = {
6,996✔
1042
                .msg_control = &control,
1043
                .msg_controllen = sizeof(control),
1044
                .msg_iov = iov,
1045
                .msg_iovlen = iovlen,
1046
        };
1047
        struct cmsghdr *found;
6,996✔
1048
        ssize_t k;
6,996✔
1049

1050
        assert(transport_fd >= 0);
6,996✔
1051
        assert(ret_fd);
6,996✔
1052

1053
        /*
1054
         * Receive a single FD via @transport_fd. We don't care for
1055
         * the transport-type. We retrieve a single FD at most, so for
1056
         * packet-based transports, the caller must ensure to send
1057
         * only a single FD per packet.  This is best used in
1058
         * combination with send_one_fd().
1059
         */
1060

1061
        k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
6,996✔
1062
        if (k < 0)
6,996✔
1063
                return k;
6,996✔
1064

1065
        found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
6,815✔
1066
        if (!found) {
6,815✔
1067
                cmsg_close_all(&mh);
2,077✔
1068

1069
                /* If didn't receive an FD or any data, return an error. */
1070
                if (k == 0)
2,077✔
1071
                        return -EIO;
1072
        }
1073

1074
        if (found)
4,741✔
1075
                *ret_fd = *CMSG_TYPED_DATA(found, int);
4,738✔
1076
        else
1077
                *ret_fd = -EBADF;
3✔
1078

1079
        return k;
1080
}
1081

1082
int receive_one_fd(int transport_fd, int flags) {
974✔
1083
        int fd;
974✔
1084
        ssize_t k;
974✔
1085

1086
        k = receive_one_fd_iov(transport_fd, NULL, 0, flags, &fd);
974✔
1087
        if (k == 0)
974✔
1088
                return fd;
885✔
1089

1090
        /* k must be negative, since receive_one_fd_iov() only returns
1091
         * a positive value if data was received through the iov. */
1092
        assert(k < 0);
89✔
1093
        return (int) k;
89✔
1094
}
1095

1096
ssize_t next_datagram_size_fd(int fd) {
200,822✔
1097
        ssize_t l;
200,822✔
1098
        int k;
200,822✔
1099

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

1106
        l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
200,822✔
1107
        if (l < 0) {
200,822✔
1108
                if (IN_SET(errno, EOPNOTSUPP, EFAULT))
583✔
1109
                        goto fallback;
×
1110

1111
                return -errno;
583✔
1112
        }
1113
        if (l == 0)
200,239✔
1114
                goto fallback;
76✔
1115

1116
        return l;
1117

1118
fallback:
76✔
1119
        k = 0;
76✔
1120

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

1124
        if (ioctl(fd, FIONREAD, &k) < 0)
76✔
1125
                return -errno;
×
1126

1127
        return (ssize_t) k;
76✔
1128
}
1129

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

1134
int flush_accept(int fd) {
49✔
1135

1136
        int r, b;
49✔
1137
        socklen_t l = sizeof(b);
49✔
1138

1139
        /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1140
         * them. */
1141

1142
        if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
49✔
1143
                return -errno;
×
1144

1145
        assert(l == sizeof(b));
49✔
1146
        if (!b) /* Let's check if this socket accepts connections before calling accept(). accept4() can
49✔
1147
                 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
1148
                 * error, or in case the incoming TCP connection triggered a network issue, which we want to
1149
                 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
1150
                 * we can loop safely on transient errors below. */
1151
                return -ENOTTY;
1152

1153
        for (unsigned iteration = 0;; iteration++) {
5✔
1154
                int cfd;
46✔
1155

1156
                r = fd_wait_for_event(fd, POLLIN, 0);
46✔
1157
                if (r == -EINTR)
46✔
1158
                        continue;
×
1159
                if (r <= 0)
46✔
1160
                        return r;
1161

1162
                if (iteration >= MAX_FLUSH_ITERATIONS)
5✔
1163
                        return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
×
1164
                                               "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS) " iterations.");
1165

1166
                cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
5✔
1167
                if (cfd < 0) {
5✔
1168
                        if (errno == EAGAIN)
×
1169
                                return 0;
1170

1171
                        if (ERRNO_IS_ACCEPT_AGAIN(errno))
×
1172
                                continue;
×
1173

1174
                        return -errno;
×
1175
                }
1176

1177
                safe_close(cfd);
5✔
1178
        }
1179
}
1180

1181
ssize_t flush_mqueue(int fd) {
×
1182
        _cleanup_free_ char *buf = NULL;
×
1183
        struct mq_attr attr;
×
1184
        ssize_t count = 0;
×
1185
        int r;
×
1186

1187
        assert(fd >= 0);
×
1188

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

1191
        for (;;) {
×
1192
                ssize_t l;
×
1193

1194
                r = fd_wait_for_event(fd, POLLIN, /* timeout= */ 0);
×
1195
                if (r == -EINTR)
×
1196
                        continue;
×
1197
                if (r < 0)
×
1198
                        return r;
×
1199
                if (r == 0)
×
1200
                        return count;
1201

1202
                if (!buf) {
×
1203
                        /* Buffer must be at least as large as mq_msgsize. */
1204
                        if (mq_getattr(fd, &attr) < 0)
×
1205
                                return -errno;
×
1206

1207
                        buf = malloc(attr.mq_msgsize);
×
1208
                        if (!buf)
×
1209
                                return -ENOMEM;
1210
                }
1211

1212
                l = mq_receive(fd, buf, attr.mq_msgsize, /* msg_prio= */ NULL);
×
1213
                if (l < 0) {
×
1214
                        if (errno == EINTR)
×
1215
                                continue;
×
1216

1217
                        if (errno == EAGAIN)
×
1218
                                return count;
1219

1220
                        return -errno;
×
1221
                }
1222

1223
                count += l;
×
1224
        }
1225
}
1226

1227
struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
392,641✔
1228
        struct cmsghdr *cmsg;
392,641✔
1229

1230
        assert(mh);
392,641✔
1231

1232
        CMSG_FOREACH(cmsg, mh)
394,003✔
1233
                if (cmsg->cmsg_level == level &&
355,023✔
1234
                    cmsg->cmsg_type == type &&
354,515✔
1235
                    (length == (socklen_t) -1 || length == cmsg->cmsg_len))
353,475✔
1236
                        return cmsg;
1237

1238
        return NULL;
1239
}
1240

1241
void* cmsg_find_and_copy_data(struct msghdr *mh, int level, int type, void *buf, size_t buf_len) {
394✔
1242
        struct cmsghdr *cmsg;
394✔
1243

1244
        assert(mh);
394✔
1245
        assert(buf);
394✔
1246
        assert(buf_len > 0);
394✔
1247

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

1252
        cmsg = cmsg_find(mh, level, type, CMSG_LEN(buf_len));
394✔
1253
        if (!cmsg)
394✔
1254
                return NULL;
1255

1256
        return memcpy_safe(buf, CMSG_DATA(cmsg), buf_len);
365✔
1257
}
1258

1259
size_t sockaddr_ll_len(const struct sockaddr_ll *sa) {
439✔
1260
        /* Certain hardware address types (e.g Infiniband) do not fit into sll_addr
1261
         * (8 bytes) and run over the structure. This function returns the correct size that
1262
         * must be passed to kernel. */
1263

1264
        assert(sa->sll_family == AF_PACKET);
439✔
1265

1266
        size_t mac_len = sizeof(sa->sll_addr);
439✔
1267

1268
        if (be16toh(sa->sll_hatype) == ARPHRD_ETHER)
439✔
1269
                mac_len = MAX(mac_len, (size_t) ETH_ALEN);
439✔
1270
        if (be16toh(sa->sll_hatype) == ARPHRD_INFINIBAND)
439✔
1271
                mac_len = MAX(mac_len, (size_t) INFINIBAND_ALEN);
×
1272

1273
        return offsetof(struct sockaddr_ll, sll_addr) + mac_len;
439✔
1274
}
1275

1276
size_t sockaddr_un_len(const struct sockaddr_un *sa) {
2,907✔
1277
        /* Covers only file system and abstract AF_UNIX socket addresses, but not unnamed socket addresses. */
1278

1279
        assert(sa->sun_family == AF_UNIX);
2,907✔
1280

1281
        return offsetof(struct sockaddr_un, sun_path) +
8,721✔
1282
                (sa->sun_path[0] == 0 ?
2,907✔
1283
                        1 + strnlen(sa->sun_path+1, sizeof(sa->sun_path)-1) :
934✔
1284
                        strnlen(sa->sun_path, sizeof(sa->sun_path))+1);
1,973✔
1285
}
1286

1287
size_t sockaddr_len(const union sockaddr_union *sa) {
454✔
1288
        switch (sa->sa.sa_family) {
454✔
1289
        case AF_INET:
1290
                return sizeof(struct sockaddr_in);
1291
        case AF_INET6:
136✔
1292
                return sizeof(struct sockaddr_in6);
136✔
1293
        case AF_UNIX:
3✔
1294
                return sockaddr_un_len(&sa->un);
3✔
1295
        case AF_PACKET:
×
1296
                return sockaddr_ll_len(&sa->ll);
×
1297
        case AF_NETLINK:
×
1298
                return sizeof(struct sockaddr_nl);
×
1299
        case AF_VSOCK:
1300
                return sizeof(struct sockaddr_vm);
1301
        default:
×
1302
                assert_not_reached();
×
1303
        }
1304
}
1305

1306
int socket_ioctl_fd(void) {
4,603✔
1307
        int fd;
4,603✔
1308

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

1314
        fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
4,603✔
1315
        if (fd < 0)
4,603✔
1316
                fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
×
1317
        if (fd < 0)
×
1318
                return -errno;
×
1319

1320
        return fd;
1321
}
1322

1323
int sockaddr_un_unlink(const struct sockaddr_un *sa) {
1,971✔
1324
        const char *p, * nul;
1,971✔
1325

1326
        assert(sa);
1,971✔
1327

1328
        if (sa->sun_family != AF_UNIX)
1,971✔
1329
                return -EPROTOTYPE;
1330

1331
        if (sa->sun_path[0] == 0) /* Nothing to do for abstract sockets */
1,971✔
1332
                return 0;
1333

1334
        /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1335
        nul = memchr(sa->sun_path, 0, sizeof(sa->sun_path));
1,971✔
1336
        if (nul)
1,971✔
1337
                p = sa->sun_path;
1338
        else
1339
                p = memdupa_suffix0(sa->sun_path, sizeof(sa->sun_path));
×
1340

1341
        if (unlink(p) < 0)
1,971✔
1342
                return -errno;
1,451✔
1343

1344
        return 1;
1345
}
1346

1347
int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path) {
414,730✔
1348
        size_t l;
414,730✔
1349

1350
        assert(ret);
414,730✔
1351
        assert(path);
414,730✔
1352

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

1358
        l = strlen(path);
414,730✔
1359
        if (l < 2)
414,730✔
1360
                return -EINVAL;
1361
        if (!IN_SET(path[0], '/', '@'))
414,729✔
1362
                return -EINVAL;
1363

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

1374
        *ret = (struct sockaddr_un) {
414,727✔
1375
                .sun_family = AF_UNIX,
1376
        };
1377

1378
        if (path[0] == '@') {
414,727✔
1379
                /* Abstract namespace socket */
1380
                memcpy(ret->sun_path + 1, path + 1, l); /* copy *with* trailing NUL byte */
200,184✔
1381
                return (int) (offsetof(struct sockaddr_un, sun_path) + l); /* 🔥 *don't* 🔥 include trailing NUL in size */
200,184✔
1382

1383
        } else {
1384
                assert(path[0] == '/');
214,543✔
1385

1386
                /* File system socket */
1387
                memcpy(ret->sun_path, path, l + 1); /* copy *with* trailing NUL byte */
214,543✔
1388
                return (int) (offsetof(struct sockaddr_un, sun_path) + l + 1); /* include trailing NUL in size */
214,543✔
1389
        }
1390
}
1391

1392
int getsockopt_int(int fd, int level, int optname, int *ret) {
12,037✔
1393
        int v;
12,037✔
1394
        socklen_t sl = sizeof(v);
12,037✔
1395

1396
        assert(fd >= 0);
12,037✔
1397
        assert(ret);
12,037✔
1398

1399
        if (getsockopt(fd, level, optname, &v, &sl) < 0)
12,037✔
1400
                return negative_errno();
74✔
1401
        if (sl != sizeof(v))
11,963✔
1402
                return -EIO;
1403

1404
        *ret = v;
11,963✔
1405
        return 0;
11,963✔
1406
}
1407

1408
int socket_bind_to_ifname(int fd, const char *ifname) {
1✔
1409
        assert(fd >= 0);
1✔
1410

1411
        /* Call with NULL to drop binding */
1412

1413
        return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen_ptr(ifname)));
2✔
1414
}
1415

1416
int socket_bind_to_ifindex(int fd, int ifindex) {
1,027✔
1417
        assert(fd >= 0);
1,027✔
1418

1419
        if (ifindex <= 0)
1,027✔
1420
                /* Drop binding */
1421
                return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, NULL, 0));
74✔
1422

1423
        return setsockopt_int(fd, SOL_SOCKET, SO_BINDTOIFINDEX, ifindex);
953✔
1424
}
1425

1426
int socket_autobind(int fd, char **ret_name) {
674✔
1427
        _cleanup_free_ char *name = NULL;
674✔
1428
        uint64_t random;
674✔
1429
        int r;
674✔
1430

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

1434
        assert(fd >= 0);
674✔
1435

1436
        random = random_u64();
674✔
1437

1438
        if (asprintf(&name, "@%" PRIu64, random) < 0)
674✔
1439
                return -ENOMEM;
1440

1441
        union sockaddr_union sa;
674✔
1442
        assert_cc(DECIMAL_STR_MAX(uint64_t) < sizeof(sa.un.sun_path));
674✔
1443

1444
        r = sockaddr_un_set_path(&sa.un, name);
674✔
1445
        if (r < 0)
674✔
1446
                return r;
1447

1448
        if (bind(fd, &sa.sa, r) < 0)
674✔
1449
                return -errno;
×
1450

1451
        if (ret_name)
674✔
1452
                *ret_name = TAKE_PTR(name);
672✔
1453
        return 0;
1454
}
1455

1456
ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags) {
1,126,159✔
1457
        ssize_t n;
1,126,159✔
1458

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

1464
        assert(sockfd >= 0);
1,126,159✔
1465
        assert(msg);
1,126,159✔
1466

1467
        n = recvmsg(sockfd, msg, flags);
1,126,159✔
1468
        if (n < 0)
1,126,159✔
1469
                return -errno;
17,751✔
1470

1471
        if (FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ||
1,108,408✔
1472
            (!FLAGS_SET(flags, MSG_PEEK) && FLAGS_SET(msg->msg_flags, MSG_TRUNC))) {
1,108,408✔
1473
                cmsg_close_all(msg);
×
1474
                return FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ? -ECHRNG : -EXFULL;
×
1475
        }
1476

1477
        return n;
1478
}
1479

1480
int socket_get_family(int fd) {
36,830✔
1481
        int af;
36,830✔
1482
        socklen_t sl = sizeof(af);
36,830✔
1483

1484
        if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &af, &sl) < 0)
36,830✔
1485
                return -errno;
×
1486

1487
        if (sl != sizeof(af))
36,830✔
1488
                return -EINVAL;
1489

1490
        return af;
36,830✔
1491
}
1492

1493
int socket_set_recvpktinfo(int fd, int af, bool b) {
15,695✔
1494

1495
        if (af == AF_UNSPEC) {
15,695✔
1496
                af = socket_get_family(fd);
×
1497
                if (af < 0)
×
1498
                        return af;
1499
        }
1500

1501
        switch (af) {
15,695✔
1502

1503
        case AF_INET:
8,207✔
1504
                return setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, b);
8,207✔
1505

1506
        case AF_INET6:
7,444✔
1507
                return setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, b);
7,444✔
1508

1509
        case AF_NETLINK:
44✔
1510
                return setsockopt_int(fd, SOL_NETLINK, NETLINK_PKTINFO, b);
44✔
1511

1512
        case AF_PACKET:
×
1513
                return setsockopt_int(fd, SOL_PACKET, PACKET_AUXDATA, b);
×
1514

1515
        default:
1516
                return -EAFNOSUPPORT;
1517
        }
1518
}
1519

1520
int socket_set_unicast_if(int fd, int af, int ifi) {
141✔
1521
        be32_t ifindex_be = htobe32(ifi);
141✔
1522

1523
        if (af == AF_UNSPEC) {
141✔
1524
                af = socket_get_family(fd);
1✔
1525
                if (af < 0)
1✔
1526
                        return af;
141✔
1527
        }
1528

1529
        switch (af) {
141✔
1530

1531
        case AF_INET:
95✔
1532
                return RET_NERRNO(setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
95✔
1533

1534
        case AF_INET6:
46✔
1535
                return RET_NERRNO(setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
46✔
1536

1537
        default:
1538
                return -EAFNOSUPPORT;
1539
        }
1540
}
1541

1542
int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val) {
30,765✔
1543
        if (af == AF_UNSPEC) {
30,765✔
1544
                af = socket_get_family(fd);
×
1545
                if (af < 0)
×
1546
                        return af;
1547
        }
1548

1549
        switch (af) {
30,765✔
1550

1551
        case AF_INET:
16,233✔
1552
                return setsockopt_int(fd, IPPROTO_IP, opt_ipv4, val);
16,233✔
1553

1554
        case AF_INET6:
14,532✔
1555
                return setsockopt_int(fd, IPPROTO_IPV6, opt_ipv6, val);
14,532✔
1556

1557
        default:
1558
                return -EAFNOSUPPORT;
1559
        }
1560
}
1561

1562
int socket_get_mtu(int fd, int af, size_t *ret) {
783✔
1563
        int mtu, r;
783✔
1564

1565
        assert(ret);
783✔
1566

1567
        if (af == AF_UNSPEC) {
783✔
1568
                af = socket_get_family(fd);
×
1569
                if (af < 0)
×
1570
                        return af;
783✔
1571
        }
1572

1573
        switch (af) {
783✔
1574

1575
        case AF_INET:
349✔
1576
                r = getsockopt_int(fd, IPPROTO_IP, IP_MTU, &mtu);
349✔
1577
                break;
1578

1579
        case AF_INET6:
434✔
1580
                r = getsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, &mtu);
434✔
1581
                break;
1582

1583
        default:
1584
                return -EAFNOSUPPORT;
1585
        }
1586

1587
        if (r < 0)
783✔
1588
                return r;
1589
        if (mtu <= 0)
709✔
1590
                return -EINVAL;
1591

1592
        *ret = (size_t) mtu;
709✔
1593
        return 0;
709✔
1594
}
1595

1596
static int connect_unix_path_simple(int fd, const char *path) {
197,851✔
1597
        union sockaddr_union sa = {
197,851✔
1598
                .un.sun_family = AF_UNIX,
1599
        };
1600
        size_t l;
197,851✔
1601

1602
        assert(fd >= 0);
197,851✔
1603
        assert(path);
197,851✔
1604

1605
        l = strlen(path);
197,851✔
1606
        assert(l > 0);
197,851✔
1607
        assert(l < sizeof(sa.un.sun_path));
197,851✔
1608

1609
        memcpy(sa.un.sun_path, path, l + 1);
197,851✔
1610
        return RET_NERRNO(connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + l + 1));
197,851✔
1611
}
1612

1613
static int connect_unix_inode(int fd, int inode_fd) {
64✔
1614
        assert(fd >= 0);
64✔
1615
        assert(inode_fd >= 0);
64✔
1616

1617
        return connect_unix_path_simple(fd, FORMAT_PROC_FD_PATH(inode_fd));
64✔
1618
}
1619

1620
int connect_unix_path(int fd, int dir_fd, const char *path) {
197,851✔
1621
        _cleanup_close_ int inode_fd = -EBADF;
197,851✔
1622

1623
        assert(fd >= 0);
197,851✔
1624
        assert(wildcard_fd_is_valid(dir_fd));
197,851✔
1625

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

1629
        if (!path) {
197,851✔
1630
                if (dir_fd < 0)
3✔
1631
                        return -EISDIR;
1632

1633
                return connect_unix_inode(fd, dir_fd); /* If no path is specified, then dir_fd refers to the socket inode to connect to. */
3✔
1634
        }
1635

1636
        /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
1637
         * namespace path, since first char is NUL */
1638
        if (isempty(path))
395,699✔
1639
                return -EINVAL;
1640

1641
        /* Shortcut for the simple case */
1642
        if (dir_fd == AT_FDCWD && strlen(path) < sizeof_field(struct sockaddr_un, sun_path))
197,848✔
1643
                return connect_unix_path_simple(fd, path);
197,787✔
1644

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

1649
        if (dir_fd == XAT_FDROOT) {
61✔
1650
                _cleanup_free_ char *j = strjoin("/", path);
2✔
1651
                if (!j)
1✔
1652
                        return -ENOMEM;
×
1653

1654
                inode_fd = open(j, O_PATH|O_CLOEXEC);
1✔
1655
        } else
1656
                inode_fd = openat(dir_fd, path, O_PATH|O_CLOEXEC);
60✔
1657
        if (inode_fd < 0)
61✔
1658
                return -errno;
×
1659

1660
        return connect_unix_inode(fd, inode_fd);
61✔
1661
}
1662

1663
int socket_address_parse_unix(SocketAddress *ret_address, const char *s) {
222,647✔
1664
        struct sockaddr_un un;
222,647✔
1665
        int r;
222,647✔
1666

1667
        assert(ret_address);
222,647✔
1668
        assert(s);
222,647✔
1669

1670
        if (!IN_SET(*s, '/', '@'))
222,647✔
1671
                return -EPROTO;
222,647✔
1672

1673
        r = sockaddr_un_set_path(&un, s);
222,051✔
1674
        if (r < 0)
222,051✔
1675
                return r;
1676

1677
        *ret_address = (SocketAddress) {
222,049✔
1678
                .sockaddr.un = un,
1679
                .size = r,
1680
        };
1681

1682
        return 0;
222,049✔
1683
}
1684

1685
int socket_address_equal_unix(const char *a, const char *b) {
1,707✔
1686
        SocketAddress socket_a, socket_b;
1,707✔
1687
        int r;
1,707✔
1688

1689
        assert(a);
1,707✔
1690
        assert(b);
1,707✔
1691

1692
        r = socket_address_parse_unix(&socket_a, a);
1,707✔
1693
        if (r < 0)
1,707✔
1694
                return r;
1,707✔
1695

1696
        r = socket_address_parse_unix(&socket_b, b);
1,707✔
1697
        if (r < 0)
1,707✔
1698
                return r;
1699

1700
        return sockaddr_equal(&socket_a.sockaddr, &socket_b.sockaddr);
1,707✔
1701
}
1702

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

1706
        assert(ret);
519✔
1707

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

1711
        unsigned u;
519✔
1712
        r = safe_atou(s, &u);
519✔
1713
        if (r < 0)
519✔
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)
516✔
1720
                return -EINVAL;
1721

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

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

1729
        if (!s)
472✔
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"))
472✔
1736
                *ret = VMADDR_CID_HYPERVISOR;
×
1737
        else if (streq(s, "local"))
472✔
1738
                *ret = VMADDR_CID_LOCAL;
×
1739
        else if (streq(s, "host"))
472✔
1740
                *ret = VMADDR_CID_HOST;
×
1741
        else
1742
                return safe_atou(s, ret);
472✔
1743

1744
        return 0;
1745
}
1746

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

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

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

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

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

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

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

1788
        *ret_address = (SocketAddress) {
513✔
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;
513✔
1799
}
1800

1801
int netlink_socket_get_multicast_groups(int fd, size_t *ret_len, uint32_t **ret_groups) {
11,201✔
1802
        _cleanup_free_ uint32_t *groups = NULL;
22,402✔
1803
        socklen_t len = 0, old_len;
11,201✔
1804

1805
        assert(fd >= 0);
11,201✔
1806

1807
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, NULL, &len) < 0)
11,201✔
UNCOV
1808
                return -errno;
×
1809

1810
        if (len == 0)
11,201✔
1811
                goto finalize;
10,744✔
1812

1813
        groups = new0(uint32_t, len);
457✔
1814
        if (!groups)
457✔
1815
                return -ENOMEM;
1816

1817
        old_len = len;
457✔
1818

1819
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, groups, &len) < 0)
457✔
UNCOV
1820
                return -errno;
×
1821

1822
        if (old_len != len)
457✔
1823
                return -EIO;
1824

1825
finalize:
457✔
1826
        if (ret_len)
11,201✔
1827
                *ret_len = len;
11,201✔
1828
        if (ret_groups)
11,201✔
1829
                *ret_groups = TAKE_PTR(groups);
11,201✔
1830

1831
        return 0;
1832
}
1833

1834
int socket_get_cookie(int fd, uint64_t *ret) {
546✔
1835
        assert(fd >= 0);
546✔
1836

1837
        uint64_t cookie = 0;
546✔
1838
        socklen_t cookie_len = sizeof(cookie);
546✔
1839
        if (getsockopt(fd, SOL_SOCKET, SO_COOKIE, &cookie, &cookie_len) < 0)
546✔
UNCOV
1840
                return -errno;
×
1841

1842
        assert(cookie_len == sizeof(cookie));
546✔
1843
        if (ret)
546✔
1844
                *ret = cookie;
546✔
1845

1846
        return 0;
1847
}
1848

1849
void cmsg_close_all(struct msghdr *mh) {
111,137✔
1850
        assert(mh);
111,137✔
1851

1852
        struct cmsghdr *cmsg;
111,137✔
1853
        CMSG_FOREACH(cmsg, mh) {
256,653✔
1854
                if (cmsg->cmsg_level != SOL_SOCKET)
72,758✔
UNCOV
1855
                        continue;
×
1856

1857
                if (cmsg->cmsg_type == SCM_RIGHTS)
72,758✔
1858
                        close_many(CMSG_TYPED_DATA(cmsg, int),
1✔
1859
                                   (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
1✔
1860
                else if (cmsg->cmsg_type == SCM_PIDFD) {
72,757✔
UNCOV
1861
                        assert(cmsg->cmsg_len == CMSG_LEN(sizeof(int)));
×
UNCOV
1862
                        safe_close(*CMSG_TYPED_DATA(cmsg, int));
×
1863
                }
1864
        }
1865
}
111,137✔
1866

1867
int tos_to_priority(uint8_t tos) {
179✔
1868
        /* Map the IP Precedence (top 3 bits of the TOS field) to Linux internal packet priorities
1869
         * (TC_PRIO_*). This exactly mirrors the standard Linux kernel IP precedence-to-priority mapping
1870
         * (rt_tos2priority) to ensure consistent behavior when explicitly setting SO_PRIORITY. */
1871
        switch (IPTOS_PREC(tos)) {
179✔
1872
        case IPTOS_PREC_NETCONTROL:      /* 0xc0 (CS7) - Network Control. Used for infrastructure control (e.g., STP, keepalives). */
1873
        case IPTOS_PREC_INTERNETCONTROL: /* 0xe0 (CS6) - Internetwork Control. Used for routing protocols (e.g., OSPF, BGP) and DHCP. */
1874
                return TC_PRIO_CONTROL;
1875

1876
        case IPTOS_PREC_CRITIC_ECP:      /* 0xa0 (CS5) - Critical. Used for delay-sensitive traffic like Voice over IP (VoIP). */
2✔
1877
        case IPTOS_PREC_FLASHOVERRIDE:   /* 0x80 (CS4) - Flash Override. Used for interactive video and multimedia. */
1878
                return TC_PRIO_INTERACTIVE;
2✔
1879

1880
        case IPTOS_PREC_FLASH:           /* 0x60 (CS3) - Flash. Used for broadcast video and call signaling (e.g., SIP). */
2✔
1881
        case IPTOS_PREC_IMMEDIATE:       /* 0x40 (CS2) - Immediate. Used for OAM (Operations, Administration, and Management) and transactional data. */
1882
                return TC_PRIO_INTERACTIVE_BULK;
2✔
1883

1884
        case IPTOS_PREC_PRIORITY:        /* 0x20 (CS1) - Priority. Used for background traffic and bulk data transfers. */
2✔
1885
                return TC_PRIO_BULK;
2✔
1886

1887
        case IPTOS_PREC_ROUTINE:         /* 0x00 (CS0) - Routine. Best effort traffic. */
2✔
1888
        default:
1889
                return TC_PRIO_BESTEFFORT;
2✔
1890
        }
1891
}
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