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

systemd / systemd / 23966986054

03 Apr 2026 09:22PM UTC coverage: 72.107% (-0.3%) from 72.362%
23966986054

push

github

daandemeyer
fd-util: Add missing assert()

1 of 1 new or added line in 1 file covered. (100.0%)

7891 existing lines in 120 files now uncovered.

318256 of 441368 relevant lines covered (72.11%)

1186882.96 hits per line

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

82.35
/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) {
13,098✔
55
        assert(a);
13,098✔
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)) {
13,098✔
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:
32✔
75
                if (a->size != sizeof(struct sockaddr_in6))
32✔
76
                        return -EINVAL;
77

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

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

84
                return 0;
85

86
        case AF_UNIX:
12,524✔
87
                if (a->size < offsetof(struct sockaddr_un, sun_path))
12,524✔
88
                        return -EINVAL;
89
                if (a->size > sizeof(struct sockaddr_un) + !strict)
12,524✔
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) &&
12,524✔
95
                    a->sockaddr.un.sun_path[0] != 0 &&
12,524✔
96
                    strict) {
97
                        /* Only validate file system sockets here, and only in strict mode */
98
                        const char *e;
3,492✔
99

100
                        e = memchr(a->sockaddr.un.sun_path, 0, sizeof(a->sockaddr.un.sun_path));
3,492✔
101
                        if (e) {
3,492✔
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,492✔
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))
12,524✔
116
                        return -EINVAL;
×
117

118
                return 0;
119

120
        case AF_NETLINK:
430✔
121

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

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

128
                return 0;
129

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

134
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
68✔
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) {
3,152✔
145
        int r;
3,152✔
146

147
        assert(a);
3,152✔
148
        assert(ret);
3,152✔
149

150
        r = socket_address_verify(a, false); /* We do non-strict validation, because we want to be
3,152✔
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)
3,152✔
155
                return r;
156

157
        if (socket_address_family(a) == AF_NETLINK) {
3,152✔
158
                _cleanup_free_ char *sfamily = NULL;
148✔
159

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

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

168
                return 0;
148✔
169
        }
170

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

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

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

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

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

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

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

196
        switch (socket_address_family(a)) {
3,164✔
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:
3,028✔
217
                if (a->size <= offsetof(struct sockaddr_un, sun_path) ||
3,028✔
218
                    b->size <= offsetof(struct sockaddr_un, sun_path))
3,028✔
219
                        return false;
220

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

224
                if (a->sockaddr.un.sun_path[0]) {
2,813✔
225
                        if (!path_equal_or_inode_same(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, 0))
2,811✔
226
                                return false;
314✔
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:
109✔
238
                if (a->protocol != b->protocol)
109✔
239
                        return false;
240

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

244
                break;
245

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

250
                if (a->sockaddr.vm.svm_port != b->sockaddr.vm.svm_port)
18✔
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) {
19,794✔
264
        assert(a);
19,794✔
265

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

269
        if (a->sockaddr.un.sun_path[0] == 0)
19,200✔
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);
19,199✔
276
        return a->sockaddr.un.sun_path;
19,199✔
277
}
278

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

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

284
                if (access("/proc/net/if_inet6", F_OK) < 0) {
1,125✔
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,125✔
294
        }
295

296
        return cached;
153,340✔
297
}
298

299
bool socket_ipv6_is_enabled(void) {
112,708✔
300
        _cleanup_free_ char *v = NULL;
112,708✔
301
        int r;
112,708✔
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())
112,708✔
307
                return false;
308

309
        r = sysctl_read_ip_property(AF_INET6, "all", "disable_ipv6", &v);
112,708✔
310
        if (r < 0) {
112,708✔
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);
112,708✔
316
        if (r < 0) {
112,708✔
317
                log_debug_errno(r, "Failed to pare 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
×
318
                return true;
×
319
        }
320

321
        return !r;
112,708✔
322
}
323

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

328
        assert(a);
1,530✔
329
        assert(fd >= 0);
1,530✔
330

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

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

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

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

345
        if (a->protocol != 0)  {
529✔
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);
529✔
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);
×
UNCOV
363
        assert(ret_port);
×
364

UNCOV
365
        switch (sa->sa.sa_family) {
×
366

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

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

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

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

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

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

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

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

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

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

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

409
        assert(u);
1,137✔
410
        assert(a);
1,137✔
411

412
        switch (family) {
1,137✔
413

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

421
                return 0;
1,044✔
422

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

430
                return 0;
93✔
431

432
        default:
433
                return -EAFNOSUPPORT;
434

435
        }
436
}
437

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

445
        union sockaddr_union *sa = (union sockaddr_union*) _sa;
10,957✔
446
        char *p;
10,957✔
447
        int r;
10,957✔
448

449
        assert(sa);
10,957✔
450
        assert(salen >= sizeof(sa->sa.sa_family));
10,957✔
451
        assert(ret);
10,957✔
452

453
        switch (sa->sa.sa_family) {
10,957✔
454

455
        case AF_INET: {
113✔
456
                uint32_t a;
113✔
457

458
                a = be32toh(sa->in.sin_addr.s_addr);
113✔
459

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

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

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

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

514
                break;
515
        }
516

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

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

536
                                _cleanup_free_ char *e = NULL;
8✔
537

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

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

548
                                p = cescape_length(path, path_len);
10,661✔
549
                        }
550
                }
551
                if (!p)
10,804✔
552
                        return -ENOMEM;
553

554
                break;
555

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

568
        default:
569
                return -EOPNOTSUPP;
570
        }
571

572
        *ret = p;
10,957✔
573
        return 0;
10,957✔
574
}
575

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

581
        assert(fd >= 0);
134✔
582
        assert(ret);
134✔
583

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

587
        if (sa.sa.sa_family == AF_UNIX) {
134✔
588
                struct ucred ucred = UCRED_INVALID;
133✔
589

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

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

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

600
                return 0;
133✔
601
        }
602

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

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

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

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

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

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

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

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

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

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

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

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

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

671
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
673✔
672

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

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

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

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

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

689
        return false;
690
}
691

692
int fd_set_sndbuf(int fd, size_t n, bool increase) {
421,485✔
693
        int r, value;
421,485✔
694
        socklen_t l = sizeof(value);
421,485✔
695

696
        if (n > INT_MAX)
421,485✔
697
                return -ERANGE;
421,485✔
698

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

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

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

715
        /* If we have the privileges we will ignore the kernel limit. */
716
        r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUFFORCE, n);
420,659✔
717
        if (r < 0)
420,659✔
718
                return r;
31,322✔
719

720
        return 1;
721
}
722

723
int fd_set_rcvbuf(int fd, size_t n, bool increase) {
32,867✔
724
        int r, value;
32,867✔
725
        socklen_t l = sizeof(value);
32,867✔
726

727
        if (n > INT_MAX)
32,867✔
728
                return -ERANGE;
32,867✔
729

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

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

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

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

751
        return 1;
752
}
753

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

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

763
bool ifname_valid_char(char a) {
497,513✔
764
        if ((unsigned char) a >= 127U)
497,513✔
765
                return false;
766

767
        if ((unsigned char) a <= 32U)
497,513✔
768
                return false;
769

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

776
        return true;
777
}
778

779
bool ifname_valid_full(const char *p, IfnameValidFlags flags) {
142,467✔
780
        bool numeric = true;
142,467✔
781

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

786
        assert(!(flags & ~_IFNAME_VALID_ALL));
142,467✔
787

788
        if (isempty(p))
142,467✔
789
                return false;
790

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

795
        if (flags & IFNAME_VALID_ALTERNATIVE) {
137,538✔
796
                if (strlen(p) >= ALTIFNAMSIZ)
13,509✔
797
                        return false;
798
        } else {
799
                if (strlen(p) >= IFNAMSIZ)
124,029✔
800
                        return false;
801
        }
802

803
        if (dot_or_dot_dot(p))
137,531✔
804
                return false;
805

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

811
        for (const char *t = p; *t; t++) {
627,752✔
812
                if (!ifname_valid_char(*t))
490,237✔
813
                        return false;
814

815
                numeric = numeric && ascii_isdigit(*t);
627,742✔
816
        }
817

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

823
        return true;
824
}
825

826
bool address_label_valid(const char *p) {
44✔
827

828
        POINTER_MAY_BE_NULL(p);
44✔
829

830
        if (isempty(p))
44✔
831
                return false;
832

833
        if (strlen(p) >= IFNAMSIZ)
44✔
834
                return false;
835

836
        while (*p) {
376✔
837
                if ((uint8_t) *p >= 127U)
332✔
838
                        return false;
839

840
                if ((uint8_t) *p <= 31U)
332✔
841
                        return false;
842
                p++;
332✔
843
        }
844

845
        return true;
846
}
847

848
int getpeercred(int fd, struct ucred *ucred) {
85,692✔
849
        socklen_t n = sizeof(struct ucred);
85,692✔
850
        struct ucred u;
85,692✔
851

852
        assert(fd >= 0);
85,692✔
853
        assert(ucred);
85,692✔
854

855
        if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n) < 0)
85,692✔
UNCOV
856
                return -errno;
×
857

858
        if (n != sizeof(struct ucred))
85,692✔
859
                return -EIO;
860

861
        /* Check if the data is actually useful and not suppressed due to namespacing issues */
862
        if (!pid_is_valid(u.pid))
85,692✔
863
                return -ENODATA;
864

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

868
        *ucred = u;
85,692✔
869
        return 0;
85,692✔
870
}
871

872
int getpeersec(int fd, char **ret) {
19,340✔
873
        _cleanup_free_ char *s = NULL;
38,680✔
874
        socklen_t n = 64;
19,340✔
875

876
        assert(fd >= 0);
19,340✔
877
        assert(ret);
19,340✔
878

879
        for (;;) {
19,340✔
880
                s = new0(char, n+1);
19,340✔
881
                if (!s)
19,340✔
882
                        return -ENOMEM;
883

884
                if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n) >= 0) {
19,340✔
885
                        s[n] = 0;
8,733✔
886
                        break;
8,733✔
887
                }
888

889
                if (errno != ERANGE)
10,607✔
890
                        return -errno;
10,607✔
891

UNCOV
892
                s = mfree(s);
×
893
        }
894

895
        if (isempty(s))
8,733✔
896
                return -EOPNOTSUPP;
897

898
        *ret = TAKE_PTR(s);
8,733✔
899

900
        return 0;
8,733✔
901
}
902

903
int getpeergroups(int fd, gid_t **ret) {
19,341✔
904
        socklen_t n = sizeof(gid_t) * 64U;
19,341✔
905
        _cleanup_free_ gid_t *d = NULL;
19,341✔
906

907
        assert(fd >= 0);
19,341✔
908
        assert(ret);
19,341✔
909

910
        long ngroups_max = sysconf(_SC_NGROUPS_MAX);
19,341✔
911
        if (ngroups_max > 0)
19,341✔
912
                n = MAX(n, sizeof(gid_t) * (socklen_t) ngroups_max);
19,341✔
913

914
        for (;;) {
19,341✔
915
                d = malloc(n);
19,341✔
916
                if (!d)
19,341✔
917
                        return -ENOMEM;
918

919
                if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
19,341✔
920
                        break;
921

922
                if (errno != ERANGE)
×
UNCOV
923
                        return -errno;
×
924

UNCOV
925
                d = mfree(d);
×
926
        }
927

928
        assert_se(n % sizeof(gid_t) == 0);
19,341✔
929
        n /= sizeof(gid_t);
19,341✔
930

931
        if (n > INT_MAX)
19,341✔
932
                return -E2BIG;
933

934
        *ret = TAKE_PTR(d);
19,341✔
935

936
        return (int) n;
19,341✔
937
}
938

939
int getpeerpidfd(int fd) {
20,009✔
940
        socklen_t n = sizeof(int);
20,009✔
941
        int pidfd = -EBADF;
20,009✔
942

943
        assert(fd >= 0);
20,009✔
944

945
        if (getsockopt(fd, SOL_SOCKET, SO_PEERPIDFD, &pidfd, &n) < 0)
20,009✔
UNCOV
946
                return -errno;
×
947

948
        if (n != sizeof(int))
20,009✔
949
                return -EIO;
950

951
        return pidfd;
20,009✔
952
}
953

954
int getpeerpidref(int fd, PidRef *ret) {
4✔
955
        int r;
4✔
956

957
        assert(fd >= 0);
4✔
958
        assert(ret);
4✔
959

960
        int pidfd = getpeerpidfd(fd);
4✔
961
        if (pidfd < 0) {
4✔
962
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(pidfd))
×
963
                        return pidfd;
×
964

UNCOV
965
                struct ucred ucred;
×
UNCOV
966
                r = getpeercred(fd, &ucred);
×
967
                if (r < 0)
×
968
                        return r;
969

UNCOV
970
                return pidref_set_pid(ret, ucred.pid);
×
971
        }
972

973
        return pidref_set_pidfd_consume(ret, pidfd);
4✔
974
}
975

976
ssize_t send_one_fd_iov_sa(
1,019✔
977
                int transport_fd,
978
                int fd,
979
                const struct iovec *iov, size_t iovlen,
980
                const struct sockaddr *sa, socklen_t len,
981
                int flags) {
982

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

992
        assert(transport_fd >= 0);
1,019✔
993

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

1001
        if (fd >= 0) {
1,018✔
1002
                struct cmsghdr *cmsg;
1,014✔
1003

1004
                mh.msg_control = &control;
1,014✔
1005
                mh.msg_controllen = sizeof(control);
1,014✔
1006

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

1017
        return k;
1018
}
1019

1020
int send_one_fd_sa(
3✔
1021
                int transport_fd,
1022
                int fd,
1023
                const struct sockaddr *sa, socklen_t len,
1024
                int flags) {
1025

1026
        assert(fd >= 0);
3✔
1027

1028
        return (int) send_one_fd_iov_sa(transport_fd, fd, NULL, 0, sa, len, flags);
3✔
1029
}
1030

1031
ssize_t receive_one_fd_iov(
6,903✔
1032
                int transport_fd,
1033
                struct iovec *iov, size_t iovlen,
1034
                int flags,
1035
                int *ret_fd) {
1036

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

1047
        assert(transport_fd >= 0);
6,903✔
1048
        assert(ret_fd);
6,903✔
1049

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

1058
        k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
6,903✔
1059
        if (k < 0)
6,903✔
1060
                return k;
6,903✔
1061

1062
        found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
6,732✔
1063
        if (!found) {
6,732✔
1064
                cmsg_close_all(&mh);
2,078✔
1065

1066
                /* If didn't receive an FD or any data, return an error. */
1067
                if (k == 0)
2,078✔
1068
                        return -EIO;
1069
        }
1070

1071
        if (found)
4,658✔
1072
                *ret_fd = *CMSG_TYPED_DATA(found, int);
4,654✔
1073
        else
1074
                *ret_fd = -EBADF;
4✔
1075

1076
        return k;
1077
}
1078

1079
int receive_one_fd(int transport_fd, int flags) {
925✔
1080
        int fd;
925✔
1081
        ssize_t k;
925✔
1082

1083
        k = receive_one_fd_iov(transport_fd, NULL, 0, flags, &fd);
925✔
1084
        if (k == 0)
925✔
1085
                return fd;
841✔
1086

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

1093
ssize_t next_datagram_size_fd(int fd) {
211,416✔
1094
        ssize_t l;
211,416✔
1095
        int k;
211,416✔
1096

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

1103
        l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
211,416✔
1104
        if (l < 0) {
211,416✔
1105
                if (IN_SET(errno, EOPNOTSUPP, EFAULT))
658✔
UNCOV
1106
                        goto fallback;
×
1107

1108
                return -errno;
658✔
1109
        }
1110
        if (l == 0)
210,758✔
1111
                goto fallback;
75✔
1112

1113
        return l;
1114

1115
fallback:
75✔
1116
        k = 0;
75✔
1117

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

1121
        if (ioctl(fd, FIONREAD, &k) < 0)
75✔
UNCOV
1122
                return -errno;
×
1123

1124
        return (ssize_t) k;
75✔
1125
}
1126

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

1131
int flush_accept(int fd) {
15✔
1132

1133
        int r, b;
15✔
1134
        socklen_t l = sizeof(b);
15✔
1135

1136
        /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1137
         * them. */
1138

1139
        if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
15✔
UNCOV
1140
                return -errno;
×
1141

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

1150
        for (unsigned iteration = 0;; iteration++) {
5✔
1151
                int cfd;
12✔
1152

1153
                r = fd_wait_for_event(fd, POLLIN, 0);
12✔
1154
                if (r == -EINTR)
12✔
UNCOV
1155
                        continue;
×
1156
                if (r <= 0)
12✔
1157
                        return r;
1158

1159
                if (iteration >= MAX_FLUSH_ITERATIONS)
5✔
UNCOV
1160
                        return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
×
1161
                                               "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS) " iterations.");
1162

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

1168
                        if (ERRNO_IS_ACCEPT_AGAIN(errno))
×
UNCOV
1169
                                continue;
×
1170

UNCOV
1171
                        return -errno;
×
1172
                }
1173

1174
                safe_close(cfd);
5✔
1175
        }
1176
}
1177

1178
ssize_t flush_mqueue(int fd) {
×
1179
        _cleanup_free_ char *buf = NULL;
×
UNCOV
1180
        struct mq_attr attr;
×
1181
        ssize_t count = 0;
×
UNCOV
1182
        int r;
×
1183

UNCOV
1184
        assert(fd >= 0);
×
1185

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

1188
        for (;;) {
×
1189
                ssize_t l;
×
1190

1191
                r = fd_wait_for_event(fd, POLLIN, /* timeout= */ 0);
×
1192
                if (r == -EINTR)
×
1193
                        continue;
×
UNCOV
1194
                if (r < 0)
×
UNCOV
1195
                        return r;
×
1196
                if (r == 0)
×
1197
                        return count;
1198

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

UNCOV
1204
                        buf = malloc(attr.mq_msgsize);
×
UNCOV
1205
                        if (!buf)
×
1206
                                return -ENOMEM;
1207
                }
1208

1209
                l = mq_receive(fd, buf, attr.mq_msgsize, /* msg_prio= */ NULL);
×
UNCOV
1210
                if (l < 0) {
×
1211
                        if (errno == EINTR)
×
UNCOV
1212
                                continue;
×
1213

1214
                        if (errno == EAGAIN)
×
1215
                                return count;
1216

1217
                        return -errno;
×
1218
                }
1219

UNCOV
1220
                count += l;
×
1221
        }
1222
}
1223

1224
struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
404,051✔
1225
        struct cmsghdr *cmsg;
404,051✔
1226

1227
        assert(mh);
404,051✔
1228

1229
        CMSG_FOREACH(cmsg, mh)
808,738✔
1230
                if (cmsg->cmsg_level == level &&
368,205✔
1231
                    cmsg->cmsg_type == type &&
367,887✔
1232
                    (length == (socklen_t) -1 || length == cmsg->cmsg_len))
367,049✔
1233
                        return cmsg;
1234

1235
        return NULL;
1236
}
1237

1238
void* cmsg_find_and_copy_data(struct msghdr *mh, int level, int type, void *buf, size_t buf_len) {
352✔
1239
        struct cmsghdr *cmsg;
352✔
1240

1241
        assert(mh);
352✔
1242
        assert(buf);
352✔
1243
        assert(buf_len > 0);
352✔
1244

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

1249
        cmsg = cmsg_find(mh, level, type, CMSG_LEN(buf_len));
352✔
1250
        if (!cmsg)
352✔
1251
                return NULL;
1252

1253
        return memcpy_safe(buf, CMSG_DATA(cmsg), buf_len);
345✔
1254
}
1255

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

1261
        assert(sa->sll_family == AF_PACKET);
361✔
1262

1263
        size_t mac_len = sizeof(sa->sll_addr);
361✔
1264

1265
        if (be16toh(sa->sll_hatype) == ARPHRD_ETHER)
361✔
1266
                mac_len = MAX(mac_len, (size_t) ETH_ALEN);
361✔
1267
        if (be16toh(sa->sll_hatype) == ARPHRD_INFINIBAND)
361✔
UNCOV
1268
                mac_len = MAX(mac_len, (size_t) INFINIBAND_ALEN);
×
1269

1270
        return offsetof(struct sockaddr_ll, sll_addr) + mac_len;
361✔
1271
}
1272

1273
size_t sockaddr_un_len(const struct sockaddr_un *sa) {
2,589✔
1274
        /* Covers only file system and abstract AF_UNIX socket addresses, but not unnamed socket addresses. */
1275

1276
        assert(sa->sun_family == AF_UNIX);
2,589✔
1277

1278
        return offsetof(struct sockaddr_un, sun_path) +
7,767✔
1279
                (sa->sun_path[0] == 0 ?
2,589✔
1280
                        1 + strnlen(sa->sun_path+1, sizeof(sa->sun_path)-1) :
640✔
1281
                        strnlen(sa->sun_path, sizeof(sa->sun_path))+1);
1,949✔
1282
}
1283

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

1303
int socket_ioctl_fd(void) {
4,943✔
1304
        int fd;
4,943✔
1305

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

1311
        fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
4,943✔
1312
        if (fd < 0)
4,943✔
UNCOV
1313
                fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
×
UNCOV
1314
        if (fd < 0)
×
UNCOV
1315
                return -errno;
×
1316

1317
        return fd;
1318
}
1319

1320
int sockaddr_un_unlink(const struct sockaddr_un *sa) {
1,759✔
1321
        const char *p, * nul;
1,759✔
1322

1323
        assert(sa);
1,759✔
1324

1325
        if (sa->sun_family != AF_UNIX)
1,759✔
1326
                return -EPROTOTYPE;
1327

1328
        if (sa->sun_path[0] == 0) /* Nothing to do for abstract sockets */
1,759✔
1329
                return 0;
1330

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

1338
        if (unlink(p) < 0)
1,759✔
1339
                return -errno;
1,342✔
1340

1341
        return 1;
1342
}
1343

1344
int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path) {
408,422✔
1345
        size_t l;
408,422✔
1346

1347
        assert(ret);
408,422✔
1348
        assert(path);
408,422✔
1349

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

1355
        l = strlen(path);
408,422✔
1356
        if (l < 2)
408,422✔
1357
                return -EINVAL;
1358
        if (!IN_SET(path[0], '/', '@'))
408,421✔
1359
                return -EINVAL;
1360

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

1371
        *ret = (struct sockaddr_un) {
408,419✔
1372
                .sun_family = AF_UNIX,
1373
        };
1374

1375
        if (path[0] == '@') {
408,419✔
1376
                /* Abstract namespace socket */
1377
                memcpy(ret->sun_path + 1, path + 1, l); /* copy *with* trailing NUL byte */
216,590✔
1378
                return (int) (offsetof(struct sockaddr_un, sun_path) + l); /* 🔥 *don't* 🔥 include trailing NUL in size */
216,590✔
1379

1380
        } else {
1381
                assert(path[0] == '/');
191,829✔
1382

1383
                /* File system socket */
1384
                memcpy(ret->sun_path, path, l + 1); /* copy *with* trailing NUL byte */
191,829✔
1385
                return (int) (offsetof(struct sockaddr_un, sun_path) + l + 1); /* include trailing NUL in size */
191,829✔
1386
        }
1387
}
1388

1389
int getsockopt_int(int fd, int level, int optname, int *ret) {
13,531✔
1390
        int v;
13,531✔
1391
        socklen_t sl = sizeof(v);
13,531✔
1392

1393
        assert(fd >= 0);
13,531✔
1394
        assert(ret);
13,531✔
1395

1396
        if (getsockopt(fd, level, optname, &v, &sl) < 0)
13,531✔
1397
                return negative_errno();
57✔
1398
        if (sl != sizeof(v))
13,474✔
1399
                return -EIO;
1400

1401
        *ret = v;
13,474✔
1402
        return 0;
13,474✔
1403
}
1404

1405
int socket_bind_to_ifname(int fd, const char *ifname) {
1✔
1406
        assert(fd >= 0);
1✔
1407

1408
        /* Call with NULL to drop binding */
1409

1410
        return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen_ptr(ifname)));
2✔
1411
}
1412

1413
int socket_bind_to_ifindex(int fd, int ifindex) {
835✔
1414
        assert(fd >= 0);
835✔
1415

1416
        if (ifindex <= 0)
835✔
1417
                /* Drop binding */
1418
                return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, NULL, 0));
57✔
1419

1420
        return setsockopt_int(fd, SOL_SOCKET, SO_BINDTOIFINDEX, ifindex);
778✔
1421
}
1422

1423
int socket_autobind(int fd, char **ret_name) {
482✔
1424
        _cleanup_free_ char *name = NULL;
482✔
1425
        uint64_t random;
482✔
1426
        int r;
482✔
1427

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

1431
        assert(fd >= 0);
482✔
1432

1433
        random = random_u64();
482✔
1434

1435
        if (asprintf(&name, "@%" PRIu64, random) < 0)
482✔
1436
                return -ENOMEM;
1437

1438
        union sockaddr_union sa;
482✔
1439
        assert_cc(DECIMAL_STR_MAX(uint64_t) < sizeof(sa.un.sun_path));
482✔
1440

1441
        r = sockaddr_un_set_path(&sa.un, name);
482✔
1442
        if (r < 0)
482✔
1443
                return r;
1444

1445
        if (bind(fd, &sa.sa, r) < 0)
482✔
UNCOV
1446
                return -errno;
×
1447

1448
        if (ret_name)
482✔
1449
                *ret_name = TAKE_PTR(name);
480✔
1450
        return 0;
1451
}
1452

1453
ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags) {
1,006,186✔
1454
        ssize_t n;
1,006,186✔
1455

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

1461
        assert(sockfd >= 0);
1,006,186✔
1462
        assert(msg);
1,006,186✔
1463

1464
        n = recvmsg(sockfd, msg, flags);
1,006,186✔
1465
        if (n < 0)
1,006,186✔
1466
                return -errno;
58,883✔
1467

1468
        if (FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ||
947,303✔
1469
            (!FLAGS_SET(flags, MSG_PEEK) && FLAGS_SET(msg->msg_flags, MSG_TRUNC))) {
947,303✔
UNCOV
1470
                cmsg_close_all(msg);
×
UNCOV
1471
                return FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ? -ECHRNG : -EXFULL;
×
1472
        }
1473

1474
        return n;
1475
}
1476

1477
int socket_get_family(int fd) {
113,862✔
1478
        int af;
113,862✔
1479
        socklen_t sl = sizeof(af);
113,862✔
1480

1481
        if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &af, &sl) < 0)
113,862✔
UNCOV
1482
                return -errno;
×
1483

1484
        if (sl != sizeof(af))
113,862✔
1485
                return -EINVAL;
1486

1487
        return af;
113,862✔
1488
}
1489

1490
int socket_set_recvpktinfo(int fd, int af, bool b) {
18,760✔
1491

1492
        if (af == AF_UNSPEC) {
18,760✔
UNCOV
1493
                af = socket_get_family(fd);
×
UNCOV
1494
                if (af < 0)
×
1495
                        return af;
1496
        }
1497

1498
        switch (af) {
18,760✔
1499

1500
        case AF_INET:
9,822✔
1501
                return setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, b);
9,822✔
1502

1503
        case AF_INET6:
8,902✔
1504
                return setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, b);
8,902✔
1505

1506
        case AF_NETLINK:
36✔
1507
                return setsockopt_int(fd, SOL_NETLINK, NETLINK_PKTINFO, b);
36✔
1508

UNCOV
1509
        case AF_PACKET:
×
UNCOV
1510
                return setsockopt_int(fd, SOL_PACKET, PACKET_AUXDATA, b);
×
1511

1512
        default:
1513
                return -EAFNOSUPPORT;
1514
        }
1515
}
1516

1517
int socket_set_unicast_if(int fd, int af, int ifi) {
124✔
1518
        be32_t ifindex_be = htobe32(ifi);
124✔
1519

1520
        if (af == AF_UNSPEC) {
124✔
1521
                af = socket_get_family(fd);
1✔
1522
                if (af < 0)
1✔
1523
                        return af;
124✔
1524
        }
1525

1526
        switch (af) {
124✔
1527

1528
        case AF_INET:
82✔
1529
                return RET_NERRNO(setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
82✔
1530

1531
        case AF_INET6:
42✔
1532
                return RET_NERRNO(setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
42✔
1533

1534
        default:
1535
                return -EAFNOSUPPORT;
1536
        }
1537
}
1538

1539
int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val) {
37,285✔
1540
        if (af == AF_UNSPEC) {
37,285✔
UNCOV
1541
                af = socket_get_family(fd);
×
UNCOV
1542
                if (af < 0)
×
1543
                        return af;
1544
        }
1545

1546
        switch (af) {
37,285✔
1547

1548
        case AF_INET:
19,472✔
1549
                return setsockopt_int(fd, IPPROTO_IP, opt_ipv4, val);
19,472✔
1550

1551
        case AF_INET6:
17,813✔
1552
                return setsockopt_int(fd, IPPROTO_IPV6, opt_ipv6, val);
17,813✔
1553

1554
        default:
1555
                return -EAFNOSUPPORT;
1556
        }
1557
}
1558

1559
int socket_get_mtu(int fd, int af, size_t *ret) {
804✔
1560
        int mtu, r;
804✔
1561

1562
        assert(ret);
804✔
1563

1564
        if (af == AF_UNSPEC) {
804✔
UNCOV
1565
                af = socket_get_family(fd);
×
UNCOV
1566
                if (af < 0)
×
1567
                        return af;
804✔
1568
        }
1569

1570
        switch (af) {
804✔
1571

1572
        case AF_INET:
358✔
1573
                r = getsockopt_int(fd, IPPROTO_IP, IP_MTU, &mtu);
358✔
1574
                break;
1575

1576
        case AF_INET6:
446✔
1577
                r = getsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, &mtu);
446✔
1578
                break;
1579

1580
        default:
1581
                return -EAFNOSUPPORT;
1582
        }
1583

1584
        if (r < 0)
804✔
1585
                return r;
1586
        if (mtu <= 0)
747✔
1587
                return -EINVAL;
1588

1589
        *ret = (size_t) mtu;
747✔
1590
        return 0;
747✔
1591
}
1592

1593
static int connect_unix_path_simple(int fd, const char *path) {
179,071✔
1594
        union sockaddr_union sa = {
179,071✔
1595
                .un.sun_family = AF_UNIX,
1596
        };
1597
        size_t l;
179,071✔
1598

1599
        assert(fd >= 0);
179,071✔
1600
        assert(path);
179,071✔
1601

1602
        l = strlen(path);
179,071✔
1603
        assert(l > 0);
179,071✔
1604
        assert(l < sizeof(sa.un.sun_path));
179,071✔
1605

1606
        memcpy(sa.un.sun_path, path, l + 1);
179,071✔
1607
        return RET_NERRNO(connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + l + 1));
179,071✔
1608
}
1609

1610
static int connect_unix_inode(int fd, int inode_fd) {
14✔
1611
        assert(fd >= 0);
14✔
1612
        assert(inode_fd >= 0);
14✔
1613

1614
        return connect_unix_path_simple(fd, FORMAT_PROC_FD_PATH(inode_fd));
14✔
1615
}
1616

1617
int connect_unix_path(int fd, int dir_fd, const char *path) {
179,071✔
1618
        _cleanup_close_ int inode_fd = -EBADF;
179,071✔
1619

1620
        assert(fd >= 0);
179,071✔
1621
        assert(dir_fd == AT_FDCWD || dir_fd >= 0);
179,071✔
1622

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

1626
        if (!path)
179,071✔
1627
                return connect_unix_inode(fd, dir_fd); /* If no path is specified, then dir_fd refers to the socket inode to connect to. */
1✔
1628

1629
        /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
1630
         * namespace path, since first char is NUL */
1631
        if (isempty(path))
358,141✔
1632
                return -EINVAL;
1633

1634
        /* Shortcut for the simple case */
1635
        if (dir_fd == AT_FDCWD && strlen(path) < sizeof_field(struct sockaddr_un, sun_path))
179,070✔
1636
                return connect_unix_path_simple(fd, path);
179,057✔
1637

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

1642
        inode_fd = openat(dir_fd, path, O_PATH|O_CLOEXEC);
13✔
1643
        if (inode_fd < 0)
13✔
UNCOV
1644
                return -errno;
×
1645

1646
        return connect_unix_inode(fd, inode_fd);
13✔
1647
}
1648

1649
int socket_address_parse_unix(SocketAddress *ret_address, const char *s) {
228,724✔
1650
        struct sockaddr_un un;
228,724✔
1651
        int r;
228,724✔
1652

1653
        assert(ret_address);
228,724✔
1654
        assert(s);
228,724✔
1655

1656
        if (!IN_SET(*s, '/', '@'))
228,724✔
1657
                return -EPROTO;
228,724✔
1658

1659
        r = sockaddr_un_set_path(&un, s);
228,283✔
1660
        if (r < 0)
228,283✔
1661
                return r;
1662

1663
        *ret_address = (SocketAddress) {
228,281✔
1664
                .sockaddr.un = un,
1665
                .size = r,
1666
        };
1667

1668
        return 0;
228,281✔
1669
}
1670

1671
int socket_address_equal_unix(const char *a, const char *b) {
947✔
1672
        SocketAddress socket_a, socket_b;
947✔
1673
        int r;
947✔
1674

1675
        assert(a);
947✔
1676
        assert(b);
947✔
1677

1678
        r = socket_address_parse_unix(&socket_a, a);
947✔
1679
        if (r < 0)
947✔
1680
                return r;
947✔
1681

1682
        r = socket_address_parse_unix(&socket_b, b);
947✔
1683
        if (r < 0)
947✔
1684
                return r;
1685

1686
        return sockaddr_equal(&socket_a.sockaddr, &socket_b.sockaddr);
947✔
1687
}
1688

1689
int vsock_parse_port(const char *s, unsigned *ret) {
367✔
1690
        int r;
367✔
1691

1692
        assert(ret);
367✔
1693

1694
        if (!s)
367✔
1695
                return -EINVAL;
367✔
1696

1697
        unsigned u;
367✔
1698
        r = safe_atou(s, &u);
367✔
1699
        if (r < 0)
367✔
1700
                return r;
1701

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

1705
        if (u == VMADDR_PORT_ANY)
364✔
1706
                return -EINVAL;
1707

1708
        *ret = u;
364✔
1709
        return 0;
364✔
1710
}
1711

1712
int vsock_parse_cid(const char *s, unsigned *ret) {
327✔
1713
        assert(ret);
327✔
1714

1715
        if (!s)
327✔
1716
                return -EINVAL;
1717

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

1721
        if (streq(s, "hypervisor"))
327✔
UNCOV
1722
                *ret = VMADDR_CID_HYPERVISOR;
×
1723
        else if (streq(s, "local"))
327✔
UNCOV
1724
                *ret = VMADDR_CID_LOCAL;
×
1725
        else if (streq(s, "host"))
327✔
UNCOV
1726
                *ret = VMADDR_CID_HOST;
×
1727
        else
1728
                return safe_atou(s, ret);
327✔
1729

1730
        return 0;
1731
}
1732

1733
int socket_address_parse_vsock(SocketAddress *ret_address, const char *s) {
441✔
1734
        /* AF_VSOCK socket in vsock:cid:port notation */
1735
        _cleanup_free_ char *n = NULL;
441✔
1736
        const char *e, *cid_start;
441✔
1737
        unsigned port, cid;
441✔
1738
        int type, r;
441✔
1739

1740
        assert(ret_address);
441✔
1741
        assert(s);
441✔
1742

1743
        if ((cid_start = startswith(s, "vsock:")))
441✔
1744
                type = 0;
1745
        else if ((cid_start = startswith(s, "vsock-dgram:")))
389✔
1746
                type = SOCK_DGRAM;
1747
        else if ((cid_start = startswith(s, "vsock-seqpacket:")))
389✔
1748
                type = SOCK_SEQPACKET;
1749
        else if ((cid_start = startswith(s, "vsock-stream:")))
389✔
1750
                type = SOCK_STREAM;
1751
        else
1752
                return -EPROTO;
1753

1754
        e = strchr(cid_start, ':');
369✔
1755
        if (!e)
369✔
1756
                return -EINVAL;
1757

1758
        r = vsock_parse_port(e+1, &port);
367✔
1759
        if (r < 0)
367✔
1760
                return r;
1761

1762
        n = strndup(cid_start, e - cid_start);
364✔
1763
        if (!n)
364✔
1764
                return -ENOMEM;
1765

1766
        if (isempty(n))
364✔
1767
                cid = VMADDR_CID_ANY;
37✔
1768
        else {
1769
                r = vsock_parse_cid(n, &cid);
327✔
1770
                if (r < 0)
327✔
1771
                        return r;
1772
        }
1773

1774
        *ret_address = (SocketAddress) {
361✔
1775
                .sockaddr.vm = {
1776
                        .svm_family = AF_VSOCK,
1777
                        .svm_cid = cid,
1778
                        .svm_port = port,
1779
                },
1780
                .type = type,
1781
                .size = sizeof(struct sockaddr_vm),
1782
        };
1783

1784
        return 0;
361✔
1785
}
1786

1787
int vsock_get_local_cid(unsigned *ret) {
83✔
1788
        _cleanup_close_ int vsock_fd = -EBADF;
83✔
1789

1790
        vsock_fd = open("/dev/vsock", O_RDONLY|O_CLOEXEC);
83✔
1791
        if (vsock_fd < 0)
83✔
1792
                return log_debug_errno(errno, "Failed to open %s: %m", "/dev/vsock");
16✔
1793

1794
        unsigned tmp;
67✔
1795
        if (ioctl(vsock_fd, IOCTL_VM_SOCKETS_GET_LOCAL_CID, &tmp) < 0)
67✔
UNCOV
1796
                return log_debug_errno(errno, "Failed to query local AF_VSOCK CID: %m");
×
1797
        log_debug("Local AF_VSOCK CID: %u", tmp);
67✔
1798

1799
        /* If ret == NULL, we're just want to check if AF_VSOCK is available, so accept
1800
         * any address. Otherwise, filter out special addresses that are cannot be used
1801
         * to identify _this_ machine from the outside. */
1802
        if (ret && IN_SET(tmp, VMADDR_CID_LOCAL, VMADDR_CID_HOST, VMADDR_CID_ANY))
67✔
UNCOV
1803
                return log_debug_errno(SYNTHETIC_ERRNO(EADDRNOTAVAIL),
×
1804
                                       "IOCTL_VM_SOCKETS_GET_LOCAL_CID returned special value (%u), ignoring.", tmp);
1805

1806
        if (ret)
64✔
1807
                *ret = tmp;
64✔
1808
        return 0;
1809
}
1810

1811
int netlink_socket_get_multicast_groups(int fd, size_t *ret_len, uint32_t **ret_groups) {
12,727✔
1812
        _cleanup_free_ uint32_t *groups = NULL;
25,454✔
1813
        socklen_t len = 0, old_len;
12,727✔
1814

1815
        assert(fd >= 0);
12,727✔
1816

1817
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, NULL, &len) < 0)
12,727✔
UNCOV
1818
                return -errno;
×
1819

1820
        if (len == 0)
12,727✔
1821
                goto finalize;
12,276✔
1822

1823
        groups = new0(uint32_t, len);
451✔
1824
        if (!groups)
451✔
1825
                return -ENOMEM;
1826

1827
        old_len = len;
451✔
1828

1829
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, groups, &len) < 0)
451✔
UNCOV
1830
                return -errno;
×
1831

1832
        if (old_len != len)
451✔
1833
                return -EIO;
1834

1835
finalize:
451✔
1836
        if (ret_len)
12,727✔
1837
                *ret_len = len;
12,727✔
1838
        if (ret_groups)
12,727✔
1839
                *ret_groups = TAKE_PTR(groups);
12,727✔
1840

1841
        return 0;
1842
}
1843

1844
int socket_get_cookie(int fd, uint64_t *ret) {
474✔
1845
        assert(fd >= 0);
474✔
1846

1847
        uint64_t cookie = 0;
474✔
1848
        socklen_t cookie_len = sizeof(cookie);
474✔
1849
        if (getsockopt(fd, SOL_SOCKET, SO_COOKIE, &cookie, &cookie_len) < 0)
474✔
UNCOV
1850
                return -errno;
×
1851

1852
        assert(cookie_len == sizeof(cookie));
474✔
1853
        if (ret)
474✔
1854
                *ret = cookie;
474✔
1855

1856
        return 0;
1857
}
1858

1859
void cmsg_close_all(struct msghdr *mh) {
101,519✔
1860
        assert(mh);
101,519✔
1861

1862
        struct cmsghdr *cmsg;
101,519✔
1863
        CMSG_FOREACH(cmsg, mh) {
339,320✔
1864
                if (cmsg->cmsg_level != SOL_SOCKET)
68,141✔
UNCOV
1865
                        continue;
×
1866

1867
                if (cmsg->cmsg_type == SCM_RIGHTS)
68,141✔
UNCOV
1868
                        close_many(CMSG_TYPED_DATA(cmsg, int),
×
UNCOV
1869
                                   (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
×
1870
                else if (cmsg->cmsg_type == SCM_PIDFD) {
68,141✔
UNCOV
1871
                        assert(cmsg->cmsg_len == CMSG_LEN(sizeof(int)));
×
UNCOV
1872
                        safe_close(*CMSG_TYPED_DATA(cmsg, int));
×
1873
                }
1874
        }
1875
}
101,519✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc