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

systemd / systemd / 28272947092

26 Jun 2026 08:38PM UTC coverage: 72.893% (+0.2%) from 72.703%
28272947092

push

github

poettering
sysupdate: Address review feedback on CheckNew varlink scaffolding

Follow-up to #42422:

 - Rename process_image() to context_process_image(), since it now
   operates on a Context object.
 - Use IN_SET() in image_type_can_sysupdate() instead of a switch.
 - Name the return parameters of context_list_components() ret_xyz, per
   our coding style.
 - Drop a redundant "else" after a return in vl_method_check_new().

9 of 11 new or added lines in 1 file covered. (81.82%)

12567 existing lines in 144 files now uncovered.

341026 of 467845 relevant lines covered (72.89%)

1339355.33 hits per line

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

83.24
/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 <sys/stat.h>
17
#include <unistd.h>
18

19
#include "alloc-util.h"
20
#include "errno-util.h"
21
#include "escape.h"
22
#include "fd-util.h"
23
#include "format-ifname.h"
24
#include "format-util.h"
25
#include "fs-util.h"
26
#include "in-addr-util.h"
27
#include "io-util.h"
28
#include "log.h"
29
#include "memory-util.h"
30
#include "parse-util.h"
31
#include "path-util.h"
32
#include "pidref.h"
33
#include "process-util.h"
34
#include "random-util.h"
35
#include "socket-util.h"
36
#include "sparse-endian.h"
37
#include "string-table.h"
38
#include "string-util.h"
39
#include "strv.h"
40
#include "sysctl-util.h"
41
#include "tmpfile-util.h"
42
#include "xattr-util.h"
43

44
#if ENABLE_IDN
45
#  define IDN_FLAGS NI_IDN
46
#else
47
#  define IDN_FLAGS 0
48
#endif
49

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

59
DEFINE_STRING_TABLE_LOOKUP(socket_address_type, int);
1✔
60

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

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

67
        switch (socket_address_family(a)) {
29,836✔
68

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

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

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

79
                return 0;
80

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

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

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

91
                return 0;
92

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

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

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

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

125
                return 0;
126

127
        case AF_NETLINK:
830✔
128

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

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

135
                return 0;
136

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

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

144
                return 0;
145

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

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

154
        assert(a);
8,412✔
155
        assert(ret);
8,412✔
156

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

164
        if (socket_address_family(a) == AF_NETLINK) {
8,412✔
165
                _cleanup_free_ char *sfamily = NULL;
297✔
166

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

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

175
                return 0;
297✔
176
        }
177

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

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

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

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

192
        /* Invalid addresses are unequal to all */
193
        if (socket_address_verify(a, false) < 0 ||
16,516✔
194
            socket_address_verify(b, false) < 0)
8,258✔
195
                return false;
196

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

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

203
        switch (socket_address_family(a)) {
8,254✔
204

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

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

212
                break;
213

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

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

221
                break;
222

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

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

231
                if (a->sockaddr.un.sun_path[0]) {
7,638✔
232
                        if (!path_equal_or_inode_same(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, 0))
7,592✔
233
                                return false;
787✔
234
                } else {
235
                        if (a->size != b->size)
46✔
236
                                return false;
237

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

242
                break;
243

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

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

251
                break;
252

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

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

260
                break;
261

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

267
        return true;
268
}
269

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

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

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

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

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

289
        if (cached < 0) {
121,535✔
290

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

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

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

303
        return cached;
121,535✔
304
}
305

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

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

313
        if (!socket_ipv6_is_supported())
73,247✔
314
                return false;
315

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

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

328
        return !r;
73,247✔
329
}
330

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

335
        assert(a);
1,406✔
336
        assert(fd >= 0);
1,406✔
337

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

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

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

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

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

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

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

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

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

UNCOV
369
        assert(sa);
×
370
        assert(ret_port);
×
371

372
        switch (sa->sa.sa_family) {
×
373

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

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

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

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

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

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

397
        switch (sa->sa.sa_family) {
342✔
398

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

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

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

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

416
        assert(u);
1,168✔
417
        assert(a);
1,168✔
418

419
        switch (family) {
1,168✔
420

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

428
                return 0;
1,075✔
429

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

437
                return 0;
93✔
438

439
        default:
440
                return -EAFNOSUPPORT;
441

442
        }
443
}
444

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

452
        union sockaddr_union *sa = (union sockaddr_union*) _sa;
16,555✔
453
        char *p;
16,555✔
454
        int r;
16,555✔
455

456
        assert(sa);
16,555✔
457
        assert(salen >= sizeof(sa->sa.sa_family));
16,555✔
458
        assert(ret);
16,555✔
459

460
        switch (sa->sa.sa_family) {
16,555✔
461

462
        case AF_INET: {
96✔
463
                uint32_t a;
96✔
464

465
                a = be32toh(sa->in.sin_addr.s_addr);
96✔
466

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

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

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

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

521
                break;
522
        }
523

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

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

543
                                _cleanup_free_ char *e = NULL;
53✔
544

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

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

555
                                p = cescape_length(path, path_len);
16,096✔
556
                        }
557
                }
558
                if (!p)
16,413✔
559
                        return -ENOMEM;
560

561
                break;
562

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

575
        default:
576
                return -EOPNOTSUPP;
577
        }
578

579
        *ret = p;
16,555✔
580
        return 0;
16,555✔
581
}
582

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

588
        assert(fd >= 0);
264✔
589
        assert(ret);
264✔
590

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

594
        if (sa.sa.sa_family == AF_UNIX) {
264✔
595
                struct ucred ucred = UCRED_INVALID;
262✔
596

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

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

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

607
                return 0;
262✔
608
        }
609

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

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

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

620
        assert(fd >= 0);
4✔
621
        assert(ret);
4✔
622

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

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

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

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

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

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

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

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

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

678
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
1,249✔
679

680
bool sockaddr_equal(const union sockaddr_union *a, const union sockaddr_union *b) {
1,753✔
681
        assert(a);
1,753✔
682
        assert(b);
1,753✔
683

684
        if (a->sa.sa_family != b->sa.sa_family)
1,753✔
685
                return false;
686

687
        if (a->sa.sa_family == AF_INET)
1,752✔
688
                return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
4✔
689

690
        if (a->sa.sa_family == AF_INET6)
1,748✔
691
                return memcmp(&a->in6.sin6_addr, &b->in6.sin6_addr, sizeof(a->in6.sin6_addr)) == 0;
1✔
692

693
        if (a->sa.sa_family == AF_VSOCK)
1,747✔
694
                return a->vm.svm_cid == b->vm.svm_cid;
1✔
695

696
        return false;
697
}
698

699
int fd_set_sndbuf(int fd, size_t n, bool increase) {
469,615✔
700
        int r, value;
469,615✔
701
        socklen_t l = sizeof(value);
469,615✔
702

703
        if (n > INT_MAX)
469,615✔
704
                return -ERANGE;
469,615✔
705

706
        r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
469,615✔
707
        if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
469,615✔
708
                return 0;
709

710
        /* First, try to set the buffer size with SO_SNDBUF. */
711
        r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUF, n);
469,615✔
712
        if (r < 0)
469,615✔
713
                return r;
714

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

722
        /* If we have the privileges we will ignore the kernel limit. */
723
        r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUFFORCE, n);
468,763✔
724
        if (r < 0)
468,763✔
725
                return r;
36,182✔
726

727
        return 1;
728
}
729

730
int fd_set_rcvbuf(int fd, size_t n, bool increase) {
41,772✔
731
        int r, value;
41,772✔
732
        socklen_t l = sizeof(value);
41,772✔
733

734
        if (n > INT_MAX)
41,772✔
735
                return -ERANGE;
41,772✔
736

737
        r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
41,772✔
738
        if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
41,772✔
739
                return 0;
740

741
        /* First, try to set the buffer size with SO_RCVBUF. */
742
        r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUF, n);
41,771✔
743
        if (r < 0)
41,771✔
744
                return r;
745

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

753
        /* If we have the privileges we will ignore the kernel limit. */
754
        r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUFFORCE, n);
40,919✔
755
        if (r < 0)
40,919✔
756
                return r;
5,813✔
757

758
        return 1;
759
}
760

761
static const char* const ip_tos_table[] = {
762
        [IPTOS_LOWDELAY]    = "low-delay",
763
        [IPTOS_THROUGHPUT]  = "throughput",
764
        [IPTOS_RELIABILITY] = "reliability",
765
        [IPTOS_LOWCOST]     = "low-cost",
766
};
767

768
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
5✔
769

770
bool ifname_valid_char(char a) {
378,828✔
771
        if ((unsigned char) a >= 127U)
378,828✔
772
                return false;
773

774
        if ((unsigned char) a <= 32U)
378,828✔
775
                return false;
776

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

783
        return true;
784
}
785

786
bool ifname_valid_full(const char *p, IfnameValidFlags flags) {
102,046✔
787
        bool numeric = true;
102,046✔
788

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

793
        assert(!(flags & ~_IFNAME_VALID_ALL));
102,046✔
794

795
        if (isempty(p))
102,046✔
796
                return false;
797

798
        /* A valid ifindex? If so, it's valid iff IFNAME_VALID_NUMERIC is set */
799
        if (parse_ifindex(p) >= 0)
98,314✔
800
                return flags & IFNAME_VALID_NUMERIC;
57✔
801

802
        if (flags & IFNAME_VALID_ALTERNATIVE) {
98,257✔
803
                if (strlen(p) >= ALTIFNAMSIZ)
13,654✔
804
                        return false;
805
        } else {
806
                if (strlen(p) >= IFNAMSIZ)
84,603✔
807
                        return false;
808
        }
809

810
        if (dot_or_dot_dot(p))
98,250✔
811
                return false;
812

813
        /* Let's refuse "all" and "default" as interface name, to avoid collisions with the special sysctl
814
         * directories /proc/sys/net/{ipv4,ipv6}/conf/{all,default} */
815
        if (!FLAGS_SET(flags, IFNAME_VALID_SPECIAL) && STR_IN_SET(p, "all", "default"))
98,248✔
UNCOV
816
                return false;
×
817

818
        for (const char *t = p; *t; t++) {
470,807✔
819
                if (!ifname_valid_char(*t))
372,573✔
820
                        return false;
821

822
                numeric = numeric && ascii_isdigit(*t);
470,797✔
823
        }
824

825
        /* It's fully numeric but didn't parse as valid ifindex above? if so, it must be too large or zero or
826
         * so, let's refuse that. */
827
        if (numeric)
98,234✔
828
                return false;
2✔
829

830
        return true;
831
}
832

833
bool address_label_valid(const char *p) {
44✔
834

835
        POINTER_MAY_BE_NULL(p);
44✔
836

837
        if (isempty(p))
44✔
838
                return false;
839

840
        if (strlen(p) >= IFNAMSIZ)
44✔
841
                return false;
842

843
        while (*p) {
376✔
844
                if ((uint8_t) *p >= 127U)
332✔
845
                        return false;
846

847
                if ((uint8_t) *p <= 31U)
332✔
848
                        return false;
849
                p++;
332✔
850
        }
851

852
        return true;
853
}
854

855
int getpeercred(int fd, struct ucred *ucred) {
115,132✔
856
        socklen_t n = sizeof(struct ucred);
115,132✔
857
        struct ucred u;
115,132✔
858

859
        assert(fd >= 0);
115,132✔
860
        assert(ucred);
115,132✔
861

862
        if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n) < 0)
115,132✔
UNCOV
863
                return -errno;
×
864

865
        if (n != sizeof(struct ucred))
115,132✔
866
                return -EIO;
867

868
        /* Check if the data is actually useful and not suppressed due to namespacing issues */
869
        if (!pid_is_valid(u.pid))
115,132✔
870
                return -ENODATA;
871

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

875
        *ucred = u;
115,132✔
876
        return 0;
115,132✔
877
}
878

879
int getpeersec(int fd, char **ret) {
29,446✔
880
        _cleanup_free_ char *s = NULL;
58,892✔
881
        socklen_t n = 64;
29,446✔
882

883
        assert(fd >= 0);
29,446✔
884
        assert(ret);
29,446✔
885

886
        for (;;) {
29,446✔
887
                s = new0(char, n+1);
29,446✔
888
                if (!s)
29,446✔
889
                        return -ENOMEM;
890

891
                if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n) >= 0) {
29,446✔
892
                        s[n] = 0;
18,610✔
893
                        break;
18,610✔
894
                }
895

896
                if (errno != ERANGE)
10,836✔
897
                        return -errno;
10,836✔
898

UNCOV
899
                s = mfree(s);
×
900
        }
901

902
        if (isempty(s))
18,610✔
903
                return -EOPNOTSUPP;
904

905
        *ret = TAKE_PTR(s);
18,610✔
906

907
        return 0;
18,610✔
908
}
909

910
int getpeergroups(int fd, gid_t **ret) {
29,447✔
911
        socklen_t n = sizeof(gid_t) * 64U;
29,447✔
912
        _cleanup_free_ gid_t *d = NULL;
29,447✔
913

914
        assert(fd >= 0);
29,447✔
915
        assert(ret);
29,447✔
916

917
        long ngroups_max = sysconf(_SC_NGROUPS_MAX);
29,447✔
918
        if (ngroups_max > 0)
29,447✔
919
                n = MAX(n, sizeof(gid_t) * (socklen_t) ngroups_max);
29,447✔
920

921
        for (;;) {
29,447✔
922
                d = malloc(n);
29,447✔
923
                if (!d)
29,447✔
924
                        return -ENOMEM;
925

926
                if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
29,447✔
927
                        break;
928

UNCOV
929
                if (errno != ERANGE)
×
UNCOV
930
                        return -errno;
×
931

UNCOV
932
                d = mfree(d);
×
933
        }
934

935
        assert_se(n % sizeof(gid_t) == 0);
29,447✔
936
        n /= sizeof(gid_t);
29,447✔
937

938
        if (n > INT_MAX)
29,447✔
939
                return -E2BIG;
940

941
        *ret = TAKE_PTR(d);
29,447✔
942

943
        return (int) n;
29,447✔
944
}
945

946
int getpeerpidfd(int fd) {
30,343✔
947
        socklen_t n = sizeof(int);
30,343✔
948
        int pidfd = -EBADF;
30,343✔
949

950
        assert(fd >= 0);
30,343✔
951

952
        if (getsockopt(fd, SOL_SOCKET, SO_PEERPIDFD, &pidfd, &n) < 0)
30,343✔
UNCOV
953
                return -errno;
×
954

955
        if (n != sizeof(int))
30,343✔
956
                return -EIO;
957

958
        return pidfd;
30,343✔
959
}
960

961
int getpeerpidref(int fd, PidRef *ret) {
4✔
962
        int r;
4✔
963

964
        assert(fd >= 0);
4✔
965
        assert(ret);
4✔
966

967
        int pidfd = getpeerpidfd(fd);
4✔
968
        if (pidfd < 0) {
4✔
969
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(pidfd))
×
970
                        return pidfd;
×
971

UNCOV
972
                struct ucred ucred;
×
973
                r = getpeercred(fd, &ucred);
×
UNCOV
974
                if (r < 0)
×
975
                        return r;
976

UNCOV
977
                return pidref_set_pid(ret, ucred.pid);
×
978
        }
979

980
        return pidref_set_pidfd_consume(ret, pidfd);
4✔
981
}
982

983
ssize_t send_one_fd_iov_sa(
1,112✔
984
                int transport_fd,
985
                int fd,
986
                const struct iovec *iov, size_t iovlen,
987
                const struct sockaddr *sa, socklen_t len,
988
                int flags) {
989

990
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control = {};
1,112✔
991
        struct msghdr mh = {
1,112✔
992
                .msg_name = (struct sockaddr*) sa,
993
                .msg_namelen = len,
994
                .msg_iov = (struct iovec *)iov,
995
                .msg_iovlen = iovlen,
996
        };
997
        ssize_t k;
1,112✔
998

999
        assert(transport_fd >= 0);
1,112✔
1000

1001
        /*
1002
         * We need either an FD or data to send.
1003
         * If there's nothing, return an error.
1004
         */
1005
        if (fd < 0 && !iov)
1,112✔
1006
                return -EINVAL;
1,112✔
1007

1008
        if (fd >= 0) {
1,111✔
1009
                struct cmsghdr *cmsg;
1,107✔
1010

1011
                mh.msg_control = &control;
1,107✔
1012
                mh.msg_controllen = sizeof(control);
1,107✔
1013

1014
                cmsg = CMSG_FIRSTHDR(&mh);
1,107✔
1015
                cmsg->cmsg_level = SOL_SOCKET;
1,107✔
1016
                cmsg->cmsg_type = SCM_RIGHTS;
1,107✔
1017
                cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1,107✔
1018
                memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
1,107✔
1019
        }
1020
        k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
1,111✔
1021
        if (k < 0)
1,111✔
UNCOV
1022
                return (ssize_t) -errno;
×
1023

1024
        return k;
1025
}
1026

1027
int send_one_fd_sa(
4✔
1028
                int transport_fd,
1029
                int fd,
1030
                const struct sockaddr *sa, socklen_t len,
1031
                int flags) {
1032

1033
        assert(fd >= 0);
4✔
1034

1035
        return (int) send_one_fd_iov_sa(transport_fd, fd, NULL, 0, sa, len, flags);
4✔
1036
}
1037

1038
ssize_t receive_one_fd_iov(
7,078✔
1039
                int transport_fd,
1040
                struct iovec *iov, size_t iovlen,
1041
                int flags,
1042
                int *ret_fd) {
1043

1044
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
7,078✔
1045
        struct msghdr mh = {
7,078✔
1046
                .msg_control = &control,
1047
                .msg_controllen = sizeof(control),
1048
                .msg_iov = iov,
1049
                .msg_iovlen = iovlen,
1050
        };
1051
        struct cmsghdr *found;
7,078✔
1052
        ssize_t k;
7,078✔
1053

1054
        assert(transport_fd >= 0);
7,078✔
1055
        assert(ret_fd);
7,078✔
1056

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

1065
        k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
7,078✔
1066
        if (k < 0)
7,078✔
1067
                return k;
7,078✔
1068

1069
        found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
6,857✔
1070
        if (!found) {
6,857✔
1071
                cmsg_close_all(&mh);
2,078✔
1072

1073
                /* If didn't receive an FD or any data, return an error. */
1074
                if (k == 0)
2,078✔
1075
                        return -EIO;
1076
        }
1077

1078
        if (found)
4,783✔
1079
                *ret_fd = *CMSG_TYPED_DATA(found, int);
4,779✔
1080
        else
1081
                *ret_fd = -EBADF;
4✔
1082

1083
        return k;
1084
}
1085

1086
int receive_one_fd(int transport_fd, int flags) {
1,027✔
1087
        int fd;
1,027✔
1088
        ssize_t k;
1,027✔
1089

1090
        k = receive_one_fd_iov(transport_fd, NULL, 0, flags, &fd);
1,027✔
1091
        if (k == 0)
1,027✔
1092
                return fd;
897✔
1093

1094
        /* k must be negative, since receive_one_fd_iov() only returns
1095
         * a positive value if data was received through the iov. */
1096
        assert(k < 0);
130✔
1097
        return (int) k;
130✔
1098
}
1099

1100
ssize_t next_datagram_size_fd(int fd) {
206,352✔
1101
        ssize_t l;
206,352✔
1102
        int k;
206,352✔
1103

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

1110
        l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
206,352✔
1111
        if (l < 0) {
206,352✔
1112
                if (IN_SET(errno, EOPNOTSUPP, EFAULT))
556✔
UNCOV
1113
                        goto fallback;
×
1114

1115
                return -errno;
556✔
1116
        }
1117
        if (l == 0)
205,796✔
1118
                goto fallback;
76✔
1119

1120
        return l;
1121

1122
fallback:
76✔
1123
        k = 0;
76✔
1124

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

1128
        if (ioctl(fd, FIONREAD, &k) < 0)
76✔
UNCOV
1129
                return -errno;
×
1130

1131
        return (ssize_t) k;
76✔
1132
}
1133

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

1138
int flush_accept(int fd) {
18✔
1139

1140
        int r, b;
18✔
1141
        socklen_t l = sizeof(b);
18✔
1142

1143
        /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1144
         * them. */
1145

1146
        if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
18✔
UNCOV
1147
                return -errno;
×
1148

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

1157
        for (unsigned iteration = 0;; iteration++) {
6✔
1158
                int cfd;
16✔
1159

1160
                r = fd_wait_for_event(fd, POLLIN, 0);
16✔
1161
                if (r == -EINTR)
16✔
UNCOV
1162
                        continue;
×
1163
                if (r <= 0)
16✔
1164
                        return r;
1165

1166
                if (iteration >= MAX_FLUSH_ITERATIONS)
6✔
UNCOV
1167
                        return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
×
1168
                                               "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS) " iterations.");
1169

1170
                cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
6✔
1171
                if (cfd < 0) {
6✔
1172
                        if (errno == EAGAIN)
×
1173
                                return 0;
1174

UNCOV
1175
                        if (ERRNO_IS_ACCEPT_AGAIN(errno))
×
UNCOV
1176
                                continue;
×
1177

UNCOV
1178
                        return -errno;
×
1179
                }
1180

1181
                safe_close(cfd);
6✔
1182
        }
1183
}
1184

1185
ssize_t flush_mqueue(int fd) {
×
UNCOV
1186
        _cleanup_free_ char *buf = NULL;
×
1187
        struct mq_attr attr;
×
UNCOV
1188
        ssize_t count = 0;
×
UNCOV
1189
        int r;
×
1190

1191
        assert(fd >= 0);
×
1192

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

1195
        for (;;) {
×
1196
                ssize_t l;
×
1197

1198
                r = fd_wait_for_event(fd, POLLIN, /* timeout= */ 0);
×
1199
                if (r == -EINTR)
×
UNCOV
1200
                        continue;
×
UNCOV
1201
                if (r < 0)
×
1202
                        return r;
×
UNCOV
1203
                if (r == 0)
×
1204
                        return count;
1205

UNCOV
1206
                if (!buf) {
×
1207
                        /* Buffer must be at least as large as mq_msgsize. */
1208
                        if (mq_getattr(fd, &attr) < 0)
×
UNCOV
1209
                                return -errno;
×
1210

UNCOV
1211
                        buf = malloc(attr.mq_msgsize);
×
1212
                        if (!buf)
×
1213
                                return -ENOMEM;
1214
                }
1215

UNCOV
1216
                l = mq_receive(fd, buf, attr.mq_msgsize, /* msg_prio= */ NULL);
×
1217
                if (l < 0) {
×
UNCOV
1218
                        if (errno == EINTR)
×
UNCOV
1219
                                continue;
×
1220

UNCOV
1221
                        if (errno == EAGAIN)
×
1222
                                return count;
1223

UNCOV
1224
                        return -errno;
×
1225
                }
1226

UNCOV
1227
                count += l;
×
1228
        }
1229
}
1230

1231
struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
398,926✔
1232
        struct cmsghdr *cmsg;
398,926✔
1233

1234
        assert(mh);
398,926✔
1235

1236
        CMSG_FOREACH(cmsg, mh)
400,252✔
1237
                if (cmsg->cmsg_level == level &&
361,507✔
1238
                    cmsg->cmsg_type == type &&
361,011✔
1239
                    (length == (socklen_t) -1 || length == cmsg->cmsg_len))
359,963✔
1240
                        return cmsg;
1241

1242
        return NULL;
1243
}
1244

1245
void* cmsg_find_and_copy_data(struct msghdr *mh, int level, int type, void *buf, size_t buf_len) {
388✔
1246
        struct cmsghdr *cmsg;
388✔
1247

1248
        assert(mh);
388✔
1249
        assert(buf);
388✔
1250
        assert(buf_len > 0);
388✔
1251

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

1256
        cmsg = cmsg_find(mh, level, type, CMSG_LEN(buf_len));
388✔
1257
        if (!cmsg)
388✔
1258
                return NULL;
1259

1260
        return memcpy_safe(buf, CMSG_DATA(cmsg), buf_len);
359✔
1261
}
1262

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

1268
        assert(sa->sll_family == AF_PACKET);
443✔
1269

1270
        size_t mac_len = sizeof(sa->sll_addr);
443✔
1271

1272
        if (be16toh(sa->sll_hatype) == ARPHRD_ETHER)
443✔
1273
                mac_len = MAX(mac_len, (size_t) ETH_ALEN);
443✔
1274
        if (be16toh(sa->sll_hatype) == ARPHRD_INFINIBAND)
443✔
UNCOV
1275
                mac_len = MAX(mac_len, (size_t) INFINIBAND_ALEN);
×
1276

1277
        return offsetof(struct sockaddr_ll, sll_addr) + mac_len;
443✔
1278
}
1279

1280
size_t sockaddr_un_len(const struct sockaddr_un *sa) {
3,222✔
1281
        /* Covers only file system and abstract AF_UNIX socket addresses, but not unnamed socket addresses. */
1282

1283
        assert(sa->sun_family == AF_UNIX);
3,222✔
1284

1285
        return offsetof(struct sockaddr_un, sun_path) +
9,666✔
1286
                (sa->sun_path[0] == 0 ?
3,222✔
1287
                        1 + strnlen(sa->sun_path+1, sizeof(sa->sun_path)-1) :
1,245✔
1288
                        strnlen(sa->sun_path, sizeof(sa->sun_path))+1);
1,977✔
1289
}
1290

1291
size_t sockaddr_len(const union sockaddr_union *sa) {
434✔
1292
        assert(sa);
434✔
1293

1294
        switch (sa->sa.sa_family) {
434✔
1295
        case AF_INET:
1296
                return sizeof(struct sockaddr_in);
1297
        case AF_INET6:
132✔
1298
                return sizeof(struct sockaddr_in6);
132✔
1299
        case AF_UNIX:
3✔
1300
                return sockaddr_un_len(&sa->un);
3✔
1301
        case AF_PACKET:
×
1302
                return sockaddr_ll_len(&sa->ll);
×
UNCOV
1303
        case AF_NETLINK:
×
UNCOV
1304
                return sizeof(struct sockaddr_nl);
×
1305
        case AF_VSOCK:
1306
                return sizeof(struct sockaddr_vm);
UNCOV
1307
        default:
×
UNCOV
1308
                assert_not_reached();
×
1309
        }
1310
}
1311

1312
int socket_ioctl_fd(void) {
4,593✔
1313
        int fd;
4,593✔
1314

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

1320
        fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
4,593✔
1321
        if (fd < 0)
4,593✔
UNCOV
1322
                fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
×
UNCOV
1323
        if (fd < 0)
×
UNCOV
1324
                return -errno;
×
1325

1326
        return fd;
1327
}
1328

1329
int sockaddr_un_unlink(const struct sockaddr_un *sa) {
2,137✔
1330
        const char *p, * nul;
2,137✔
1331

1332
        assert(sa);
2,137✔
1333

1334
        if (sa->sun_family != AF_UNIX)
2,137✔
1335
                return -EPROTOTYPE;
1336

1337
        if (sa->sun_path[0] == 0) /* Nothing to do for abstract sockets */
2,137✔
1338
                return 0;
1339

1340
        /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1341
        nul = memchr(sa->sun_path, 0, sizeof(sa->sun_path));
2,137✔
1342
        if (nul)
2,137✔
1343
                p = sa->sun_path;
1344
        else
UNCOV
1345
                p = memdupa_suffix0(sa->sun_path, sizeof(sa->sun_path));
×
1346

1347
        if (unlink(p) < 0)
2,137✔
1348
                return -errno;
1,524✔
1349

1350
        return 1;
1351
}
1352

1353
int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path) {
422,329✔
1354
        size_t l;
422,329✔
1355

1356
        assert(ret);
422,329✔
1357
        assert(path);
422,329✔
1358

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

1364
        l = strlen(path);
422,329✔
1365
        if (l < 2)
422,329✔
1366
                return -EINVAL;
1367
        if (!IN_SET(path[0], '/', '@'))
422,328✔
1368
                return -EINVAL;
1369

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

1380
        *ret = (struct sockaddr_un) {
422,326✔
1381
                .sun_family = AF_UNIX,
1382
        };
1383

1384
        if (path[0] == '@') {
422,326✔
1385
                /* Abstract namespace socket */
1386
                memcpy(ret->sun_path + 1, path + 1, l); /* copy *with* trailing NUL byte */
201,445✔
1387
                return (int) (offsetof(struct sockaddr_un, sun_path) + l); /* 🔥 *don't* 🔥 include trailing NUL in size */
201,445✔
1388

1389
        } else {
1390
                assert(path[0] == '/');
220,881✔
1391

1392
                /* File system socket */
1393
                memcpy(ret->sun_path, path, l + 1); /* copy *with* trailing NUL byte */
220,881✔
1394
                return (int) (offsetof(struct sockaddr_un, sun_path) + l + 1); /* include trailing NUL in size */
220,881✔
1395
        }
1396
}
1397

1398
int getsockopt_int(int fd, int level, int optname, int *ret) {
12,094✔
1399
        int v;
12,094✔
1400
        socklen_t sl = sizeof(v);
12,094✔
1401

1402
        assert(fd >= 0);
12,094✔
1403
        assert(ret);
12,094✔
1404

1405
        if (getsockopt(fd, level, optname, &v, &sl) < 0)
12,094✔
1406
                return negative_errno();
66✔
1407
        if (sl != sizeof(v))
12,028✔
1408
                return -EIO;
1409

1410
        *ret = v;
12,028✔
1411
        return 0;
12,028✔
1412
}
1413

1414
int socket_bind_to_ifname(int fd, const char *ifname) {
1✔
1415
        assert(fd >= 0);
1✔
1416

1417
        /* Call with NULL to drop binding */
1418

1419
        return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen_ptr(ifname)));
2✔
1420
}
1421

1422
int socket_bind_to_ifindex(int fd, int ifindex) {
1,023✔
1423
        assert(fd >= 0);
1,023✔
1424

1425
        if (ifindex <= 0)
1,023✔
1426
                /* Drop binding */
1427
                return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, NULL, 0));
66✔
1428

1429
        return setsockopt_int(fd, SOL_SOCKET, SO_BINDTOIFINDEX, ifindex);
957✔
1430
}
1431

1432
int socket_autobind(int fd, char **ret_name) {
1,173✔
1433
        _cleanup_free_ char *name = NULL;
1,173✔
1434
        uint64_t random;
1,173✔
1435
        int r;
1,173✔
1436

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

1440
        assert(fd >= 0);
1,173✔
1441

1442
        random = random_u64();
1,173✔
1443

1444
        if (asprintf(&name, "@%" PRIu64, random) < 0)
1,173✔
1445
                return -ENOMEM;
1446

1447
        union sockaddr_union sa;
1,173✔
1448
        assert_cc(DECIMAL_STR_MAX(uint64_t) < sizeof(sa.un.sun_path));
1,173✔
1449

1450
        r = sockaddr_un_set_path(&sa.un, name);
1,173✔
1451
        if (r < 0)
1,173✔
1452
                return r;
1453

1454
        if (bind(fd, &sa.sa, r) < 0)
1,173✔
UNCOV
1455
                return -errno;
×
1456

1457
        if (ret_name)
1,173✔
1458
                *ret_name = TAKE_PTR(name);
1,171✔
1459
        return 0;
1460
}
1461

1462
ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags) {
1,323,301✔
1463
        ssize_t n;
1,323,301✔
1464

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

1470
        assert(sockfd >= 0);
1,323,301✔
1471
        assert(msg);
1,323,301✔
1472

1473
        n = recvmsg(sockfd, msg, flags);
1,323,301✔
1474
        if (n < 0)
1,323,301✔
1475
                return -errno;
18,147✔
1476

1477
        if (FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ||
1,305,154✔
1478
            (!FLAGS_SET(flags, MSG_PEEK) && FLAGS_SET(msg->msg_flags, MSG_TRUNC))) {
1,305,154✔
UNCOV
1479
                cmsg_close_all(msg);
×
UNCOV
1480
                return FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ? -ECHRNG : -EXFULL;
×
1481
        }
1482

1483
        return n;
1484
}
1485

1486
int socket_get_family(int fd) {
36,568✔
1487
        int af;
36,568✔
1488
        socklen_t sl = sizeof(af);
36,568✔
1489

1490
        if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &af, &sl) < 0)
36,568✔
UNCOV
1491
                return -errno;
×
1492

1493
        if (sl != sizeof(af))
36,568✔
1494
                return -EINVAL;
1495

1496
        return af;
36,568✔
1497
}
1498

1499
int socket_set_recvpktinfo(int fd, int af, bool b) {
14,835✔
1500

1501
        if (af == AF_UNSPEC) {
14,835✔
UNCOV
1502
                af = socket_get_family(fd);
×
UNCOV
1503
                if (af < 0)
×
1504
                        return af;
1505
        }
1506

1507
        switch (af) {
14,835✔
1508

1509
        case AF_INET:
7,759✔
1510
                return setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, b);
7,759✔
1511

1512
        case AF_INET6:
7,023✔
1513
                return setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, b);
7,023✔
1514

1515
        case AF_NETLINK:
53✔
1516
                return setsockopt_int(fd, SOL_NETLINK, NETLINK_PKTINFO, b);
53✔
1517

UNCOV
1518
        case AF_PACKET:
×
UNCOV
1519
                return setsockopt_int(fd, SOL_PACKET, PACKET_AUXDATA, b);
×
1520

1521
        default:
1522
                return -EAFNOSUPPORT;
1523
        }
1524
}
1525

1526
int socket_set_unicast_if(int fd, int af, int ifi) {
129✔
1527
        be32_t ifindex_be = htobe32(ifi);
129✔
1528

1529
        if (af == AF_UNSPEC) {
129✔
1530
                af = socket_get_family(fd);
1✔
1531
                if (af < 0)
1✔
1532
                        return af;
129✔
1533
        }
1534

1535
        switch (af) {
129✔
1536

1537
        case AF_INET:
91✔
1538
                return RET_NERRNO(setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
91✔
1539

1540
        case AF_INET6:
38✔
1541
                return RET_NERRNO(setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
38✔
1542

1543
        default:
1544
                return -EAFNOSUPPORT;
1545
        }
1546
}
1547

1548
int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val) {
29,020✔
1549
        if (af == AF_UNSPEC) {
29,020✔
UNCOV
1550
                af = socket_get_family(fd);
×
UNCOV
1551
                if (af < 0)
×
1552
                        return af;
1553
        }
1554

1555
        switch (af) {
29,020✔
1556

1557
        case AF_INET:
15,332✔
1558
                return setsockopt_int(fd, IPPROTO_IP, opt_ipv4, val);
15,332✔
1559

1560
        case AF_INET6:
13,688✔
1561
                return setsockopt_int(fd, IPPROTO_IPV6, opt_ipv6, val);
13,688✔
1562

1563
        default:
1564
                return -EAFNOSUPPORT;
1565
        }
1566
}
1567

1568
int socket_get_mtu(int fd, int af, size_t *ret) {
758✔
1569
        int mtu, r;
758✔
1570

1571
        assert(ret);
758✔
1572

1573
        if (af == AF_UNSPEC) {
758✔
UNCOV
1574
                af = socket_get_family(fd);
×
UNCOV
1575
                if (af < 0)
×
1576
                        return af;
758✔
1577
        }
1578

1579
        switch (af) {
758✔
1580

1581
        case AF_INET:
310✔
1582
                r = getsockopt_int(fd, IPPROTO_IP, IP_MTU, &mtu);
310✔
1583
                break;
1584

1585
        case AF_INET6:
448✔
1586
                r = getsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, &mtu);
448✔
1587
                break;
1588

1589
        default:
1590
                return -EAFNOSUPPORT;
1591
        }
1592

1593
        if (r < 0)
758✔
1594
                return r;
1595
        if (mtu <= 0)
692✔
1596
                return -EINVAL;
1597

1598
        *ret = (size_t) mtu;
692✔
1599
        return 0;
692✔
1600
}
1601

1602
static int connect_unix_path_simple(int fd, const char *path) {
232,338✔
1603
        union sockaddr_union sa = {
232,338✔
1604
                .un.sun_family = AF_UNIX,
1605
        };
1606
        size_t l;
232,338✔
1607

1608
        assert(fd >= 0);
232,338✔
1609
        assert(path);
232,338✔
1610

1611
        l = strlen(path);
232,338✔
1612
        assert(l > 0);
232,338✔
1613
        assert(l < sizeof(sa.un.sun_path));
232,338✔
1614

1615
        memcpy(sa.un.sun_path, path, l + 1);
232,338✔
1616
        return RET_NERRNO(connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + l + 1));
232,338✔
1617
}
1618

1619
static int connect_unix_inode(int fd, int inode_fd) {
234✔
1620
        assert(fd >= 0);
234✔
1621
        assert(inode_fd >= 0);
234✔
1622

1623
        return connect_unix_path_simple(fd, FORMAT_PROC_FD_PATH(inode_fd));
234✔
1624
}
1625

1626
int connect_unix_path(int fd, int dir_fd, const char *path) {
232,338✔
1627
        _cleanup_close_ int inode_fd = -EBADF;
232,338✔
1628

1629
        assert(fd >= 0);
232,338✔
1630
        assert(wildcard_fd_is_valid(dir_fd));
232,338✔
1631

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

1635
        if (!path) {
232,338✔
1636
                if (dir_fd < 0)
3✔
1637
                        return -EISDIR;
1638

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

1642
        /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
1643
         * namespace path, since first char is NUL */
1644
        if (isempty(path))
464,673✔
1645
                return -EINVAL;
1646

1647
        /* Shortcut for the simple case */
1648
        if (dir_fd == AT_FDCWD && strlen(path) < sizeof_field(struct sockaddr_un, sun_path))
232,335✔
1649
                return connect_unix_path_simple(fd, path);
232,104✔
1650

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

1655
        if (dir_fd == XAT_FDROOT) {
231✔
1656
                _cleanup_free_ char *j = strjoin("/", path);
2✔
1657
                if (!j)
1✔
1658
                        return -ENOMEM;
×
1659

1660
                inode_fd = open(j, O_PATH|O_CLOEXEC);
1✔
1661
        } else
1662
                inode_fd = openat(dir_fd, path, O_PATH|O_CLOEXEC);
230✔
1663
        if (inode_fd < 0)
231✔
UNCOV
1664
                return -errno;
×
1665

1666
        return connect_unix_inode(fd, inode_fd);
231✔
1667
}
1668

1669
int socket_address_parse_unix(SocketAddress *ret_address, const char *s) {
228,696✔
1670
        struct sockaddr_un un;
228,696✔
1671
        int r;
228,696✔
1672

1673
        assert(ret_address);
228,696✔
1674
        assert(s);
228,696✔
1675

1676
        if (!IN_SET(*s, '/', '@'))
228,696✔
1677
                return -EPROTO;
228,696✔
1678

1679
        r = sockaddr_un_set_path(&un, s);
227,891✔
1680
        if (r < 0)
227,891✔
1681
                return r;
1682

1683
        *ret_address = (SocketAddress) {
227,889✔
1684
                .sockaddr.un = un,
1685
                .size = r,
1686
        };
1687

1688
        return 0;
227,889✔
1689
}
1690

1691
int socket_address_equal_unix(const char *a, const char *b) {
1,746✔
1692
        SocketAddress socket_a, socket_b;
1,746✔
1693
        int r;
1,746✔
1694

1695
        assert(a);
1,746✔
1696
        assert(b);
1,746✔
1697

1698
        r = socket_address_parse_unix(&socket_a, a);
1,746✔
1699
        if (r < 0)
1,746✔
1700
                return r;
1,746✔
1701

1702
        r = socket_address_parse_unix(&socket_b, b);
1,746✔
1703
        if (r < 0)
1,746✔
1704
                return r;
1705

1706
        return sockaddr_equal(&socket_a.sockaddr, &socket_b.sockaddr);
1,746✔
1707
}
1708

1709
int vsock_parse_port(const char *s, unsigned *ret) {
728✔
1710
        int r;
728✔
1711

1712
        assert(ret);
728✔
1713

1714
        if (!s)
728✔
1715
                return -EINVAL;
728✔
1716

1717
        unsigned u;
728✔
1718
        r = safe_atou(s, &u);
728✔
1719
        if (r < 0)
728✔
1720
                return r;
1721

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

1725
        if (u == VMADDR_PORT_ANY)
725✔
1726
                return -EINVAL;
1727

1728
        *ret = u;
725✔
1729
        return 0;
725✔
1730
}
1731

1732
int vsock_parse_cid(const char *s, unsigned *ret) {
678✔
1733
        assert(ret);
678✔
1734

1735
        if (!s)
678✔
1736
                return -EINVAL;
1737

1738
        /* Parsed an AF_VSOCK "CID". This is a 32bit entity, and the usual type is "unsigned". We recognize
1739
         * the four special CIDs as strings, and otherwise parse the numeric CIDs. */
1740

1741
        if (streq(s, "hypervisor"))
678✔
1742
                *ret = VMADDR_CID_HYPERVISOR;
×
1743
        else if (streq(s, "local"))
678✔
UNCOV
1744
                *ret = VMADDR_CID_LOCAL;
×
1745
        else if (streq(s, "host"))
678✔
UNCOV
1746
                *ret = VMADDR_CID_HOST;
×
1747
        else if (STR_IN_SET(s, "any", "-1"))
678✔
UNCOV
1748
                *ret = VMADDR_CID_ANY;
×
1749
        else
1750
                return safe_atou(s, ret);
678✔
1751

1752
        return 0;
1753
}
1754

1755
int socket_address_parse_vsock(SocketAddress *ret_address, const char *s) {
805✔
1756
        /* AF_VSOCK socket in vsock:cid:port notation */
1757
        _cleanup_free_ char *n = NULL;
805✔
1758
        const char *e, *cid_start;
805✔
1759
        unsigned port, cid;
805✔
1760
        int type, r;
805✔
1761

1762
        assert(ret_address);
805✔
1763
        assert(s);
805✔
1764

1765
        if ((cid_start = startswith(s, "vsock:")))
805✔
1766
                type = 0;
1767
        else if ((cid_start = startswith(s, "vsock-dgram:")))
743✔
1768
                type = SOCK_DGRAM;
1769
        else if ((cid_start = startswith(s, "vsock-seqpacket:")))
743✔
1770
                type = SOCK_SEQPACKET;
1771
        else if ((cid_start = startswith(s, "vsock-stream:")))
743✔
1772
                type = SOCK_STREAM;
1773
        else
1774
                return -EPROTO;
1775

1776
        e = strchr(cid_start, ':');
730✔
1777
        if (!e)
730✔
1778
                return -EINVAL;
1779

1780
        r = vsock_parse_port(e+1, &port);
728✔
1781
        if (r < 0)
728✔
1782
                return r;
1783

1784
        n = strndup(cid_start, e - cid_start);
725✔
1785
        if (!n)
725✔
1786
                return -ENOMEM;
1787

1788
        if (isempty(n))
725✔
1789
                cid = VMADDR_CID_ANY;
47✔
1790
        else {
1791
                r = vsock_parse_cid(n, &cid);
678✔
1792
                if (r < 0)
678✔
1793
                        return r;
1794
        }
1795

1796
        *ret_address = (SocketAddress) {
722✔
1797
                .sockaddr.vm = {
1798
                        .svm_family = AF_VSOCK,
1799
                        .svm_cid = cid,
1800
                        .svm_port = port,
1801
                },
1802
                .type = type,
1803
                .size = sizeof(struct sockaddr_vm),
1804
        };
1805

1806
        return 0;
722✔
1807
}
1808

1809
int netlink_socket_get_multicast_groups(int fd, size_t *ret_len, uint32_t **ret_groups) {
11,279✔
1810
        _cleanup_free_ uint32_t *groups = NULL;
22,558✔
1811
        socklen_t len = 0, old_len;
11,279✔
1812

1813
        assert(fd >= 0);
11,279✔
1814

1815
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, NULL, &len) < 0)
11,279✔
UNCOV
1816
                return -errno;
×
1817

1818
        if (len == 0)
11,279✔
1819
                goto finalize;
10,816✔
1820

1821
        groups = new0(uint32_t, len);
463✔
1822
        if (!groups)
463✔
1823
                return -ENOMEM;
1824

1825
        old_len = len;
463✔
1826

1827
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, groups, &len) < 0)
463✔
UNCOV
1828
                return -errno;
×
1829

1830
        if (old_len != len)
463✔
1831
                return -EIO;
1832

1833
finalize:
463✔
1834
        if (ret_len)
11,279✔
1835
                *ret_len = len;
11,279✔
1836
        if (ret_groups)
11,279✔
1837
                *ret_groups = TAKE_PTR(groups);
11,279✔
1838

1839
        return 0;
1840
}
1841

1842
int socket_get_cookie(int fd, uint64_t *ret) {
725✔
1843
        assert(fd >= 0);
725✔
1844

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

1850
        assert(cookie_len == sizeof(cookie));
725✔
1851
        if (ret)
725✔
1852
                *ret = cookie;
725✔
1853

1854
        return 0;
1855
}
1856

1857
void cmsg_close_all(struct msghdr *mh) {
112,083✔
1858
        assert(mh);
112,083✔
1859

1860
        struct cmsghdr *cmsg;
112,083✔
1861
        CMSG_FOREACH(cmsg, mh) {
259,821✔
1862
                if (cmsg->cmsg_level != SOL_SOCKET)
73,869✔
1863
                        continue;
×
1864

1865
                if (cmsg->cmsg_type == SCM_RIGHTS)
73,869✔
1866
                        close_many(CMSG_TYPED_DATA(cmsg, int),
1✔
1867
                                   (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
1✔
1868
                else if (cmsg->cmsg_type == SCM_PIDFD) {
73,868✔
UNCOV
1869
                        assert(cmsg->cmsg_len == CMSG_LEN(sizeof(int)));
×
UNCOV
1870
                        safe_close(*CMSG_TYPED_DATA(cmsg, int));
×
1871
                }
1872
        }
1873
}
112,083✔
1874

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

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

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

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

1895
        case IPTOS_PREC_ROUTINE:         /* 0x00 (CS0) - Routine. Best effort traffic. */
2✔
1896
        default:
1897
                return TC_PRIO_BESTEFFORT;
2✔
1898
        }
1899
}
1900

1901
int socket_xattr_supported(void) {
298,364✔
1902
        int r;
298,364✔
1903

1904
        // FIXME: Drop this check once Linux 7.0 becomes our baseline
1905

1906
        /* Checks if socket inodes may have xattrs on this kernel. This should pass on kernel 7.0, fail on
1907
         * older kernels */
1908

1909
        static int cached = -1;
298,364✔
1910
        if (cached >= 0)
298,364✔
1911
                return cached;
298,364✔
1912

1913
        const char *t;
14,772✔
1914
        r = tmp_dir(&t);
14,772✔
1915
        if (r < 0)
14,772✔
1916
                return r;
1917

1918
        _cleanup_free_ char *sp = NULL;
14,772✔
1919
        r = tempfn_random_child(t, "sockxattrtest", &sp);
14,772✔
1920
        if (r < 0)
14,772✔
1921
                return r;
1922

1923
        if (mknod(sp, S_IFSOCK | 0600, /* dev= */ 0) < 0)
14,772✔
1924
                return -errno;
2,839✔
1925

1926
        _cleanup_(unlink_and_freep) char *sp_destroy = TAKE_PTR(sp);
11,933✔
1927

1928
        /* Old kernels return EPERM. But let's also check for more appropriate error codes, to be friendly to
1929
         * seccomp policies */
1930
        r = xsetxattr(AT_FDCWD, sp_destroy, /* at_flags= */ 0, "user.testxxx", "1");
11,933✔
1931
        if (ERRNO_IS_NEG_NOT_SUPPORTED(r) || r == -EPERM)
11,933✔
1932
                return (cached = false);
11,933✔
UNCOV
1933
        if (r < 0)
×
UNCOV
1934
                return log_debug_errno(r, "Failed to set test xattr on socket inode '%s': %m", sp_destroy);
×
1935

UNCOV
1936
        return (cached = true);
×
1937
}
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