nm-netlink.c 44.1 KB
Newer Older
1
/* SPDX-License-Identifier: GPL-2.0-or-later */
2
/*
3
4
5
 * Copyright (C) 2018 Red Hat, Inc.
 */

6
#include "libnm-glib-aux/nm-default-glib-i18n-lib.h"
7
8
9

#include "nm-netlink.h"

10
11
12
13
14
15
#include <unistd.h>
#include <fcntl.h>

/*****************************************************************************/

#ifndef SOL_NETLINK
16
#define SOL_NETLINK 270
17
18
19
20
#endif

/*****************************************************************************/

21
22
23
24
25
26
27
28
29
30
#define nm_assert_sk(sk)                  \
    G_STMT_START                          \
    {                                     \
        const struct nl_sock *_sk = (sk); \
                                          \
        nm_assert(_sk);                   \
        nm_assert(_sk->s_fd >= 0);        \
    }                                     \
    G_STMT_END

31
#ifndef NETLINK_EXT_ACK
32
#define NETLINK_EXT_ACK 11
33
34
#endif

35
struct nl_msg {
36
37
38
39
    int                nm_protocol;
    struct sockaddr_nl nm_src;
    struct sockaddr_nl nm_dst;
    struct ucred       nm_creds;
40
    struct nlmsghdr   *nm_nlh;
41
42
    size_t             nm_size;
    bool               nm_creds_has : 1;
43
44
45
};

struct nl_sock {
46
47
    struct sockaddr_nl s_local;
    struct sockaddr_nl s_peer;
48
    size_t             s_bufsize;
49
50
51
52
    int                s_fd;
    int                s_proto;
    unsigned int       s_seq_next;
    unsigned int       s_seq_expect;
53
54
    bool               s_msg_peek : 1;
    bool               s_auto_ack : 1;
55
56
57
58
};

/*****************************************************************************/

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
NM_UTILS_ENUM2STR_DEFINE(nl_nlmsgtype2str,
                         int,
                         NM_UTILS_ENUM2STR(NLMSG_NOOP, "NOOP"),
                         NM_UTILS_ENUM2STR(NLMSG_ERROR, "ERROR"),
                         NM_UTILS_ENUM2STR(NLMSG_DONE, "DONE"),
                         NM_UTILS_ENUM2STR(NLMSG_OVERRUN, "OVERRUN"), );

NM_UTILS_FLAGS2STR_DEFINE(nl_nlmsg_flags2str,
                          int,
                          NM_UTILS_FLAGS2STR(NLM_F_REQUEST, "REQUEST"),
                          NM_UTILS_FLAGS2STR(NLM_F_MULTI, "MULTI"),
                          NM_UTILS_FLAGS2STR(NLM_F_ACK, "ACK"),
                          NM_UTILS_FLAGS2STR(NLM_F_ECHO, "ECHO"),
                          NM_UTILS_FLAGS2STR(NLM_F_ROOT, "ROOT"),
                          NM_UTILS_FLAGS2STR(NLM_F_MATCH, "MATCH"),
                          NM_UTILS_FLAGS2STR(NLM_F_ATOMIC, "ATOMIC"),
                          NM_UTILS_FLAGS2STR(NLM_F_REPLACE, "REPLACE"),
                          NM_UTILS_FLAGS2STR(NLM_F_EXCL, "EXCL"),
                          NM_UTILS_FLAGS2STR(NLM_F_CREATE, "CREATE"),
                          NM_UTILS_FLAGS2STR(NLM_F_APPEND, "APPEND"), );
79

80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
static NM_UTILS_LOOKUP_STR_DEFINE(_rtnl_type_to_str,
                                  guint16,
                                  NM_UTILS_LOOKUP_DEFAULT(NULL),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_GETLINK, "RTM_GETLINK"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_NEWLINK, "RTM_NEWLINK"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_DELLINK, "RTM_DELLINK"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_SETLINK, "RTM_SETLINK"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_GETADDR, "RTM_GETADDR"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_NEWADDR, "RTM_NEWADDR"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_DELADDR, "RTM_DELADDR"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_GETROUTE, "RTM_GETROUTE"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_NEWROUTE, "RTM_NEWROUTE"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_DELROUTE, "RTM_DELROUTE"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_GETRULE, "RTM_GETRULE"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_NEWRULE, "RTM_NEWRULE"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_DELRULE, "RTM_DELRULE"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_GETQDISC, "RTM_GETQDISC"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_NEWQDISC, "RTM_NEWQDISC"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_DELQDISC, "RTM_DELQDISC"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_GETTFILTER, "RTM_GETTFILTER"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_NEWTFILTER, "RTM_NEWTFILTER"),
                                  NM_UTILS_LOOKUP_STR_ITEM(RTM_DELTFILTER, "RTM_DELTFILTER"),
                                  NM_UTILS_LOOKUP_STR_ITEM(NLMSG_NOOP, "NLMSG_NOOP"),
                                  NM_UTILS_LOOKUP_STR_ITEM(NLMSG_ERROR, "NLMSG_ERROR"),
                                  NM_UTILS_LOOKUP_STR_ITEM(NLMSG_DONE, "NLMSG_DONE"),
                                  NM_UTILS_LOOKUP_STR_ITEM(NLMSG_OVERRUN, "NLMSG_OVERRUN"), );

static NM_UTILS_LOOKUP_STR_DEFINE(
    _genl_ctrl_cmd_to_str,
    guint8,
    NM_UTILS_LOOKUP_DEFAULT(NULL),
    NM_UTILS_LOOKUP_STR_ITEM(CTRL_CMD_UNSPEC, "CTRL_CMD_UNSPEC"),
    NM_UTILS_LOOKUP_STR_ITEM(CTRL_CMD_NEWFAMILY, "CTRL_CMD_NEWFAMILY"),
    NM_UTILS_LOOKUP_STR_ITEM(CTRL_CMD_DELFAMILY, "CTRL_CMD_DELFAMILY"),
    NM_UTILS_LOOKUP_STR_ITEM(CTRL_CMD_GETFAMILY, "CTRL_CMD_GETFAMILY"),
    NM_UTILS_LOOKUP_STR_ITEM(CTRL_CMD_NEWOPS, "CTRL_CMD_NEWOPS"),
    NM_UTILS_LOOKUP_STR_ITEM(CTRL_CMD_DELOPS, "CTRL_CMD_DELOPS"),
    NM_UTILS_LOOKUP_STR_ITEM(CTRL_CMD_GETOPS, "CTRL_CMD_GETOPS"),
    NM_UTILS_LOOKUP_STR_ITEM(CTRL_CMD_NEWMCAST_GRP, "CTRL_CMD_NEWMCAST_GRP"),
    NM_UTILS_LOOKUP_STR_ITEM(CTRL_CMD_DELMCAST_GRP, "CTRL_CMD_DELMCAST_GRP"),
    NM_UTILS_LOOKUP_STR_ITEM(CTRL_CMD_GETMCAST_GRP, "CTRL_CMD_GETMCAST_GRP"),
121
122
123
    /* CTRL_CMD_GETPOLICY was added in Linux 5.7 (released on 31 May, 2020),
     * commit d07dcf9aadd6 ('netlink: add infrastructure to expose policies to userspace') */
    NM_UTILS_LOOKUP_STR_ITEM(10 /* CTRL_CMD_GETPOLICY */, "CTRL_CMD_GETPOLICY"), );
124

125
126
127
/*****************************************************************************/

const char *
128
129
130
131
132
nl_nlmsghdr_to_str(int                    netlink_protocol,
                   guint32                pktinfo_group,
                   const struct nlmsghdr *hdr,
                   char                  *buf,
                   gsize                  len)
133
{
134
    const char *b;
135
    const char *s = NULL;
136
137
138
139
140
141
142
143
    guint       flags, flags_before;
    const char *prefix;

    if (!nm_utils_to_string_buffer_init_null(hdr, &buf, &len))
        return buf;

    b = buf;

144
145
    switch (netlink_protocol) {
    case NETLINK_ROUTE:
146
147
148
149
150
        s = _rtnl_type_to_str(hdr->nlmsg_type);
        if (s)
            nm_strbuf_append_str(&buf, &len, s);
        else
            nm_strbuf_append(&buf, &len, "(%u)", (unsigned) hdr->nlmsg_type);
151
        break;
152
153
154
    default:
        nm_assert_not_reached();
        /* fall-through */
155
    case NETLINK_GENERIC:
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
        if (pktinfo_group == 0)
            nm_strbuf_append(&buf, &len, "group:unicast");
        else
            nm_strbuf_append(&buf, &len, "group:multicast(%u)", (unsigned) pktinfo_group);

        s = NULL;
        if (hdr->nlmsg_type == GENL_ID_CTRL)
            s = "GENL_ID_CTRL";
        if (s)
            nm_strbuf_append(&buf, &len, ", msg-type:%s", s);
        else
            nm_strbuf_append(&buf, &len, ", msg-type:(%u)", (unsigned) hdr->nlmsg_type);

        if (genlmsg_valid_hdr(hdr, 0)) {
            const struct genlmsghdr *ghdr;

            ghdr = nlmsg_data(hdr);
            s    = NULL;
            if (hdr->nlmsg_type == GENL_ID_CTRL)
                s = _genl_ctrl_cmd_to_str(ghdr->cmd);
            if (s)
                nm_strbuf_append(&buf, &len, ", cmd:%s", s);
            else
                nm_strbuf_append(&buf, &len, ", cmd:(%u)", (unsigned) ghdr->cmd);
        }
181
182
183
184
185
186
        break;
    }

    flags = hdr->nlmsg_flags;

    if (!flags) {
187
        nm_strbuf_append_str(&buf, &len, ", flags 0");
188
189
190
        goto flags_done;
    }

191
192
193
194
195
196
197
198
199
200
201
#define _F(f, n)                                             \
    G_STMT_START                                             \
    {                                                        \
        if (NM_FLAGS_ALL(flags, f)) {                        \
            flags &= ~(f);                                   \
            nm_strbuf_append(&buf, &len, "%s%s", prefix, n); \
            if (!flags)                                      \
                goto flags_done;                             \
            prefix = ",";                                    \
        }                                                    \
    }                                                        \
202
203
204
205
206
207
208
209
210
211
212
213
214
215
    G_STMT_END

    prefix       = ", flags ";
    flags_before = flags;
    _F(NLM_F_REQUEST, "request");
    _F(NLM_F_MULTI, "multi");
    _F(NLM_F_ACK, "ack");
    _F(NLM_F_ECHO, "echo");
    _F(NLM_F_DUMP_INTR, "dump_intr");
    _F(0x20 /*NLM_F_DUMP_FILTERED*/, "dump_filtered");

    if (flags_before != flags)
        prefix = ";";

216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
    switch (netlink_protocol) {
    case NETLINK_ROUTE:
        switch (hdr->nlmsg_type) {
        case RTM_NEWLINK:
        case RTM_NEWADDR:
        case RTM_NEWROUTE:
        case RTM_NEWQDISC:
        case RTM_NEWTFILTER:
            _F(NLM_F_REPLACE, "replace");
            _F(NLM_F_EXCL, "excl");
            _F(NLM_F_CREATE, "create");
            _F(NLM_F_APPEND, "append");
            break;
        case RTM_GETLINK:
        case RTM_GETADDR:
        case RTM_GETROUTE:
        case RTM_DELQDISC:
        case RTM_DELTFILTER:
            _F(NLM_F_DUMP, "dump");
            _F(NLM_F_ROOT, "root");
            _F(NLM_F_MATCH, "match");
            _F(NLM_F_ATOMIC, "atomic");
            break;
        }
240
    }
241
242
243

#undef _F

244
245
    if (flags_before != flags)
        prefix = ";";
246
    nm_strbuf_append(&buf, &len, "%s0x%04x", prefix, flags);
247
248
249

flags_done:

250
    nm_strbuf_append(&buf, &len, ", seq %u", (unsigned) hdr->nlmsg_seq);
251

252
    return b;
253
254
}

255
256
257
/*****************************************************************************/

struct nlmsghdr *
258
nlmsg_hdr(struct nl_msg *n)
259
{
260
    return n->nm_nlh;
261
262
263
}

void *
264
nlmsg_reserve(struct nl_msg *n, size_t len, int pad)
265
{
266
    char  *buf       = (char *) n->nm_nlh;
267
268
    size_t nlmsg_len = n->nm_nlh->nlmsg_len;
    size_t tlen;
269

270
    nm_assert(pad >= 0);
271

272
273
    if (len > n->nm_size)
        return NULL;
274

275
    tlen = pad ? ((len + (pad - 1)) & ~(pad - 1)) : len;
276

277
278
    if ((tlen + nlmsg_len) > n->nm_size)
        return NULL;
279

280
281
    buf += nlmsg_len;
    n->nm_nlh->nlmsg_len += tlen;
282

283
284
    if (tlen > len)
        memset(buf + len, 0, tlen - len);
285

286
    return buf;
287
288
289
290
291
}

/*****************************************************************************/

struct nlattr *
292
nla_reserve(struct nl_msg *msg, int attrtype, int attrlen)
293
{
294
295
    struct nlattr *nla;
    int            tlen;
296

297
298
    if (attrlen < 0)
        return NULL;
299

300
    tlen = NLMSG_ALIGN(msg->nm_nlh->nlmsg_len) + nla_total_size(attrlen);
301

302
303
    if (tlen > msg->nm_size)
        return NULL;
304

305
306
307
    nla           = (struct nlattr *) nlmsg_tail(msg->nm_nlh);
    nla->nla_type = attrtype;
    nla->nla_len  = nla_attr_size(attrlen);
308

309
310
311
    if (attrlen)
        memset((unsigned char *) nla + nla->nla_len, 0, nla_padlen(attrlen));
    msg->nm_nlh->nlmsg_len = tlen;
312

313
    return nla;
314
315
}

Thomas Haller's avatar
Thomas Haller committed
316
317
/*****************************************************************************/

318
struct nl_msg *
319
nlmsg_alloc_size(size_t len)
320
{
321
322
323
324
325
326
327
328
329
330
331
332
333
    struct nl_msg *nm;

    if (len < sizeof(struct nlmsghdr))
        len = sizeof(struct nlmsghdr);

    nm  = g_slice_new(struct nl_msg);
    *nm = (struct nl_msg){
        .nm_protocol = -1,
        .nm_size     = len,
        .nm_nlh      = g_malloc0(len),
    };
    nm->nm_nlh->nlmsg_len = nlmsg_total_size(0);
    return nm;
334
335
336
337
338
339
340
341
342
343
344
345
}

/**
 * Allocate a new netlink message with the default maximum payload size.
 *
 * Allocates a new netlink message without any further payload. The
 * maximum payload size defaults to PAGESIZE or as otherwise specified
 * with nlmsg_set_default_size().
 *
 * @return Newly allocated netlink message or NULL.
 */
struct nl_msg *
346
nlmsg_alloc(void)
347
{
348
    return nlmsg_alloc_size(nm_utils_getpagesize());
349
350
351
}

struct nl_msg *
352
nlmsg_alloc_convert(struct nlmsghdr *hdr)
353
{
354
    struct nl_msg *nm;
355

356
357
358
    nm = nlmsg_alloc_size(NLMSG_ALIGN(hdr->nlmsg_len));
    memcpy(nm->nm_nlh, hdr, hdr->nlmsg_len);
    return nm;
359
360
361
}

struct nl_msg *
362
nlmsg_alloc_simple(int nlmsgtype, int flags)
363
{
364
365
366
367
368
369
370
371
    struct nl_msg *nm;
    struct nlmsghdr *new;

    nm               = nlmsg_alloc();
    new              = nm->nm_nlh;
    new->nlmsg_type  = nlmsgtype;
    new->nlmsg_flags = flags;
    return nm;
372
373
}

374
375
void
nlmsg_free(struct nl_msg *msg)
Thomas Haller's avatar
Thomas Haller committed
376
{
377
378
    if (!msg)
        return;
Thomas Haller's avatar
Thomas Haller committed
379

380
381
    g_free(msg->nm_nlh);
    g_slice_free(struct nl_msg, msg);
Thomas Haller's avatar
Thomas Haller committed
382
383
384
385
}

/*****************************************************************************/

386
int
387
nlmsg_append(struct nl_msg *n, const void *data, size_t len, int pad)
388
{
389
    void *tmp;
390

391
392
393
394
    nm_assert(n);
    nm_assert(data);
    nm_assert(len > 0);
    nm_assert(pad >= 0);
395

396
397
398
    tmp = nlmsg_reserve(n, len, pad);
    if (tmp == NULL)
        return -ENOMEM;
399

400
401
    memcpy(tmp, data, len);
    return 0;
402
403
}

Thomas Haller's avatar
Thomas Haller committed
404
405
/*****************************************************************************/

406
int
407
nlmsg_parse(const struct nlmsghdr   *nlh,
408
            int                      hdrlen,
409
            struct nlattr           *tb[],
410
411
            int                      maxtype,
            const struct nla_policy *policy)
412
{
413
414
    if (!nlmsg_valid_hdr(nlh, hdrlen))
        return -NME_NL_MSG_TOOSHORT;
415

416
    return nla_parse(tb, maxtype, nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), policy);
417
418
419
}

struct nlmsghdr *
420
nlmsg_put(struct nl_msg *n, uint32_t pid, uint32_t seq, int type, int payload, int flags)
421
{
422
    struct nlmsghdr *nlh;
423

424
425
    if (n->nm_nlh->nlmsg_len < NLMSG_HDRLEN)
        g_return_val_if_reached(NULL);
426

427
428
429
430
431
    nlh              = (struct nlmsghdr *) n->nm_nlh;
    nlh->nlmsg_type  = type;
    nlh->nlmsg_flags = flags;
    nlh->nlmsg_pid   = pid;
    nlh->nlmsg_seq   = seq;
432

433
434
    if (payload > 0 && nlmsg_reserve(n, payload, NLMSG_ALIGNTO) == NULL)
        return NULL;
435

436
    return nlh;
437
438
439
}

size_t
440
nla_strlcpy(char *dst, const struct nlattr *nla, size_t dstsize)
441
{
442
443
444
    const char *src;
    size_t      srclen;
    size_t      len;
445

446
    /* - Always writes @dstsize bytes to @dst
447
448
449
450
     * - Copies the first non-NUL characters to @dst.
     *   Any characters after the first NUL bytes in @nla are ignored.
     * - If the string @nla is longer than @dstsize, the string
     *   gets truncated. @dst will always be NUL terminated. */
451

452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
    if (G_UNLIKELY(dstsize <= 1)) {
        if (dstsize == 1)
            dst[0] = '\0';
        if (nla && (srclen = nla_len(nla)) > 0)
            return strnlen(nla_data(nla), srclen);
        return 0;
    }

    nm_assert(dst);

    if (nla) {
        srclen = nla_len(nla);
        if (srclen > 0) {
            src    = nla_data(nla);
            srclen = strnlen(src, srclen);
            if (srclen > 0) {
                len = NM_MIN(dstsize - 1, srclen);
                memcpy(dst, src, len);
                memset(&dst[len], 0, dstsize - len);
                return srclen;
            }
        }
    }

    memset(dst, 0, dstsize);
    return 0;
478
479
}

480
size_t
481
nla_memcpy(void *dst, const struct nlattr *nla, size_t dstsize)
482
{
483
484
    size_t len;
    int    srclen;
485

486
487
    if (!nla)
        return 0;
488

489
    srclen = nla_len(nla);
490

491
492
493
494
    if (srclen <= 0) {
        nm_assert(srclen == 0);
        return 0;
    }
495

496
497
498
    len = NM_MIN((size_t) srclen, dstsize);
    if (len > 0) {
        /* there is a crucial difference between nla_strlcpy() and nla_memcpy().
499
500
         * The former always write @dstsize bytes (akin to strncpy()), here, we only
         * write the bytes that we actually have (leaving the remainder undefined). */
501
502
        memcpy(dst, nla_data(nla), len);
    }
503

504
    return srclen;
505
506
507
}

int
508
nla_put(struct nl_msg *msg, int attrtype, int datalen, const void *data)
509
{
510
    struct nlattr *nla;
511

512
513
514
515
    nla = nla_reserve(msg, attrtype, datalen);
    if (!nla) {
        if (datalen < 0)
            g_return_val_if_reached(-NME_BUG);
516

517
518
        return -ENOMEM;
    }
519

520
521
    if (datalen > 0)
        memcpy(nla_data(nla), data, datalen);
522

523
    return 0;
524
525
526
}

struct nlattr *
527
nla_find(const struct nlattr *head, int len, int attrtype)
528
{
529
530
    const struct nlattr *nla;
    int                  rem;
531

532
533
534
535
    nla_for_each_attr (nla, head, len, rem) {
        if (nla_type(nla) == attrtype)
            return (struct nlattr *) nla;
    }
536

537
    return NULL;
538
539
540
}

void
541
nla_nest_cancel(struct nl_msg *msg, const struct nlattr *attr)
542
{
543
544
545
546
547
548
549
550
551
    ssize_t len;

    len = (char *) nlmsg_tail(msg->nm_nlh) - (char *) attr;
    if (len < 0)
        g_return_if_reached();
    else if (len > 0) {
        msg->nm_nlh->nlmsg_len -= len;
        memset(nlmsg_tail(msg->nm_nlh), 0, len);
    }
552
553
554
}

struct nlattr *
555
nla_nest_start(struct nl_msg *msg, int attrtype)
556
{
557
    struct nlattr *start = (struct nlattr *) nlmsg_tail(msg->nm_nlh);
558

559
560
    if (nla_put(msg, NLA_F_NESTED | attrtype, 0, NULL) < 0)
        return NULL;
561

562
    return start;
563
564
565
}

static int
566
_nest_end(struct nl_msg *msg, struct nlattr *start, int keep_empty)
567
{
568
    size_t pad, len;
569

570
    len = (char *) nlmsg_tail(msg->nm_nlh) - (char *) start;
571

572
573
    if (len > USHRT_MAX || (!keep_empty && len == NLA_HDRLEN)) {
        /*
574
575
576
         * Max nlattr size exceeded or empty nested attribute, trim the
         * attribute header again
         */
577
        nla_nest_cancel(msg, start);
578

579
580
581
        /* Return error only if nlattr size was exceeded */
        return (len == NLA_HDRLEN) ? 0 : -NME_NL_ATTRSIZE;
    }
582

583
    start->nla_len = len;
584

585
586
587
    pad = NLMSG_ALIGN(msg->nm_nlh->nlmsg_len) - msg->nm_nlh->nlmsg_len;
    if (pad > 0) {
        /*
588
589
590
591
592
         * Data inside attribute does not end at a alignment boundary.
         * Pad accordingly and account for the additional space in
         * the message. nlmsg_reserve() may never fail in this situation,
         * the allocate message buffer must be a multiple of NLMSG_ALIGNTO.
         */
593
594
595
        if (!nlmsg_reserve(msg, pad, 0))
            g_return_val_if_reached(-NME_BUG);
    }
596

597
    return 0;
598
599
600
}

int
601
nla_nest_end(struct nl_msg *msg, struct nlattr *start)
602
{
603
    return _nest_end(msg, start, 0);
604
605
}

606
static const uint8_t nla_attr_minlen[NLA_TYPE_MAX + 1] = {
607
608
609
610
611
    [NLA_U8]     = sizeof(uint8_t),
    [NLA_U16]    = sizeof(uint16_t),
    [NLA_U32]    = sizeof(uint32_t),
    [NLA_U64]    = sizeof(uint64_t),
    [NLA_STRING] = 1,
612
613
614
};

static int
615
validate_nla(const struct nlattr *nla, int maxtype, const struct nla_policy *policy)
616
{
617
    const struct nla_policy *pt;
618
    uint8_t                  minlen;
619
    uint16_t                 len;
620
    int                      type = nla_type(nla);
621

622
623
    if (type < 0 || type > maxtype)
        return 0;
624

625
    pt = &policy[type];
626

627
628
    if (pt->type > NLA_TYPE_MAX)
        g_return_val_if_reached(-NME_BUG);
629

630
    if (pt->minlen > 0)
631
        minlen = pt->minlen;
632
    else
633
        minlen = nla_attr_minlen[pt->type];
634

635
636
637
    len = nla_len(nla);

    if (len < minlen)
638
        return -NME_UNSPEC;
639

640
    if (pt->maxlen > 0 && len > pt->maxlen)
641
        return -NME_UNSPEC;
642

643
644
645
646
    switch (pt->type) {
    case NLA_STRING:
    {
        const char *data = nla_data(nla);
647

648
        nm_assert(minlen > 0);
649

650
        if (data[len - 1u] != '\0')
651
            return -NME_UNSPEC;
652
653
        break;
    }
654
    }
655

656
    return 0;
657
658
659
}

int
660
nla_parse(struct nlattr           *tb[],
661
          int                      maxtype,
662
          struct nlattr           *head,
663
664
          int                      len,
          const struct nla_policy *policy)
665
{
666
667
    struct nlattr *nla;
    int            rem, nmerr;
668

669
    memset(tb, 0, sizeof(struct nlattr *) * (maxtype + 1));
670

671
672
    nla_for_each_attr (nla, head, len, rem) {
        int type = nla_type(nla);
673

674
675
        if (type > maxtype)
            continue;
676

677
678
679
680
681
        if (policy) {
            nmerr = validate_nla(nla, maxtype, policy);
            if (nmerr < 0)
                return nmerr;
        }
682

683
684
        tb[type] = nla;
    }
685

686
    return 0;
687
688
689
690
691
}

/*****************************************************************************/

int
692
nlmsg_get_proto(struct nl_msg *msg)
693
{
694
    return msg->nm_protocol;
695
696
697
}

void
698
nlmsg_set_proto(struct nl_msg *msg, int protocol)
699
{
700
    msg->nm_protocol = protocol;
701
702
703
}

void
704
nlmsg_set_src(struct nl_msg *msg, struct sockaddr_nl *addr)
705
{
706
    memcpy(&msg->nm_src, addr, sizeof(*addr));
707
708
709
}

struct ucred *
710
nlmsg_get_creds(struct nl_msg *msg)
711
{
712
713
714
    if (msg->nm_creds_has)
        return &msg->nm_creds;
    return NULL;
715
716
717
}

void
718
nlmsg_set_creds(struct nl_msg *msg, struct ucred *creds)
719
{
720
721
722
723
724
    if (creds) {
        memcpy(&msg->nm_creds, creds, sizeof(*creds));
        msg->nm_creds_has = TRUE;
    } else
        msg->nm_creds_has = FALSE;
725
726
727
}

/*****************************************************************************/
728
729

void *
730
731
732
733
734
735
736
737
genlmsg_put(struct nl_msg *msg,
            uint32_t       port,
            uint32_t       seq,
            int            family,
            int            hdrlen,
            int            flags,
            uint8_t        cmd,
            uint8_t        version)
738
{
739
    struct nlmsghdr  *nlh;
740
741
742
743
    struct genlmsghdr hdr = {
        .cmd     = cmd,
        .version = version,
    };
744

745
746
747
    nlh = nlmsg_put(msg, port, seq, family, GENL_HDRLEN + hdrlen, flags);
    if (nlh == NULL)
        return NULL;
748

749
    memcpy(nlmsg_data(nlh), &hdr, sizeof(hdr));
750

751
    return (char *) nlmsg_data(nlh) + GENL_HDRLEN;
752
753
754
}

void *
755
genlmsg_data(const struct genlmsghdr *gnlh)
756
{
757
    return ((unsigned char *) gnlh + GENL_HDRLEN);
758
759
760
}

void *
761
genlmsg_user_hdr(const struct genlmsghdr *gnlh)
762
{
763
    return genlmsg_data(gnlh);
764
765
}

766
767
const struct genlmsghdr *
genlmsg_hdr(const struct nlmsghdr *nlh)
768
{
769
    return nlmsg_data(nlh);
770
771
772
}

void *
773
genlmsg_user_data(const struct genlmsghdr *gnlh, const int hdrlen)
774
{
775
    return (char *) genlmsg_user_hdr(gnlh) + NLMSG_ALIGN(hdrlen);
776
777
778
}

struct nlattr *
779
genlmsg_attrdata(const struct genlmsghdr *gnlh, int hdrlen)
780
{
781
    return genlmsg_user_data(gnlh, hdrlen);
782
783
784
}

int
785
genlmsg_len(const struct genlmsghdr *gnlh)
786
{
787
    const struct nlmsghdr *nlh;
788

789
790
    nlh = (const struct nlmsghdr *) ((const unsigned char *) gnlh - NLMSG_HDRLEN);
    return (nlh->nlmsg_len - GENL_HDRLEN - NLMSG_HDRLEN);
791
792
793
}

int
794
genlmsg_attrlen(const struct genlmsghdr *gnlh, int hdrlen)
795
{
796
    return genlmsg_len(gnlh) - NLMSG_ALIGN(hdrlen);
797
798
799
}

int
800
genlmsg_valid_hdr(const struct nlmsghdr *nlh, int hdrlen)
801
{
802
    struct genlmsghdr *ghdr;
803

804
805
    if (!nlmsg_valid_hdr(nlh, GENL_HDRLEN))
        return 0;
806

807
808
809
    ghdr = nlmsg_data(nlh);
    if (genlmsg_len(ghdr) < NLMSG_ALIGN(hdrlen))
        return 0;
810

811
    return 1;
812
813
814
}

int
815
genlmsg_parse(const struct nlmsghdr   *nlh,
816
              int                      hdrlen,
817
              struct nlattr           *tb[],
818
819
              int                      maxtype,
              const struct nla_policy *policy)
820
{
821
    const struct genlmsghdr *ghdr;
822

823
824
    if (!genlmsg_valid_hdr(nlh, hdrlen))
        return -NME_NL_MSG_TOOSHORT;
825

826
827
828
829
830
831
    ghdr = nlmsg_data(nlh);
    return nla_parse(tb,
                     maxtype,
                     genlmsg_attrdata(ghdr, hdrlen),
                     genlmsg_attrlen(ghdr, hdrlen),
                     policy);
832
833
}

834
835
836
837
838
839
840
841
842
843
const struct nla_policy genl_ctrl_policy[CTRL_ATTR_MCAST_GROUPS + 1] = {
    [CTRL_ATTR_FAMILY_ID]    = {.type = NLA_U16},
    [CTRL_ATTR_FAMILY_NAME]  = {.type = NLA_STRING, .maxlen = GENL_NAMSIZ},
    [CTRL_ATTR_VERSION]      = {.type = NLA_U32},
    [CTRL_ATTR_HDRSIZE]      = {.type = NLA_U32},
    [CTRL_ATTR_MAXATTR]      = {.type = NLA_U32},
    [CTRL_ATTR_OPS]          = {.type = NLA_NESTED},
    [CTRL_ATTR_MCAST_GROUPS] = {.type = NLA_NESTED},
};

844
static int
845
_genl_parse_getfamily(struct nl_msg *msg, void *arg)
846
{
847
    struct nlattr   *tb[G_N_ELEMENTS(genl_ctrl_policy)];
848
    struct nlmsghdr *nlh           = nlmsg_hdr(msg);
849
    gint32          *response_data = arg;
850

851
    if (genlmsg_parse_arr(nlh, 0, tb, genl_ctrl_policy) < 0)
852
853
854
855
856
857
        return NL_SKIP;

    if (tb[CTRL_ATTR_FAMILY_ID])
        *response_data = nla_get_u16(tb[CTRL_ATTR_FAMILY_ID]);

    return NL_STOP;
858
859
860
}

int
861
genl_ctrl_resolve(struct nl_sock *sk, const char *name)
862
{
863
864
865
866
    nm_auto_nlmsg struct nl_msg *msg = NULL;
    int                          nmerr;
    gint32                       response_data = -1;
    const struct nl_cb           cb            = {
867
868
                             .valid_cb  = _genl_parse_getfamily,
                             .valid_arg = &response_data,
869
    };
870

871
    msg = nlmsg_alloc();
872

873
874
    if (!genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, GENL_ID_CTRL, 0, 0, CTRL_CMD_GETFAMILY, 1))
        return -ENOMEM;
875

876
877
878
    nmerr = nla_put_string(msg, CTRL_ATTR_FAMILY_NAME, name);
    if (nmerr < 0)
        return nmerr;
879

880
881
882
    nmerr = nl_send_auto(sk, msg);
    if (nmerr < 0)
        return nmerr;
883

884
885
886
    nmerr = nl_recvmsgs(sk, &cb);
    if (nmerr < 0)
        return nmerr;
887

888
889
890
891
    /* If search was successful, request may be ACKed after data */
    nmerr = nl_wait_for_ack(sk, NULL);
    if (nmerr < 0)
        return nmerr;
892

893
894
    if (response_data < 0)
        return -NME_UNSPEC;
895

896
    return response_data;
897
898
}

899
/*****************************************************************************/
900
901

void
902
nl_socket_free(struct nl_sock *sk)
903
{
904
905
    if (!sk)
        return;
906

907
908
    nm_close(sk->s_fd);
    nm_g_slice_free(sk);
909
910
911
}

int
912
nl_socket_get_fd(const struct nl_sock *sk)
913
{
914
    return sk->s_fd;
915
916
917
}

uint32_t
918
nl_socket_get_local_port(const struct nl_sock *sk)
919
{
920
    return sk->s_local.nl_pid;
921
922
923
}

size_t
924
nl_socket_get_msg_buf_size(struct nl_sock *sk)
925
{
926
    return sk->s_bufsize;
927
928
929
}

int
930
nl_socket_set_passcred(struct nl_sock *sk, int state)
931
{
932
    int err;
933

934
    nm_assert_sk(sk);
935

936
937
938
    err = setsockopt(sk->s_fd, SOL_SOCKET, SO_PASSCRED, &state, sizeof(state));
    if (err < 0)
        return -nm_errno_from_native(errno);
939
940
    return 0;
}
941

942
943
944
945
int
nl_socket_set_pktinfo(struct nl_sock *sk, int state)
{
    int err;
946

947
948
949
950
951
    nm_assert_sk(sk);

    err = setsockopt(sk->s_fd, SOL_NETLINK, NETLINK_PKTINFO, &state, sizeof(state));
    if (err < 0)
        return -nm_errno_from_native(errno);
952
    return 0;
953
954
955
}

int
956
nl_socket_set_msg_buf_size(struct nl_sock *sk, size_t bufsize)
957
{