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

systemd / systemd / 15057632786

15 May 2025 09:01PM UTC coverage: 72.267% (+0.02%) from 72.244%
15057632786

push

github

bluca
man: document how to hook stuff into system wakeup

Fixes: #6364

298523 of 413084 relevant lines covered (72.27%)

738132.88 hits per line

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

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

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

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

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

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

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

61
DEFINE_STRING_TABLE_LOOKUP(socket_address_type, int);
×
62

63
int socket_address_verify(const SocketAddress *a, bool strict) {
8,052✔
64
        assert(a);
8,052✔
65

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

69
        switch (socket_address_family(a)) {
8,052✔
70

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

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

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

81
                return 0;
82

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

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

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

93
                return 0;
94

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

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

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

124
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET))
7,577✔
125
                        return -EINVAL;
×
126

127
                return 0;
128

129
        case AF_NETLINK:
349✔
130

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

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

137
                return 0;
138

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

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

146
                return 0;
147

148
        default:
149
                return -EAFNOSUPPORT;
150
        }
151
}
152

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

156
        assert(a);
1,679✔
157
        assert(ret);
1,679✔
158

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

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

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

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

177
                return 0;
115✔
178
        }
179

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

183
bool socket_address_can_accept(const SocketAddress *a) {
4,764✔
184
        assert(a);
4,764✔
185

186
        return
4,764✔
187
                IN_SET(a->type, SOCK_STREAM, SOCK_SEQPACKET);
4,764✔
188
}
189

190
bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) {
1,993✔
191
        assert(a);
1,993✔
192
        assert(b);
1,993✔
193

194
        /* Invalid addresses are unequal to all */
195
        if (socket_address_verify(a, false) < 0 ||
3,986✔
196
            socket_address_verify(b, false) < 0)
1,993✔
197
                return false;
198

199
        if (a->type != b->type)
1,992✔
200
                return false;
201

202
        if (socket_address_family(a) != socket_address_family(b))
1,991✔
203
                return false;
204

205
        switch (socket_address_family(a)) {
1,989✔
206

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

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

214
                break;
215

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

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

223
                break;
224

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

230
                if ((a->sockaddr.un.sun_path[0] == 0) != (b->sockaddr.un.sun_path[0] == 0))
1,875✔
231
                        return false;
232

233
                if (a->sockaddr.un.sun_path[0]) {
1,610✔
234
                        if (!path_equal_or_inode_same(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, 0))
1,608✔
235
                                return false;
433✔
236
                } else {
237
                        if (a->size != b->size)
2✔
238
                                return false;
239

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

244
                break;
245

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

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

253
                break;
254

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

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

262
                break;
263

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

269
        return true;
270
}
271

272
const char* socket_address_get_path(const SocketAddress *a) {
10,628✔
273
        assert(a);
10,628✔
274

275
        if (socket_address_family(a) != AF_UNIX)
10,628✔
276
                return NULL;
277

278
        if (a->sockaddr.un.sun_path[0] == 0)
10,142✔
279
                return NULL;
280

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

288
bool socket_ipv6_is_supported(void) {
141,316✔
289
        static int cached = -1;
141,316✔
290

291
        if (cached < 0) {
141,316✔
292

293
                if (access("/proc/net/if_inet6", F_OK) < 0) {
1,133✔
294

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

300
                        cached = false;
×
301
                } else
302
                        cached = true;
1,133✔
303
        }
304

305
        return cached;
141,316✔
306
}
307

308
bool socket_ipv6_is_enabled(void) {
102,116✔
309
        _cleanup_free_ char *v = NULL;
102,116✔
310
        int r;
102,116✔
311

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

315
        if (!socket_ipv6_is_supported())
102,116✔
316
                return false;
317

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

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

330
        return !r;
102,116✔
331
}
332

333
bool socket_address_matches_fd(const SocketAddress *a, int fd) {
938✔
334
        SocketAddress b;
938✔
335
        socklen_t solen;
938✔
336

337
        assert(a);
938✔
338
        assert(fd >= 0);
938✔
339

340
        b.size = sizeof(b.sockaddr);
938✔
341
        if (getsockname(fd, &b.sockaddr.sa, &b.size) < 0)
938✔
342
                return false;
938✔
343

344
        if (b.sockaddr.sa.sa_family != a->sockaddr.sa.sa_family)
938✔
345
                return false;
346

347
        solen = sizeof(b.type);
823✔
348
        if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &b.type, &solen) < 0)
823✔
349
                return false;
350

351
        if (b.type != a->type)
823✔
352
                return false;
353

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

359
                if (b.protocol != a->protocol)
×
360
                        return false;
361
        }
362

363
        return socket_address_equal(a, &b);
698✔
364
}
365

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

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

371
        assert(sa);
×
372

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

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

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

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

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

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

395
        if (!sa)
406✔
396
                return NULL;
397

398
        switch (sa->sa.sa_family) {
406✔
399

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

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

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

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

417
        assert(u);
706✔
418
        assert(a);
706✔
419

420
        switch (family) {
706✔
421

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

429
                return 0;
703✔
430

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

438
                return 0;
3✔
439

440
        default:
441
                return -EAFNOSUPPORT;
442

443
        }
444
}
445

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

453
        union sockaddr_union *sa = (union sockaddr_union*) _sa;
9,303✔
454
        char *p;
9,303✔
455
        int r;
9,303✔
456

457
        assert(sa);
9,303✔
458
        assert(salen >= sizeof(sa->sa.sa_family));
9,303✔
459
        assert(ret);
9,303✔
460

461
        switch (sa->sa.sa_family) {
9,303✔
462

463
        case AF_INET: {
84✔
464
                uint32_t a;
84✔
465

466
                a = be32toh(sa->in.sin_addr.s_addr);
84✔
467

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

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

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

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

522
                break;
523
        }
524

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

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

544
                                _cleanup_free_ char *e = NULL;
8✔
545

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

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

556
                                p = cescape_length(path, path_len);
9,168✔
557
                        }
558
                }
559
                if (!p)
9,180✔
560
                        return -ENOMEM;
561

562
                break;
563

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

576
        default:
577
                return -EOPNOTSUPP;
578
        }
579

580
        *ret = p;
9,303✔
581
        return 0;
9,303✔
582
}
583

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

589
        assert(fd >= 0);
3✔
590
        assert(ret);
3✔
591

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

595
        if (sa.sa.sa_family == AF_UNIX) {
3✔
596
                struct ucred ucred = UCRED_INVALID;
2✔
597

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

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

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

608
                return 0;
2✔
609
        }
610

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

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

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

621
        assert(fd >= 0);
1✔
622
        assert(ret);
1✔
623

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

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

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

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

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

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

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

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

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

679
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
540✔
680

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

687
DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only, SocketAddressBindIPv6Only);
160✔
688

689
SocketAddressBindIPv6Only socket_address_bind_ipv6_only_or_bool_from_string(const char *n) {
×
690
        int r;
×
691

692
        r = parse_boolean(n);
×
693
        if (r > 0)
×
694
                return SOCKET_ADDRESS_IPV6_ONLY;
695
        if (r == 0)
×
696
                return SOCKET_ADDRESS_BOTH;
697

698
        return socket_address_bind_ipv6_only_from_string(n);
×
699
}
700

701
bool sockaddr_equal(const union sockaddr_union *a, const union sockaddr_union *b) {
1,286✔
702
        assert(a);
1,286✔
703
        assert(b);
1,286✔
704

705
        if (a->sa.sa_family != b->sa.sa_family)
1,286✔
706
                return false;
707

708
        if (a->sa.sa_family == AF_INET)
1,285✔
709
                return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
4✔
710

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

714
        if (a->sa.sa_family == AF_VSOCK)
1,280✔
715
                return a->vm.svm_cid == b->vm.svm_cid;
1✔
716

717
        return false;
718
}
719

720
int fd_set_sndbuf(int fd, size_t n, bool increase) {
409,317✔
721
        int r, value;
409,317✔
722
        socklen_t l = sizeof(value);
409,317✔
723

724
        if (n > INT_MAX)
409,317✔
725
                return -ERANGE;
409,317✔
726

727
        r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
409,317✔
728
        if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
409,317✔
729
                return 0;
730

731
        /* First, try to set the buffer size with SO_SNDBUF. */
732
        r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUF, n);
409,317✔
733
        if (r < 0)
409,317✔
734
                return r;
735

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

743
        /* If we have the privileges we will ignore the kernel limit. */
744
        r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUFFORCE, n);
409,317✔
745
        if (r < 0)
409,317✔
746
                return r;
33,938✔
747

748
        return 1;
749
}
750

751
int fd_set_rcvbuf(int fd, size_t n, bool increase) {
32,515✔
752
        int r, value;
32,515✔
753
        socklen_t l = sizeof(value);
32,515✔
754

755
        if (n > INT_MAX)
32,515✔
756
                return -ERANGE;
32,515✔
757

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

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

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

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

779
        return 1;
780
}
781

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

789
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
×
790

791
bool ifname_valid_char(char a) {
445,827✔
792
        if ((unsigned char) a >= 127U)
445,827✔
793
                return false;
794

795
        if ((unsigned char) a <= 32U)
445,827✔
796
                return false;
797

798
        if (IN_SET(a,
445,823✔
799
                   ':',  /* colons are used by the legacy "alias" interface logic */
800
                   '/',  /* slashes cannot work, since we need to use network interfaces in sysfs paths, and in paths slashes are separators */
801
                   '%')) /* %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 */
802
                return false;
10✔
803

804
        return true;
805
}
806

807
bool ifname_valid_full(const char *p, IfnameValidFlags flags) {
128,310✔
808
        bool numeric = true;
128,310✔
809

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

814
        assert(!(flags & ~_IFNAME_VALID_ALL));
128,310✔
815

816
        if (isempty(p))
128,310✔
817
                return false;
818

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

823
        if (flags & IFNAME_VALID_ALTERNATIVE) {
123,748✔
824
                if (strlen(p) >= ALTIFNAMSIZ)
11,707✔
825
                        return false;
826
        } else {
827
                if (strlen(p) >= IFNAMSIZ)
112,041✔
828
                        return false;
829
        }
830

831
        if (dot_or_dot_dot(p))
123,741✔
832
                return false;
833

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

839
        for (const char *t = p; *t; t++) {
562,876✔
840
                if (!ifname_valid_char(*t))
439,151✔
841
                        return false;
842

843
                numeric = numeric && ascii_isdigit(*t);
562,866✔
844
        }
845

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

851
        return true;
852
}
853

854
bool address_label_valid(const char *p) {
44✔
855

856
        if (isempty(p))
44✔
857
                return false;
858

859
        if (strlen(p) >= IFNAMSIZ)
44✔
860
                return false;
861

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

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

871
        return true;
872
}
873

874
int getpeercred(int fd, struct ucred *ucred) {
81,084✔
875
        socklen_t n = sizeof(struct ucred);
81,084✔
876
        struct ucred u;
81,084✔
877

878
        assert(fd >= 0);
81,084✔
879
        assert(ucred);
81,084✔
880

881
        if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n) < 0)
81,084✔
882
                return -errno;
×
883

884
        if (n != sizeof(struct ucred))
81,084✔
885
                return -EIO;
886

887
        /* Check if the data is actually useful and not suppressed due to namespacing issues */
888
        if (!pid_is_valid(u.pid))
81,084✔
889
                return -ENODATA;
890

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

894
        *ucred = u;
81,084✔
895
        return 0;
81,084✔
896
}
897

898
int getpeersec(int fd, char **ret) {
20,046✔
899
        _cleanup_free_ char *s = NULL;
40,092✔
900
        socklen_t n = 64;
20,046✔
901

902
        assert(fd >= 0);
20,046✔
903
        assert(ret);
20,046✔
904

905
        for (;;) {
20,046✔
906
                s = new0(char, n+1);
20,046✔
907
                if (!s)
20,046✔
908
                        return -ENOMEM;
909

910
                if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n) >= 0) {
20,046✔
911
                        s[n] = 0;
7,130✔
912
                        break;
7,130✔
913
                }
914

915
                if (errno != ERANGE)
12,916✔
916
                        return -errno;
12,916✔
917

918
                s = mfree(s);
×
919
        }
920

921
        if (isempty(s))
7,130✔
922
                return -EOPNOTSUPP;
923

924
        *ret = TAKE_PTR(s);
7,130✔
925

926
        return 0;
7,130✔
927
}
928

929
int getpeergroups(int fd, gid_t **ret) {
20,047✔
930
        socklen_t n = sizeof(gid_t) * 64U;
20,047✔
931
        _cleanup_free_ gid_t *d = NULL;
20,047✔
932

933
        assert(fd >= 0);
20,047✔
934
        assert(ret);
20,047✔
935

936
        long ngroups_max = sysconf(_SC_NGROUPS_MAX);
20,047✔
937
        if (ngroups_max > 0)
20,047✔
938
                n = MAX(n, sizeof(gid_t) * (socklen_t) ngroups_max);
20,047✔
939

940
        for (;;) {
20,047✔
941
                d = malloc(n);
20,047✔
942
                if (!d)
20,047✔
943
                        return -ENOMEM;
944

945
                if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
20,047✔
946
                        break;
947

948
                if (errno != ERANGE)
×
949
                        return -errno;
×
950

951
                d = mfree(d);
×
952
        }
953

954
        assert_se(n % sizeof(gid_t) == 0);
20,047✔
955
        n /= sizeof(gid_t);
20,047✔
956

957
        if (n > INT_MAX)
20,047✔
958
                return -E2BIG;
959

960
        *ret = TAKE_PTR(d);
20,047✔
961

962
        return (int) n;
20,047✔
963
}
964

965
int getpeerpidfd(int fd) {
20,347✔
966
        socklen_t n = sizeof(int);
20,347✔
967
        int pidfd = -EBADF;
20,347✔
968

969
        assert(fd >= 0);
20,347✔
970

971
        if (getsockopt(fd, SOL_SOCKET, SO_PEERPIDFD, &pidfd, &n) < 0)
20,347✔
972
                return -errno;
2✔
973

974
        if (n != sizeof(int))
20,345✔
975
                return -EIO;
976

977
        return pidfd;
20,345✔
978
}
979

980
int getpeerpidref(int fd, PidRef *ret) {
4✔
981
        int r;
4✔
982

983
        assert(fd >= 0);
4✔
984
        assert(ret);
4✔
985

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

991
                struct ucred ucred;
×
992
                r = getpeercred(fd, &ucred);
×
993
                if (r < 0)
×
994
                        return r;
995

996
                return pidref_set_pid(ret, ucred.pid);
×
997
        }
998

999
        return pidref_set_pidfd_consume(ret, pidfd);
4✔
1000
}
1001

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

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

1018
        assert(transport_fd >= 0);
1✔
1019
        assert(fds_array || n_fds_array == 0);
1✔
1020

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

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

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

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

1046
        return k;
1047
}
1048

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

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

1065
        assert(transport_fd >= 0);
748✔
1066

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

1074
        if (fd >= 0) {
747✔
1075
                struct cmsghdr *cmsg;
745✔
1076

1077
                mh.msg_control = &control;
745✔
1078
                mh.msg_controllen = sizeof(control);
745✔
1079

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

1090
        return k;
1091
}
1092

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

1099
        assert(fd >= 0);
6✔
1100

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

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

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

1122
        assert(transport_fd >= 0);
1✔
1123
        assert(ret_fds_array);
1✔
1124
        assert(ret_n_fds_array);
1✔
1125

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

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

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

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

1145
        if (n_fds_array == 0) {
1✔
1146
                cmsg_close_all(&mh);
×
1147

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

1153
        *ret_fds_array = TAKE_PTR(fds_array);
1✔
1154
        *ret_n_fds_array = n_fds_array;
1✔
1155

1156
        return k;
1✔
1157
}
1158

1159
int receive_many_fds(int transport_fd, int **ret_fds_array, size_t *ret_n_fds_array, int flags) {
×
1160
        ssize_t k;
×
1161

1162
        k = receive_many_fds_iov(transport_fd, NULL, 0, ret_fds_array, ret_n_fds_array, flags);
×
1163
        if (k == 0)
×
1164
                return 0;
1165

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

1172
ssize_t receive_one_fd_iov(
5,107✔
1173
                int transport_fd,
1174
                struct iovec *iov, size_t iovlen,
1175
                int flags,
1176
                int *ret_fd) {
1177

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

1188
        assert(transport_fd >= 0);
5,107✔
1189
        assert(ret_fd);
5,107✔
1190

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

1199
        k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
5,107✔
1200
        if (k < 0)
5,107✔
1201
                return k;
5,107✔
1202

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

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

1212
        if (found)
3,383✔
1213
                *ret_fd = *CMSG_TYPED_DATA(found, int);
3,382✔
1214
        else
1215
                *ret_fd = -EBADF;
1✔
1216

1217
        return k;
1218
}
1219

1220
int receive_one_fd(int transport_fd, int flags) {
592✔
1221
        int fd;
592✔
1222
        ssize_t k;
592✔
1223

1224
        k = receive_one_fd_iov(transport_fd, NULL, 0, flags, &fd);
592✔
1225
        if (k == 0)
592✔
1226
                return fd;
522✔
1227

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

1234
ssize_t next_datagram_size_fd(int fd) {
209,805✔
1235
        ssize_t l;
209,805✔
1236
        int k;
209,805✔
1237

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

1244
        l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
209,805✔
1245
        if (l < 0) {
209,805✔
1246
                if (IN_SET(errno, EOPNOTSUPP, EFAULT))
587✔
1247
                        goto fallback;
×
1248

1249
                return -errno;
587✔
1250
        }
1251
        if (l == 0)
209,218✔
1252
                goto fallback;
65✔
1253

1254
        return l;
1255

1256
fallback:
65✔
1257
        k = 0;
65✔
1258

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

1262
        if (ioctl(fd, FIONREAD, &k) < 0)
65✔
1263
                return -errno;
×
1264

1265
        return (ssize_t) k;
65✔
1266
}
1267

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

1272
int flush_accept(int fd) {
12✔
1273

1274
        int r, b;
12✔
1275
        socklen_t l = sizeof(b);
12✔
1276

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

1280
        if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
12✔
1281
                return -errno;
×
1282

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

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

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

1299
                        return r;
1300
                }
1301
                if (r == 0)
6✔
1302
                        return 0;
1303

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

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

1313
                        if (ERRNO_IS_ACCEPT_AGAIN(errno))
×
1314
                                continue;
×
1315

1316
                        return -errno;
×
1317
                }
1318

1319
                safe_close(cfd);
2✔
1320
        }
1321
}
1322

1323
ssize_t flush_mqueue(int fd) {
×
1324
        _cleanup_free_ char *buf = NULL;
×
1325
        struct mq_attr attr;
×
1326
        ssize_t count = 0;
×
1327
        int r;
×
1328

1329
        assert(fd >= 0);
×
1330

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

1333
        for (;;) {
×
1334
                ssize_t l;
×
1335

1336
                r = fd_wait_for_event(fd, POLLIN, /* timeout= */ 0);
×
1337
                if (r < 0) {
×
1338
                        if (r == -EINTR)
×
1339
                                continue;
×
1340

1341
                        return r;
×
1342
                }
1343
                if (r == 0)
×
1344
                        return count;
1345

1346
                if (!buf) {
×
1347
                        /* Buffer must be at least as large as mq_msgsize. */
1348
                        if (mq_getattr(fd, &attr) < 0)
×
1349
                                return -errno;
×
1350

1351
                        buf = malloc(attr.mq_msgsize);
×
1352
                        if (!buf)
×
1353
                                return -ENOMEM;
1354
                }
1355

1356
                l = mq_receive(fd, buf, attr.mq_msgsize, /* msg_prio = */ NULL);
×
1357
                if (l < 0) {
×
1358
                        if (errno == EINTR)
×
1359
                                continue;
×
1360

1361
                        if (errno == EAGAIN)
×
1362
                                return count;
1363

1364
                        return -errno;
×
1365
                }
1366

1367
                count += l;
×
1368
        }
1369
}
1370

1371
struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
653,009✔
1372
        struct cmsghdr *cmsg;
653,009✔
1373

1374
        assert(mh);
653,009✔
1375

1376
        CMSG_FOREACH(cmsg, mh)
1,306,540✔
1377
                if (cmsg->cmsg_level == level &&
619,828✔
1378
                    cmsg->cmsg_type == type &&
619,567✔
1379
                    (length == (socklen_t) -1 || length == cmsg->cmsg_len))
619,109✔
1380
                        return cmsg;
1381

1382
        return NULL;
1383
}
1384

1385
void* cmsg_find_and_copy_data(struct msghdr *mh, int level, int type, void *buf, size_t buf_len) {
294✔
1386
        struct cmsghdr *cmsg;
294✔
1387

1388
        assert(mh);
294✔
1389
        assert(buf);
294✔
1390
        assert(buf_len > 0);
294✔
1391

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

1396
        cmsg = cmsg_find(mh, level, type, CMSG_LEN(buf_len));
294✔
1397
        if (!cmsg)
294✔
1398
                return NULL;
1399

1400
        return memcpy_safe(buf, CMSG_DATA(cmsg), buf_len);
289✔
1401
}
1402

1403
size_t sockaddr_ll_len(const struct sockaddr_ll *sa) {
306✔
1404
        /* Certain hardware address types (e.g Infiniband) do not fit into sll_addr
1405
         * (8 bytes) and run over the structure. This function returns the correct size that
1406
         * must be passed to kernel. */
1407

1408
        assert(sa->sll_family == AF_PACKET);
306✔
1409

1410
        size_t mac_len = sizeof(sa->sll_addr);
306✔
1411

1412
        if (be16toh(sa->sll_hatype) == ARPHRD_ETHER)
306✔
1413
                mac_len = MAX(mac_len, (size_t) ETH_ALEN);
306✔
1414
        if (be16toh(sa->sll_hatype) == ARPHRD_INFINIBAND)
306✔
1415
                mac_len = MAX(mac_len, (size_t) INFINIBAND_ALEN);
×
1416

1417
        return offsetof(struct sockaddr_ll, sll_addr) + mac_len;
306✔
1418
}
1419

1420
size_t sockaddr_un_len(const struct sockaddr_un *sa) {
2,479✔
1421
        /* Covers only file system and abstract AF_UNIX socket addresses, but not unnamed socket addresses. */
1422

1423
        assert(sa->sun_family == AF_UNIX);
2,479✔
1424

1425
        return offsetof(struct sockaddr_un, sun_path) +
7,437✔
1426
                (sa->sun_path[0] == 0 ?
2,479✔
1427
                        1 + strnlen(sa->sun_path+1, sizeof(sa->sun_path)-1) :
592✔
1428
                        strnlen(sa->sun_path, sizeof(sa->sun_path))+1);
1,887✔
1429
}
1430

1431
size_t sockaddr_len(const union sockaddr_union *sa) {
211✔
1432
        switch (sa->sa.sa_family) {
211✔
1433
        case AF_INET:
1434
                return sizeof(struct sockaddr_in);
1435
        case AF_INET6:
62✔
1436
                return sizeof(struct sockaddr_in6);
62✔
1437
        case AF_UNIX:
3✔
1438
                return sockaddr_un_len(&sa->un);
3✔
1439
        case AF_PACKET:
×
1440
                return sockaddr_ll_len(&sa->ll);
×
1441
        case AF_NETLINK:
×
1442
                return sizeof(struct sockaddr_nl);
×
1443
        case AF_VSOCK:
1444
                return sizeof(struct sockaddr_vm);
1445
        default:
×
1446
                assert_not_reached();
×
1447
        }
1448
}
1449

1450
int socket_ioctl_fd(void) {
4,308✔
1451
        int fd;
4,308✔
1452

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

1458
        fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
4,308✔
1459
        if (fd < 0)
4,308✔
1460
                fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
×
1461
        if (fd < 0)
×
1462
                return -errno;
×
1463

1464
        return fd;
1465
}
1466

1467
int sockaddr_un_unlink(const struct sockaddr_un *sa) {
1,773✔
1468
        const char *p, * nul;
1,773✔
1469

1470
        assert(sa);
1,773✔
1471

1472
        if (sa->sun_family != AF_UNIX)
1,773✔
1473
                return -EPROTOTYPE;
1474

1475
        if (sa->sun_path[0] == 0) /* Nothing to do for abstract sockets */
1,773✔
1476
                return 0;
1477

1478
        /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1479
        nul = memchr(sa->sun_path, 0, sizeof(sa->sun_path));
1,773✔
1480
        if (nul)
1,773✔
1481
                p = sa->sun_path;
1482
        else
1483
                p = memdupa_suffix0(sa->sun_path, sizeof(sa->sun_path));
×
1484

1485
        if (unlink(p) < 0)
1,773✔
1486
                return -errno;
1,531✔
1487

1488
        return 1;
1489
}
1490

1491
int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path) {
413,056✔
1492
        size_t l;
413,056✔
1493

1494
        assert(ret);
413,056✔
1495
        assert(path);
413,056✔
1496

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

1502
        l = strlen(path);
413,056✔
1503
        if (l < 2)
413,056✔
1504
                return -EINVAL;
1505
        if (!IN_SET(path[0], '/', '@'))
413,055✔
1506
                return -EINVAL;
1507

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

1518
        *ret = (struct sockaddr_un) {
413,053✔
1519
                .sun_family = AF_UNIX,
1520
        };
1521

1522
        if (path[0] == '@') {
413,053✔
1523
                /* Abstract namespace socket */
1524
                memcpy(ret->sun_path + 1, path + 1, l); /* copy *with* trailing NUL byte */
215,209✔
1525
                return (int) (offsetof(struct sockaddr_un, sun_path) + l); /* 🔥 *don't* 🔥 include trailing NUL in size */
215,209✔
1526

1527
        } else {
1528
                assert(path[0] == '/');
197,844✔
1529

1530
                /* File system socket */
1531
                memcpy(ret->sun_path, path, l + 1); /* copy *with* trailing NUL byte */
197,844✔
1532
                return (int) (offsetof(struct sockaddr_un, sun_path) + l + 1); /* include trailing NUL in size */
197,844✔
1533
        }
1534
}
1535

1536
int socket_bind_to_ifname(int fd, const char *ifname) {
1✔
1537
        assert(fd >= 0);
1✔
1538

1539
        /* Call with NULL to drop binding */
1540

1541
        return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen_ptr(ifname)));
2✔
1542
}
1543

1544
int socket_bind_to_ifindex(int fd, int ifindex) {
711✔
1545
        assert(fd >= 0);
711✔
1546

1547
        if (ifindex <= 0)
711✔
1548
                /* Drop binding */
1549
                return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, NULL, 0));
56✔
1550

1551
        return setsockopt_int(fd, SOL_SOCKET, SO_BINDTOIFINDEX, ifindex);
655✔
1552
}
1553

1554
int socket_autobind(int fd, char **ret_name) {
244✔
1555
        _cleanup_free_ char *name = NULL;
244✔
1556
        uint64_t random;
244✔
1557
        int r;
244✔
1558

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

1562
        assert(fd >= 0);
244✔
1563

1564
        random = random_u64();
244✔
1565

1566
        if (asprintf(&name, "@%" PRIu64, random) < 0)
244✔
1567
                return -ENOMEM;
1568

1569
        union sockaddr_union sa;
244✔
1570
        assert_cc(DECIMAL_STR_MAX(uint64_t) < sizeof(sa.un.sun_path));
244✔
1571

1572
        r = sockaddr_un_set_path(&sa.un, name);
244✔
1573
        if (r < 0)
244✔
1574
                return r;
1575

1576
        if (bind(fd, &sa.sa, r) < 0)
244✔
1577
                return -errno;
×
1578

1579
        if (ret_name)
244✔
1580
                *ret_name = TAKE_PTR(name);
242✔
1581
        return 0;
1582
}
1583

1584
ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags) {
3,431,294✔
1585
        ssize_t n;
3,431,294✔
1586

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

1592
        assert(sockfd >= 0);
3,431,294✔
1593
        assert(msg);
3,431,294✔
1594

1595
        n = recvmsg(sockfd, msg, flags);
3,431,294✔
1596
        if (n < 0)
3,431,294✔
1597
                return -errno;
298,472✔
1598

1599
        if (FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ||
3,132,822✔
1600
            (!FLAGS_SET(flags, MSG_PEEK) && FLAGS_SET(msg->msg_flags, MSG_TRUNC))) {
3,132,822✔
1601
                cmsg_close_all(msg);
×
1602
                return FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ? -ECHRNG : -EXFULL;
×
1603
        }
1604

1605
        return n;
1606
}
1607

1608
int socket_get_family(int fd) {
30,899✔
1609
        int af;
30,899✔
1610
        socklen_t sl = sizeof(af);
30,899✔
1611

1612
        if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &af, &sl) < 0)
30,899✔
1613
                return -errno;
×
1614

1615
        if (sl != sizeof(af))
30,899✔
1616
                return -EINVAL;
1617

1618
        return af;
30,899✔
1619
}
1620

1621
int socket_set_recvpktinfo(int fd, int af, bool b) {
12,213✔
1622

1623
        if (af == AF_UNSPEC) {
12,213✔
1624
                af = socket_get_family(fd);
×
1625
                if (af < 0)
×
1626
                        return af;
1627
        }
1628

1629
        switch (af) {
12,213✔
1630

1631
        case AF_INET:
6,438✔
1632
                return setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, b);
6,438✔
1633

1634
        case AF_INET6:
5,742✔
1635
                return setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, b);
5,742✔
1636

1637
        case AF_NETLINK:
33✔
1638
                return setsockopt_int(fd, SOL_NETLINK, NETLINK_PKTINFO, b);
33✔
1639

1640
        case AF_PACKET:
×
1641
                return setsockopt_int(fd, SOL_PACKET, PACKET_AUXDATA, b);
×
1642

1643
        default:
1644
                return -EAFNOSUPPORT;
1645
        }
1646
}
1647

1648
int socket_set_unicast_if(int fd, int af, int ifi) {
125✔
1649
        be32_t ifindex_be = htobe32(ifi);
125✔
1650

1651
        if (af == AF_UNSPEC) {
125✔
1652
                af = socket_get_family(fd);
×
1653
                if (af < 0)
×
1654
                        return af;
125✔
1655
        }
1656

1657
        switch (af) {
125✔
1658

1659
        case AF_INET:
93✔
1660
                return RET_NERRNO(setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
93✔
1661

1662
        case AF_INET6:
32✔
1663
                return RET_NERRNO(setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
32✔
1664

1665
        default:
1666
                return -EAFNOSUPPORT;
1667
        }
1668
}
1669

1670
int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val) {
24,229✔
1671
        if (af == AF_UNSPEC) {
24,229✔
1672
                af = socket_get_family(fd);
×
1673
                if (af < 0)
×
1674
                        return af;
1675
        }
1676

1677
        switch (af) {
24,229✔
1678

1679
        case AF_INET:
12,737✔
1680
                return setsockopt_int(fd, IPPROTO_IP, opt_ipv4, val);
12,737✔
1681

1682
        case AF_INET6:
11,492✔
1683
                return setsockopt_int(fd, IPPROTO_IPV6, opt_ipv6, val);
11,492✔
1684

1685
        default:
1686
                return -EAFNOSUPPORT;
1687
        }
1688
}
1689

1690
int socket_get_mtu(int fd, int af, size_t *ret) {
708✔
1691
        int mtu, r;
708✔
1692

1693
        if (af == AF_UNSPEC) {
708✔
1694
                af = socket_get_family(fd);
×
1695
                if (af < 0)
×
1696
                        return af;
708✔
1697
        }
1698

1699
        switch (af) {
708✔
1700

1701
        case AF_INET:
322✔
1702
                r = getsockopt_int(fd, IPPROTO_IP, IP_MTU, &mtu);
322✔
1703
                break;
1704

1705
        case AF_INET6:
386✔
1706
                r = getsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, &mtu);
386✔
1707
                break;
1708

1709
        default:
1710
                return -EAFNOSUPPORT;
1711
        }
1712

1713
        if (r < 0)
708✔
1714
                return r;
1715
        if (mtu <= 0)
652✔
1716
                return -EINVAL;
1717

1718
        *ret = (size_t) mtu;
652✔
1719
        return 0;
652✔
1720
}
1721

1722
static int connect_unix_path_simple(int fd, const char *path) {
167,656✔
1723
        union sockaddr_union sa = {
167,656✔
1724
                .un.sun_family = AF_UNIX,
1725
        };
1726
        size_t l;
167,656✔
1727

1728
        assert(fd >= 0);
167,656✔
1729
        assert(path);
167,656✔
1730

1731
        l = strlen(path);
167,656✔
1732
        assert(l > 0);
167,656✔
1733
        assert(l < sizeof(sa.un.sun_path));
167,656✔
1734

1735
        memcpy(sa.un.sun_path, path, l + 1);
167,656✔
1736
        return RET_NERRNO(connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + l + 1));
167,656✔
1737
}
1738

1739
static int connect_unix_inode(int fd, int inode_fd) {
14✔
1740
        assert(fd >= 0);
14✔
1741
        assert(inode_fd >= 0);
14✔
1742

1743
        return connect_unix_path_simple(fd, FORMAT_PROC_FD_PATH(inode_fd));
14✔
1744
}
1745

1746
int connect_unix_path(int fd, int dir_fd, const char *path) {
167,656✔
1747
        _cleanup_close_ int inode_fd = -EBADF;
167,656✔
1748

1749
        assert(fd >= 0);
167,656✔
1750
        assert(dir_fd == AT_FDCWD || dir_fd >= 0);
167,656✔
1751

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

1755
        if (!path)
167,656✔
1756
                return connect_unix_inode(fd, dir_fd); /* If no path is specified, then dir_fd refers to the socket inode to connect to. */
1✔
1757

1758
        /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
1759
         * namespace path, since first char is NUL */
1760
        if (isempty(path))
335,311✔
1761
                return -EINVAL;
1762

1763
        /* Shortcut for the simple case */
1764
        if (dir_fd == AT_FDCWD && strlen(path) < sizeof_field(struct sockaddr_un, sun_path))
167,655✔
1765
                return connect_unix_path_simple(fd, path);
167,642✔
1766

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

1771
        inode_fd = openat(dir_fd, path, O_PATH|O_CLOEXEC);
13✔
1772
        if (inode_fd < 0)
13✔
1773
                return -errno;
×
1774

1775
        return connect_unix_inode(fd, inode_fd);
13✔
1776
}
1777

1778
int socket_address_parse_unix(SocketAddress *ret_address, const char *s) {
223,427✔
1779
        struct sockaddr_un un;
223,427✔
1780
        int r;
223,427✔
1781

1782
        assert(ret_address);
223,427✔
1783
        assert(s);
223,427✔
1784

1785
        if (!IN_SET(*s, '/', '@'))
223,427✔
1786
                return -EPROTO;
223,427✔
1787

1788
        r = sockaddr_un_set_path(&un, s);
222,988✔
1789
        if (r < 0)
222,988✔
1790
                return r;
1791

1792
        *ret_address = (SocketAddress) {
222,986✔
1793
                .sockaddr.un = un,
1794
                .size = r,
1795
        };
1796

1797
        return 0;
222,986✔
1798
}
1799

1800
int socket_address_equal_unix(const char *a, const char *b) {
1,279✔
1801
        SocketAddress socket_a, socket_b;
1,279✔
1802
        int r;
1,279✔
1803

1804
        assert(a);
1,279✔
1805
        assert(b);
1,279✔
1806

1807
        r = socket_address_parse_unix(&socket_a, a);
1,279✔
1808
        if (r < 0)
1,279✔
1809
                return r;
1,279✔
1810

1811
        r = socket_address_parse_unix(&socket_b, b);
1,279✔
1812
        if (r < 0)
1,279✔
1813
                return r;
1814

1815
        return sockaddr_equal(&socket_a.sockaddr, &socket_b.sockaddr);
1,279✔
1816
}
1817

1818
int vsock_parse_port(const char *s, unsigned *ret) {
371✔
1819
        int r;
371✔
1820

1821
        assert(ret);
371✔
1822

1823
        if (!s)
371✔
1824
                return -EINVAL;
371✔
1825

1826
        unsigned u;
371✔
1827
        r = safe_atou(s, &u);
371✔
1828
        if (r < 0)
371✔
1829
                return r;
1830

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

1834
        if (u == VMADDR_PORT_ANY)
368✔
1835
                return -EINVAL;
1836

1837
        *ret = u;
368✔
1838
        return 0;
368✔
1839
}
1840

1841
int vsock_parse_cid(const char *s, unsigned *ret) {
331✔
1842
        assert(ret);
331✔
1843

1844
        if (!s)
331✔
1845
                return -EINVAL;
1846

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

1850
        if (streq(s, "hypervisor"))
331✔
1851
                *ret = VMADDR_CID_HYPERVISOR;
×
1852
        else if (streq(s, "local"))
331✔
1853
                *ret = VMADDR_CID_LOCAL;
×
1854
        else if (streq(s, "host"))
331✔
1855
                *ret = VMADDR_CID_HOST;
×
1856
        else
1857
                return safe_atou(s, ret);
331✔
1858

1859
        return 0;
1860
}
1861

1862
int socket_address_parse_vsock(SocketAddress *ret_address, const char *s) {
439✔
1863
        /* AF_VSOCK socket in vsock:cid:port notation */
1864
        _cleanup_free_ char *n = NULL;
439✔
1865
        char *e, *cid_start;
439✔
1866
        unsigned port, cid;
439✔
1867
        int type, r;
439✔
1868

1869
        assert(ret_address);
439✔
1870
        assert(s);
439✔
1871

1872
        if ((cid_start = startswith(s, "vsock:")))
439✔
1873
                type = 0;
1874
        else if ((cid_start = startswith(s, "vsock-dgram:")))
387✔
1875
                type = SOCK_DGRAM;
1876
        else if ((cid_start = startswith(s, "vsock-seqpacket:")))
387✔
1877
                type = SOCK_SEQPACKET;
1878
        else if ((cid_start = startswith(s, "vsock-stream:")))
387✔
1879
                type = SOCK_STREAM;
1880
        else
1881
                return -EPROTO;
1882

1883
        e = strchr(cid_start, ':');
373✔
1884
        if (!e)
373✔
1885
                return -EINVAL;
1886

1887
        r = vsock_parse_port(e+1, &port);
371✔
1888
        if (r < 0)
371✔
1889
                return r;
1890

1891
        n = strndup(cid_start, e - cid_start);
368✔
1892
        if (!n)
368✔
1893
                return -ENOMEM;
1894

1895
        if (isempty(n))
368✔
1896
                cid = VMADDR_CID_ANY;
37✔
1897
        else {
1898
                r = vsock_parse_cid(n, &cid);
331✔
1899
                if (r < 0)
331✔
1900
                        return r;
1901
        }
1902

1903
        *ret_address = (SocketAddress) {
365✔
1904
                .sockaddr.vm = {
1905
                        .svm_family = AF_VSOCK,
1906
                        .svm_cid = cid,
1907
                        .svm_port = port,
1908
                },
1909
                .type = type,
1910
                .size = sizeof(struct sockaddr_vm),
1911
        };
1912

1913
        return 0;
365✔
1914
}
1915

1916
int vsock_get_local_cid(unsigned *ret) {
16✔
1917
        _cleanup_close_ int vsock_fd = -EBADF;
16✔
1918

1919
        vsock_fd = open("/dev/vsock", O_RDONLY|O_CLOEXEC);
16✔
1920
        if (vsock_fd < 0)
16✔
1921
                return log_debug_errno(errno, "Failed to open /dev/vsock: %m");
13✔
1922

1923
        unsigned tmp;
3✔
1924
        if (ioctl(vsock_fd, IOCTL_VM_SOCKETS_GET_LOCAL_CID, ret ?: &tmp) < 0)
6✔
1925
                return log_debug_errno(errno, "Failed to query local AF_VSOCK CID: %m");
×
1926

1927
        return 0;
1928
}
1929

1930
int netlink_socket_get_multicast_groups(int fd, size_t *ret_len, uint32_t **ret_groups) {
12,144✔
1931
        _cleanup_free_ uint32_t *groups = NULL;
24,288✔
1932
        socklen_t len = 0, old_len;
12,144✔
1933

1934
        assert(fd >= 0);
12,144✔
1935

1936
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, NULL, &len) < 0)
12,144✔
1937
                return -errno;
×
1938

1939
        if (len == 0)
12,144✔
1940
                goto finalize;
11,727✔
1941

1942
        groups = new0(uint32_t, len);
417✔
1943
        if (!groups)
417✔
1944
                return -ENOMEM;
1945

1946
        old_len = len;
417✔
1947

1948
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, groups, &len) < 0)
417✔
1949
                return -errno;
×
1950

1951
        if (old_len != len)
417✔
1952
                return -EIO;
1953

1954
finalize:
417✔
1955
        if (ret_len)
12,144✔
1956
                *ret_len = len;
12,144✔
1957
        if (ret_groups)
12,144✔
1958
                *ret_groups = TAKE_PTR(groups);
12,144✔
1959

1960
        return 0;
1961
}
1962

1963
int socket_get_cookie(int fd, uint64_t *ret) {
131✔
1964
        assert(fd >= 0);
131✔
1965

1966
        uint64_t cookie = 0;
131✔
1967
        socklen_t cookie_len = sizeof(cookie);
131✔
1968
        if (getsockopt(fd, SOL_SOCKET, SO_COOKIE, &cookie, &cookie_len) < 0)
131✔
1969
                return -errno;
×
1970

1971
        assert(cookie_len == sizeof(cookie));
131✔
1972
        if (ret)
131✔
1973
                *ret = cookie;
131✔
1974

1975
        return 0;
1976
}
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