summaryrefslogtreecommitdiff
path: root/src/libnm-platform/nm-netlink.c
blob: 571de3b819746bbb9296c8018a45eee0046872cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
 * Copyright (C) 2018 Red Hat, Inc.
 */

#include "libnm-glib-aux/nm-default-glib-i18n-lib.h"

#include "nm-netlink.h"

#include <unistd.h>
#include <fcntl.h>

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

#ifndef SOL_NETLINK
#define SOL_NETLINK 270
#endif

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

#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

#define NL_SOCK_PASSCRED     (1 << 1)
#define NL_MSG_PEEK          (1 << 3)
#define NL_MSG_PEEK_EXPLICIT (1 << 4)
#define NL_NO_AUTO_ACK       (1 << 5)

#ifndef NETLINK_EXT_ACK
#define NETLINK_EXT_ACK 11
#endif

struct nl_msg {
    int                nm_protocol;
    struct sockaddr_nl nm_src;
    struct sockaddr_nl nm_dst;
    struct ucred       nm_creds;
    struct nlmsghdr   *nm_nlh;
    size_t             nm_size;
    bool               nm_creds_has : 1;
};

struct nl_sock {
    struct sockaddr_nl s_local;
    struct sockaddr_nl s_peer;
    int                s_fd;
    int                s_proto;
    unsigned int       s_seq_next;
    unsigned int       s_seq_expect;
    int                s_flags;
    size_t             s_bufsize;
};

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

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"), );

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

const char *
nl_nlmsghdr_to_str(int netlink_protocol, const struct nlmsghdr *hdr, char *buf, gsize len)
{
    const char *b;
    const char *s = NULL;
    guint       flags, flags_before;
    const char *prefix;

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

    b = buf;

    switch (netlink_protocol) {
    case NETLINK_ROUTE:
        switch (hdr->nlmsg_type) {
        case RTM_GETLINK:
            s = "RTM_GETLINK";
            break;
        case RTM_NEWLINK:
            s = "RTM_NEWLINK";
            break;
        case RTM_DELLINK:
            s = "RTM_DELLINK";
            break;
        case RTM_SETLINK:
            s = "RTM_SETLINK";
            break;
        case RTM_GETADDR:
            s = "RTM_GETADDR";
            break;
        case RTM_NEWADDR:
            s = "RTM_NEWADDR";
            break;
        case RTM_DELADDR:
            s = "RTM_DELADDR";
            break;
        case RTM_GETROUTE:
            s = "RTM_GETROUTE";
            break;
        case RTM_NEWROUTE:
            s = "RTM_NEWROUTE";
            break;
        case RTM_DELROUTE:
            s = "RTM_DELROUTE";
            break;
        case RTM_GETRULE:
            s = "RTM_GETRULE";
            break;
        case RTM_NEWRULE:
            s = "RTM_NEWRULE";
            break;
        case RTM_DELRULE:
            s = "RTM_DELRULE";
            break;
        case RTM_GETQDISC:
            s = "RTM_GETQDISC";
            break;
        case RTM_NEWQDISC:
            s = "RTM_NEWQDISC";
            break;
        case RTM_DELQDISC:
            s = "RTM_DELQDISC";
            break;
        case RTM_GETTFILTER:
            s = "RTM_GETTFILTER";
            break;
        case RTM_NEWTFILTER:
            s = "RTM_NEWTFILTER";
            break;
        case RTM_DELTFILTER:
            s = "RTM_DELTFILTER";
            break;
        case NLMSG_NOOP:
            s = "NLMSG_NOOP";
            break;
        case NLMSG_ERROR:
            s = "NLMSG_ERROR";
            break;
        case NLMSG_DONE:
            s = "NLMSG_DONE";
            break;
        case NLMSG_OVERRUN:
            s = "NLMSG_OVERRUN";
            break;
        }
        break;
    case NETLINK_GENERIC:
        break;
    }

    if (s)
        nm_strbuf_append_str(&buf, &len, s);
    else
        nm_strbuf_append(&buf, &len, "(%u)", (unsigned) hdr->nlmsg_type);

    flags = hdr->nlmsg_flags;

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

#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 = ",";                                    \
        }                                                    \
    }                                                        \
    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 = ";";

    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;
        }
    }

#undef _F

    if (flags_before != flags)
        prefix = ";";
    nm_strbuf_append(&buf, &len, "%s0x%04x", prefix, flags);

flags_done:

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

    return b;
}

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

struct nlmsghdr *
nlmsg_hdr(struct nl_msg *n)
{
    return n->nm_nlh;
}

void *
nlmsg_reserve(struct nl_msg *n, size_t len, int pad)
{
    char  *buf       = (char *) n->nm_nlh;
    size_t nlmsg_len = n->nm_nlh->nlmsg_len;
    size_t tlen;

    nm_assert(pad >= 0);

    if (len > n->nm_size)
        return NULL;

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

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

    buf += nlmsg_len;
    n->nm_nlh->nlmsg_len += tlen;

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

    return buf;
}

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

struct nlattr *
nla_reserve(struct nl_msg *msg, int attrtype, int attrlen)
{
    struct nlattr *nla;
    int            tlen;

    if (attrlen < 0)
        return NULL;

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

    if (tlen > msg->nm_size)
        return NULL;

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

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

    return nla;
}

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

struct nl_msg *
nlmsg_alloc_size(size_t len)
{
    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;
}

/**
 * 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 *
nlmsg_alloc(void)
{
    return nlmsg_alloc_size(nm_utils_getpagesize());
}

struct nl_msg *
nlmsg_alloc_convert(struct nlmsghdr *hdr)
{
    struct nl_msg *nm;

    nm = nlmsg_alloc_size(NLMSG_ALIGN(hdr->nlmsg_len));
    memcpy(nm->nm_nlh, hdr, hdr->nlmsg_len);
    return nm;
}

struct nl_msg *
nlmsg_alloc_simple(int nlmsgtype, int flags)
{
    struct nl_msg *nm;
    struct nlmsghdr *new;

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

void
nlmsg_free(struct nl_msg *msg)
{
    if (!msg)
        return;

    g_free(msg->nm_nlh);
    g_slice_free(struct nl_msg, msg);
}

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

int
nlmsg_append(struct nl_msg *n, const void *data, size_t len, int pad)
{
    void *tmp;

    nm_assert(n);
    nm_assert(data);
    nm_assert(len > 0);
    nm_assert(pad >= 0);

    tmp = nlmsg_reserve(n, len, pad);
    if (tmp == NULL)
        return -ENOMEM;

    memcpy(tmp, data, len);
    return 0;
}

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

int
nlmsg_parse(const struct nlmsghdr   *nlh,
            int                      hdrlen,
            struct nlattr           *tb[],
            int                      maxtype,
            const struct nla_policy *policy)
{
    if (!nlmsg_valid_hdr(nlh, hdrlen))
        return -NME_NL_MSG_TOOSHORT;

    return nla_parse(tb, maxtype, nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), policy);
}

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

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

    nlh              = (struct nlmsghdr *) n->nm_nlh;
    nlh->nlmsg_type  = type;
    nlh->nlmsg_flags = flags;
    nlh->nlmsg_pid   = pid;
    nlh->nlmsg_seq   = seq;

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

    return nlh;
}

size_t
nla_strlcpy(char *dst, const struct nlattr *nla, size_t dstsize)
{
    const char *src;
    size_t      srclen;
    size_t      len;

    /* - Always writes @dstsize bytes to @dst
     * - 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. */

    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;
}

size_t
nla_memcpy(void *dst, const struct nlattr *nla, size_t dstsize)
{
    size_t len;
    int    srclen;

    if (!nla)
        return 0;

    srclen = nla_len(nla);

    if (srclen <= 0) {
        nm_assert(srclen == 0);
        return 0;
    }

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

    return srclen;
}

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

    nla = nla_reserve(msg, attrtype, datalen);
    if (!nla) {
        if (datalen < 0)
            g_return_val_if_reached(-NME_BUG);

        return -ENOMEM;
    }

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

    return 0;
}

struct nlattr *
nla_find(const struct nlattr *head, int len, int attrtype)
{
    const struct nlattr *nla;
    int                  rem;

    nla_for_each_attr (nla, head, len, rem) {
        if (nla_type(nla) == attrtype)
            return (struct nlattr *) nla;
    }

    return NULL;
}

void
nla_nest_cancel(struct nl_msg *msg, const struct nlattr *attr)
{
    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);
    }
}

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

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

    return start;
}

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

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

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

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

    start->nla_len = len;

    pad = NLMSG_ALIGN(msg->nm_nlh->nlmsg_len) - msg->nm_nlh->nlmsg_len;
    if (pad > 0) {
        /*
         * 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.
         */
        if (!nlmsg_reserve(msg, pad, 0))
            g_return_val_if_reached(-NME_BUG);
    }

    return 0;
}

int
nla_nest_end(struct nl_msg *msg, struct nlattr *start)
{
    return _nest_end(msg, start, 0);
}

static const uint8_t nla_attr_minlen[NLA_TYPE_MAX + 1] = {
    [NLA_U8]     = sizeof(uint8_t),
    [NLA_U16]    = sizeof(uint16_t),
    [NLA_U32]    = sizeof(uint32_t),
    [NLA_U64]    = sizeof(uint64_t),
    [NLA_STRING] = 1,
};

static int
validate_nla(const struct nlattr *nla, int maxtype, const struct nla_policy *policy)
{
    const struct nla_policy *pt;
    uint8_t                  minlen;
    uint16_t                 len;
    int                      type = nla_type(nla);

    if (type < 0 || type > maxtype)
        return 0;

    pt = &policy[type];

    if (pt->type > NLA_TYPE_MAX)
        g_return_val_if_reached(-NME_BUG);

    if (pt->minlen > 0)
        minlen = pt->minlen;
    else
        minlen = nla_attr_minlen[pt->type];

    len = nla_len(nla);

    if (len < minlen)
        return -NME_UNSPEC;

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

    switch (pt->type) {
    case NLA_STRING:
    {
        const char *data = nla_data(nla);

        nm_assert(minlen > 0);

        if (data[len - 1u] != '\0')
            return -NME_UNSPEC;
        break;
    }
    }

    return 0;
}

int
nla_parse(struct nlattr           *tb[],
          int                      maxtype,
          struct nlattr           *head,
          int                      len,
          const struct nla_policy *policy)
{
    struct nlattr *nla;
    int            rem, nmerr;

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

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

        if (type > maxtype)
            continue;

        if (policy) {
            nmerr = validate_nla(nla, maxtype, policy);
            if (nmerr < 0)
                return nmerr;
        }

        tb[type] = nla;
    }

    return 0;
}

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

int
nlmsg_get_proto(struct nl_msg *msg)
{
    return msg->nm_protocol;
}

void
nlmsg_set_proto(struct nl_msg *msg, int protocol)
{
    msg->nm_protocol = protocol;
}

void
nlmsg_set_src(struct nl_msg *msg, struct sockaddr_nl *addr)
{
    memcpy(&msg->nm_src, addr, sizeof(*addr));
}

struct ucred *
nlmsg_get_creds(struct nl_msg *msg)
{
    if (msg->nm_creds_has)
        return &msg->nm_creds;
    return NULL;
}

void
nlmsg_set_creds(struct nl_msg *msg, struct ucred *creds)
{
    if (creds) {
        memcpy(&msg->nm_creds, creds, sizeof(*creds));
        msg->nm_creds_has = TRUE;
    } else
        msg->nm_creds_has = FALSE;
}

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

void *
genlmsg_put(struct nl_msg *msg,
            uint32_t       port,
            uint32_t       seq,
            int            family,
            int            hdrlen,
            int            flags,
            uint8_t        cmd,
            uint8_t        version)
{
    struct nlmsghdr  *nlh;
    struct genlmsghdr hdr = {
        .cmd     = cmd,
        .version = version,
    };

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

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

    return (char *) nlmsg_data(nlh) + GENL_HDRLEN;
}

void *
genlmsg_data(const struct genlmsghdr *gnlh)
{
    return ((unsigned char *) gnlh + GENL_HDRLEN);
}

void *
genlmsg_user_hdr(const struct genlmsghdr *gnlh)
{
    return genlmsg_data(gnlh);
}

const struct genlmsghdr *
genlmsg_hdr(const struct nlmsghdr *nlh)
{
    return nlmsg_data(nlh);
}

void *
genlmsg_user_data(const struct genlmsghdr *gnlh, const int hdrlen)
{
    return (char *) genlmsg_user_hdr(gnlh) + NLMSG_ALIGN(hdrlen);
}

struct nlattr *
genlmsg_attrdata(const struct genlmsghdr *gnlh, int hdrlen)
{
    return genlmsg_user_data(gnlh, hdrlen);
}

int
genlmsg_len(const struct genlmsghdr *gnlh)
{
    const struct nlmsghdr *nlh;

    nlh = (const struct nlmsghdr *) ((const unsigned char *) gnlh - NLMSG_HDRLEN);
    return (nlh->nlmsg_len - GENL_HDRLEN - NLMSG_HDRLEN);
}

int
genlmsg_attrlen(const struct genlmsghdr *gnlh, int hdrlen)
{
    return genlmsg_len(gnlh) - NLMSG_ALIGN(hdrlen);
}

int
genlmsg_valid_hdr(const struct nlmsghdr *nlh, int hdrlen)
{
    struct genlmsghdr *ghdr;

    if (!nlmsg_valid_hdr(nlh, GENL_HDRLEN))
        return 0;

    ghdr = nlmsg_data(nlh);
    if (genlmsg_len(ghdr) < NLMSG_ALIGN(hdrlen))
        return 0;

    return 1;
}

int
genlmsg_parse(const struct nlmsghdr   *nlh,
              int                      hdrlen,
              struct nlattr           *tb[],
              int                      maxtype,
              const struct nla_policy *policy)
{
    const struct genlmsghdr *ghdr;

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

    ghdr = nlmsg_data(nlh);
    return nla_parse(tb,
                     maxtype,
                     genlmsg_attrdata(ghdr, hdrlen),
                     genlmsg_attrlen(ghdr, hdrlen),
                     policy);
}

static int
_genl_parse_getfamily(struct nl_msg *msg, void *arg)
{
    static const struct nla_policy ctrl_policy[] = {
        [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},
    };
    struct nlattr   *tb[G_N_ELEMENTS(ctrl_policy)];
    struct nlmsghdr *nlh           = nlmsg_hdr(msg);
    gint32          *response_data = arg;

    if (genlmsg_parse_arr(nlh, 0, tb, ctrl_policy) < 0)
        return NL_SKIP;

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

    return NL_STOP;
}

int
genl_ctrl_resolve(struct nl_sock *sk, const char *name)
{
    nm_auto_nlmsg struct nl_msg *msg = NULL;
    int                          nmerr;
    gint32                       response_data = -1;
    const struct nl_cb           cb            = {
                             .valid_cb  = _genl_parse_getfamily,
                             .valid_arg = &response_data,
    };

    msg = nlmsg_alloc();

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

    nmerr = nla_put_string(msg, CTRL_ATTR_FAMILY_NAME, name);
    if (nmerr < 0)
        return nmerr;

    nmerr = nl_send_auto(sk, msg);
    if (nmerr < 0)
        return nmerr;

    nmerr = nl_recvmsgs(sk, &cb);
    if (nmerr < 0)
        return nmerr;

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

    if (response_data < 0)
        return -NME_UNSPEC;

    return response_data;
}

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

void
nl_socket_free(struct nl_sock *sk)
{
    if (!sk)
        return;

    nm_close(sk->s_fd);
    nm_g_slice_free(sk);
}

int
nl_socket_get_fd(const struct nl_sock *sk)
{
    return sk->s_fd;
}

uint32_t
nl_socket_get_local_port(const struct nl_sock *sk)
{
    return sk->s_local.nl_pid;
}

size_t
nl_socket_get_msg_buf_size(struct nl_sock *sk)
{
    return sk->s_bufsize;
}

int
nl_socket_set_passcred(struct nl_sock *sk, int state)
{
    int err;

    nm_assert_sk(sk);

    err = setsockopt(sk->s_fd, SOL_SOCKET, SO_PASSCRED, &state, sizeof(state));
    if (err < 0)
        return -nm_errno_from_native(errno);

    if (state)
        sk->s_flags |= NL_SOCK_PASSCRED;
    else
        sk->s_flags &= ~NL_SOCK_PASSCRED;

    return 0;
}

int
nl_socket_set_msg_buf_size(struct nl_sock *sk, size_t bufsize)
{
    sk->s_bufsize = bufsize;

    return 0;
}

struct sockaddr_nl *
nlmsg_get_dst(struct nl_msg *msg)
{
    return &msg->nm_dst;
}

int
nl_socket_set_nonblocking(const struct nl_sock *sk)
{
    nm_assert_sk(sk);

    if (fcntl(sk->s_fd, F_SETFL, O_NONBLOCK) < 0)
        return -nm_errno_from_native(errno);

    return 0;
}

int
nl_socket_set_buffer_size(struct nl_sock *sk, int rxbuf, int txbuf)
{
    int err;

    nm_assert_sk(sk);

    if (rxbuf <= 0)
        rxbuf = 32768;

    if (txbuf <= 0)
        txbuf = 32768;

    err = setsockopt(sk->s_fd, SOL_SOCKET, SO_SNDBUF, &txbuf, sizeof(txbuf));
    if (err < 0) {
        return -nm_errno_from_native(errno);
    }

    err = setsockopt(sk->s_fd, SOL_SOCKET, SO_RCVBUF, &rxbuf, sizeof(rxbuf));
    if (err < 0) {
        return -nm_errno_from_native(errno);
    }

    return 0;
}

int
nl_socket_add_memberships(struct nl_sock *sk, int group, ...)
{
    int     err;
    va_list ap;

    nm_assert_sk(sk);

    va_start(ap, group);

    while (group != 0) {
        if (group < 0) {
            va_end(ap);
            g_return_val_if_reached(-NME_BUG);
        }

        err = setsockopt(sk->s_fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group));
        if (err < 0) {
            int errsv = errno;

            va_end(ap);
            return -nm_errno_from_native(errsv);
        }

        group = va_arg(ap, int);
    }

    va_end(ap);

    return 0;
}

int
nl_socket_set_ext_ack(struct nl_sock *sk, gboolean enable)
{
    int err;
    int val;

    nm_assert_sk(sk);

    val = !!enable;
    err = setsockopt(sk->s_fd, SOL_NETLINK, NETLINK_EXT_ACK, &val, sizeof(val));
    if (err < 0)
        return -nm_errno_from_native(errno);

    return 0;
}

void
nl_socket_disable_msg_peek(struct nl_sock *sk)
{
    sk->s_flags |= NL_MSG_PEEK_EXPLICIT;
    sk->s_flags &= ~NL_MSG_PEEK;
}

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

int
nl_socket_new(struct nl_sock **out_sk, int protocol, bool blocking, int bufsize_rx, int bufsize_tx)
{
    nm_auto_nlsock struct nl_sock *sk = NULL;
    nm_auto_close int              fd = -1;
    time_t                         t;
    int                            err;
    int                            nmerr;
    socklen_t                      addrlen;
    struct sockaddr_nl             local = {0};

    nm_assert(out_sk && !*out_sk);

    fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC | (blocking ? 0 : SOCK_NONBLOCK), protocol);
    if (fd < 0)
        return -nm_errno_from_native(errno);

    t = time(NULL);

    sk  = g_slice_new(struct nl_sock);
    *sk = (struct nl_sock){
        .s_fd = nm_steal_fd(&fd),
        .s_local =
            {
                .nl_pid    = 0,
                .nl_family = AF_NETLINK,
                .nl_groups = 0,
            },
        .s_peer =
            {
                .nl_pid    = 0,
                .nl_family = AF_NETLINK,
                .nl_groups = 0,
            },
        .s_seq_expect = t,
        .s_seq_next   = t,
    };

    nmerr = nl_socket_set_buffer_size(sk, bufsize_rx, bufsize_tx);
    if (nmerr < 0)
        return nmerr;

    err = bind(sk->s_fd, (struct sockaddr *) &sk->s_local, sizeof(sk->s_local));
    if (err != 0)
        return -nm_errno_from_native(errno);

    addrlen = sizeof(local);
    err     = getsockname(sk->s_fd, (struct sockaddr *) &local, &addrlen);
    if (err < 0)
        return -nm_errno_from_native(errno);

    if (addrlen != sizeof(local))
        return -NME_UNSPEC;

    if (local.nl_family != AF_NETLINK)
        return -NME_UNSPEC;

    (void) nl_socket_set_ext_ack(sk, TRUE);

    sk->s_local = local;
    sk->s_proto = protocol;

    *out_sk = g_steal_pointer(&sk);
    return 0;
}

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

static void
_cb_init(struct nl_cb *dst, const struct nl_cb *src)
{
    nm_assert(dst);

    if (src)
        *dst = *src;
    else
        memset(dst, 0, sizeof(*dst));
}

static int
ack_wait_handler(struct nl_msg *msg, void *arg)
{
    return NL_STOP;
}

int
nl_wait_for_ack(struct nl_sock *sk, const struct nl_cb *cb)
{
    struct nl_cb cb2;

    _cb_init(&cb2, cb);
    cb2.ack_cb = ack_wait_handler;
    return nl_recvmsgs(sk, &cb2);
}

#define NL_CB_CALL(cb, type, msg)                                \
    do {                                                         \
        const struct nl_cb *_cb = (cb);                          \
                                                                 \
        if (_cb && _cb->type##_cb) {                             \
            /* the returned value here must be either a negative
         * netlink error number, or one of NL_SKIP, NL_STOP, NL_OK. */ \
            nmerr = _cb->type##_cb((msg), _cb->type##_arg);      \
            switch (nmerr) {                                     \
            case NL_OK:                                          \
                nm_assert(nmerr == 0);                           \
                break;                                           \
            case NL_SKIP:                                        \
                goto skip;                                       \
            case NL_STOP:                                        \
                goto stop;                                       \
            default:                                             \
                if (nmerr >= 0) {                                \
                    nm_assert_not_reached();                     \
                    nmerr = -NME_BUG;                            \
                }                                                \
                goto out;                                        \
            }                                                    \
        }                                                        \
    } while (0)

int
nl_recvmsgs(struct nl_sock *sk, const struct nl_cb *cb)
{
    int                    n, nmerr = 0, multipart = 0, interrupted = 0, nrecv = 0;
    gs_free unsigned char *buf = NULL;
    struct nlmsghdr       *hdr;
    struct sockaddr_nl     nla;
    struct ucred           creds;
    gboolean               creds_has;

continue_reading:
    n = nl_recv(sk, NULL, 0, &nla, &buf, &creds, &creds_has);
    if (n <= 0)
        return n;

    hdr = (struct nlmsghdr *) buf;
    while (nlmsg_ok(hdr, n)) {
        nm_auto_nlmsg struct nl_msg *msg = NULL;

        msg = nlmsg_alloc_convert(hdr);

        nlmsg_set_proto(msg, sk->s_proto);
        nlmsg_set_src(msg, &nla);
        nlmsg_set_creds(msg, creds_has ? &creds : NULL);

        nrecv++;

        /* Only do sequence checking if auto-ack mode is enabled */
        if (!(sk->s_flags & NL_NO_AUTO_ACK)) {
            if (hdr->nlmsg_seq != sk->s_seq_expect) {
                nmerr = -NME_NL_SEQ_MISMATCH;
                goto out;
            }
        }

        if (hdr->nlmsg_type == NLMSG_DONE || hdr->nlmsg_type == NLMSG_ERROR
            || hdr->nlmsg_type == NLMSG_NOOP || hdr->nlmsg_type == NLMSG_OVERRUN) {
            /* We can't check for !NLM_F_MULTI since some netlink
             * users in the kernel are broken. */
            sk->s_seq_expect++;
        }

        if (hdr->nlmsg_flags & NLM_F_MULTI)
            multipart = 1;

        if (hdr->nlmsg_flags & NLM_F_DUMP_INTR) {
            /*
             * We have to continue reading to clear
             * all messages until a NLMSG_DONE is
             * received and report the inconsistency.
             */
            interrupted = 1;
        }

        /* messages terminates a multipart message, this is
         * usually the end of a message and therefore we slip
         * out of the loop by default. the user may overrule
         * this action by skipping this packet. */
        if (hdr->nlmsg_type == NLMSG_DONE) {
            multipart = 0;
            NL_CB_CALL(cb, finish, msg);
        }

        /* Message to be ignored, the default action is to
         * skip this message if no callback is specified. The
         * user may overrule this action by returning
         * NL_PROCEED. */
        else if (hdr->nlmsg_type == NLMSG_NOOP)
            goto skip;

        /* Data got lost, report back to user. The default action is to
         * quit parsing. The user may overrule this action by returning
         * NL_SKIP or NL_PROCEED (dangerous) */
        else if (hdr->nlmsg_type == NLMSG_OVERRUN) {
            nmerr = -NME_NL_MSG_OVERFLOW;
            goto out;
        }

        /* Message carries a nlmsgerr */
        else if (hdr->nlmsg_type == NLMSG_ERROR) {
            struct nlmsgerr *e = nlmsg_data(hdr);

            if (hdr->nlmsg_len < nlmsg_size(sizeof(*e))) {
                /* Truncated error message, the default action
                 * is to stop parsing. The user may overrule
                 * this action by returning NL_SKIP or
                 * NL_PROCEED (dangerous) */
                nmerr = -NME_NL_MSG_TRUNC;
                goto out;
            }
            if (e->error) {
                /* Error message reported back from kernel. */
                if (cb && cb->err_cb) {
                    /* the returned value here must be either a negative
                     * netlink error number, or one of NL_SKIP, NL_STOP, NL_OK. */
                    nmerr = cb->err_cb(&nla, e, cb->err_arg);
                    if (nmerr < 0)
                        goto out;
                    else if (nmerr == NL_SKIP)
                        goto skip;
                    else if (nmerr == NL_STOP) {
                        nmerr = -nm_errno_from_native(e->error);
                        goto out;
                    }
                    nm_assert(nmerr == NL_OK);
                } else {
                    nmerr = -nm_errno_from_native(e->error);
                    goto out;
                }
            } else
                NL_CB_CALL(cb, ack, msg);
        } else {
            /* Valid message (not checking for MULTIPART bit to
             * get along with broken kernels. NL_SKIP has no
             * effect on this.  */
            NL_CB_CALL(cb, valid, msg);
        }
skip:
        nmerr = 0;
        hdr   = nlmsg_next(hdr, &n);
    }

    if (multipart) {
        /* Multipart message not yet complete, continue reading */
        nm_clear_g_free(&buf);

        nmerr = 0;
        goto continue_reading;
    }

stop:
    nmerr = 0;

out:
    if (interrupted)
        nmerr = -NME_NL_DUMP_INTR;

    nm_assert(nmerr <= 0);
    return nmerr ?: nrecv;
}

int
nl_sendmsg(struct nl_sock *sk, struct nl_msg *msg, struct msghdr *hdr)
{
    int ret;

    if (sk->s_fd < 0)
        return -NME_NL_BAD_SOCK;

    nlmsg_set_src(msg, &sk->s_local);

    ret = sendmsg(sk->s_fd, hdr, 0);
    if (ret < 0)
        return -nm_errno_from_native(errno);

    return ret;
}

int
nl_send_iovec(struct nl_sock *sk, struct nl_msg *msg, struct iovec *iov, unsigned iovlen)
{
    struct sockaddr_nl *dst;
    struct ucred       *creds;
    struct msghdr       hdr = {
              .msg_name    = (void *) &sk->s_peer,
              .msg_namelen = sizeof(struct sockaddr_nl),
              .msg_iov     = iov,
              .msg_iovlen  = iovlen,
    };
    char buf[CMSG_SPACE(sizeof(struct ucred))];

    /* Overwrite destination if specified in the message itself, defaults
     * to the peer address of the socket.
     */
    dst = nlmsg_get_dst(msg);
    if (dst->nl_family == AF_NETLINK)
        hdr.msg_name = dst;

    /* Add credentials if present. */
    creds = nlmsg_get_creds(msg);
    if (creds != NULL) {
        struct cmsghdr *cmsg;

        hdr.msg_control    = buf;
        hdr.msg_controllen = sizeof(buf);

        cmsg             = CMSG_FIRSTHDR(&hdr);
        cmsg->cmsg_level = SOL_SOCKET;
        cmsg->cmsg_type  = SCM_CREDENTIALS;
        cmsg->cmsg_len   = CMSG_LEN(sizeof(struct ucred));
        memcpy(CMSG_DATA(cmsg), creds, sizeof(struct ucred));
    }

    return nl_sendmsg(sk, msg, &hdr);
}

void
nl_complete_msg(struct nl_sock *sk, struct nl_msg *msg)
{
    struct nlmsghdr *nlh;

    nlh = nlmsg_hdr(msg);
    if (nlh->nlmsg_pid == NL_AUTO_PORT)
        nlh->nlmsg_pid = nl_socket_get_local_port(sk);

    if (nlh->nlmsg_seq == NL_AUTO_SEQ)
        nlh->nlmsg_seq = sk->s_seq_next++;

    if (msg->nm_protocol == -1)
        msg->nm_protocol = sk->s_proto;

    nlh->nlmsg_flags |= NLM_F_REQUEST;

    if (!(sk->s_flags & NL_NO_AUTO_ACK))
        nlh->nlmsg_flags |= NLM_F_ACK;
}

int
nl_send(struct nl_sock *sk, struct nl_msg *msg)
{
    struct iovec iov = {
        .iov_base = (void *) nlmsg_hdr(msg),
        .iov_len  = nlmsg_hdr(msg)->nlmsg_len,
    };

    return nl_send_iovec(sk, msg, &iov, 1);
}

int
nl_send_auto(struct nl_sock *sk, struct nl_msg *msg)
{
    nl_complete_msg(sk, msg);

    return nl_send(sk, msg);
}

/**
 * nl_recv():
 * @sk: the netlink socket
 * @buf0: NULL or a receive buffer of length @buf0_len
 * @buf0_len: the length of the optional receive buffer.
 * @nla: (out): the source address on success.
 * @buf: (out): pointer to the result buffer on success. This is
 *   either @buf0 or an allocated buffer that gets returned.
 * @out_creds: (out) (allow-none): optional out buffer for the credentials
 *   on success.
 * @out_creds_has: (out) (allow-none): result indicating whether
 *   @out_creds was filled.
 *
 * If @buf0_len is zero, the function will g_malloc() a new receive buffer of size
 * nl_socket_get_msg_buf_size(). If @buf0_len is larger than zero, then @buf0
 * is used as receive buffer. That is also the buffer returned by @buf.
 *
 * If NL_MSG_PEEK is not enabled and the receive buffer is too small, then
 * the message was lost and -NME_NL_MSG_TRUNC gets returned.
 * If NL_MSG_PEEK is enabled, then we first peek. If the buffer is too small,
 * we g_malloc() a new buffer. In any case, we proceed to receive the buffer.
 * NL_MSG_PEEK is great because it means no messages are lost. But it's bad,
 * because we always need two syscalls on every receive.
 *
 * Returns: a negative error code or the length of the received message in
 *   @buf.
 */
int
nl_recv(struct nl_sock     *sk,
        unsigned char      *buf0,
        size_t              buf0_len,
        struct sockaddr_nl *nla,
        unsigned char     **buf,
        struct ucred       *out_creds,
        gboolean           *out_creds_has)
{
    /* We really expect msg_contol_buf to be large enough and MSG_CTRUNC not
     * happening. We nm_assert() against that. However, in release builds
     * we don't assert, so add some extra safety space for the unexpected
     * case where we might need more than CMSG_SPACE(sizeof(struct ucred)).
     * It should not hurt and should not be necessary. It's just some
     * extra defensive space. */
#define _MSG_CONTROL_BUF_EXTRA_SPACE (NM_MORE_ASSERTS ? 512u : 0u)
    union {
        struct cmsghdr cmsghdr;
        char           buf[CMSG_SPACE(sizeof(struct ucred)) + _MSG_CONTROL_BUF_EXTRA_SPACE];
    } msg_contol_buf;
    ssize_t       n;
    int           flags = 0;
    struct iovec  iov;
    struct msghdr msg = {
        .msg_name       = (void *) nla,
        .msg_namelen    = sizeof(struct sockaddr_nl),
        .msg_iov        = &iov,
        .msg_iovlen     = 1,
        .msg_controllen = 0,
        .msg_control    = NULL,
    };
    struct ucred tmpcreds;
    gboolean     tmpcreds_has = FALSE;
    int          retval;
    int          errsv;

    nm_assert(nla);
    nm_assert(buf && !*buf);
    nm_assert(!out_creds_has == !out_creds);

    if ((sk->s_flags & NL_MSG_PEEK)
        || (!(sk->s_flags & NL_MSG_PEEK_EXPLICIT) && sk->s_bufsize == 0))
        flags |= MSG_PEEK | MSG_TRUNC;

    if (buf0_len > 0) {
        iov.iov_len  = buf0_len;
        iov.iov_base = buf0;
    } else {
        iov.iov_len  = sk->s_bufsize ?: (((size_t) nm_utils_getpagesize()) * 4u);
        iov.iov_base = g_malloc(iov.iov_len);
    }

    if (out_creds && (sk->s_flags & NL_SOCK_PASSCRED)) {
        msg.msg_controllen = sizeof(msg_contol_buf);
        msg.msg_control    = msg_contol_buf.buf;
    }

retry:
    n = recvmsg(sk->s_fd, &msg, flags);
    if (!n) {
        retval = 0;
        goto abort;
    }

    if (n < 0) {
        errsv = errno;
        if (errsv == EINTR)
            goto retry;
        retval = -nm_errno_from_native(errsv);
        goto abort;
    }

    /* We really don't expect truncation of ancillary data. We provided a large
    * enough buffer, so this is likely a bug. In the worst case, we might lack
    * the requested credentials and the caller likely will reject the message
    * later. */
    nm_assert(!(msg.msg_flags & MSG_CTRUNC));

    if (iov.iov_len < n || (msg.msg_flags & MSG_TRUNC)) {
        /* respond with error to an incomplete message */
        if (flags == 0) {
            retval = -NME_NL_MSG_TRUNC;
            goto abort;
        }

        /* Provided buffer is not long enough, enlarge it
         * to size of n (which should be total length of the message)
         * and try again. */
        iov.iov_base = g_realloc(iov.iov_base != buf0 ? iov.iov_base : NULL, n);
        iov.iov_len  = n;
        flags        = 0;
        goto retry;
    }

    if (flags != 0) {
        /* Buffer is big enough, do the actual reading */
        flags = 0;
        goto retry;
    }

    if (msg.msg_namelen != sizeof(struct sockaddr_nl)) {
        retval = -NME_UNSPEC;
        goto abort;
    }

    if (out_creds && (sk->s_flags & NL_SOCK_PASSCRED)) {
        struct cmsghdr *cmsg;

        for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
            if (cmsg->cmsg_level != SOL_SOCKET)
                continue;
            if (cmsg->cmsg_type != SCM_CREDENTIALS)
                continue;
            memcpy(&tmpcreds, CMSG_DATA(cmsg), sizeof(tmpcreds));
            tmpcreds_has = TRUE;
            break;
        }
    }

    retval = n;

abort:
    if (retval <= 0) {
        if (iov.iov_base != buf0)
            g_free(iov.iov_base);
        return retval;
    }

    *buf = iov.iov_base;
    if (out_creds && tmpcreds_has)
        *out_creds = tmpcreds;
    NM_SET_OUT(out_creds_has, tmpcreds_has);
    return retval;
}