1 /*
2 * Copyright (c) 2017 JingPiao Chen <chenjingpiao@gmail.com>
3 * Copyright (c) 2017-2021 The strace developers.
4 * All rights reserved.
5 *
6 * SPDX-License-Identifier: GPL-2.0-or-later
7 */
8
9 #include "tests.h"
10
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdint.h>
14 #include "test_nlattr.h"
15 #include <linux/netlink_diag.h>
16 #include <linux/sock_diag.h>
17
18 static void
19 init_netlink_diag_msg(struct nlmsghdr *const nlh, const unsigned int msg_len)
20 {
21 SET_STRUCT(struct nlmsghdr, nlh,
22 .nlmsg_len = msg_len,
23 .nlmsg_type = SOCK_DIAG_BY_FAMILY,
24 .nlmsg_flags = NLM_F_DUMP
25 );
26
27 struct netlink_diag_msg *const msg = NLMSG_DATA(nlh);
28 SET_STRUCT(struct netlink_diag_msg, msg,
29 .ndiag_family = AF_NETLINK,
30 .ndiag_type = SOCK_RAW,
31 .ndiag_protocol = NETLINK_ROUTE,
32 .ndiag_state = NETLINK_CONNECTED
33 );
34 }
35
36 static void
37 print_netlink_diag_msg(const unsigned int msg_len)
38 {
39 printf("{nlmsg_len=%u, nlmsg_type=SOCK_DIAG_BY_FAMILY"
40 ", nlmsg_flags=NLM_F_DUMP, nlmsg_seq=0, nlmsg_pid=0}"
41 ", {ndiag_family=AF_NETLINK, ndiag_type=SOCK_RAW"
42 ", ndiag_protocol=NETLINK_ROUTE, ndiag_state=NETLINK_CONNECTED"
43 ", ndiag_portid=0, ndiag_dst_portid=0, ndiag_dst_group=0"
44 ", ndiag_ino=0, ndiag_cookie=[0, 0]}",
45 msg_len);
46 }
47
48 static void
49 print_xlong(const unsigned long *p, size_t i)
50 {
51 printf("%#lx", *p);
52 }
53
54 int
55 main(void)
56 {
57 skip_if_unavailable("/proc/self/fd/");
58
59 static const unsigned long groups[] = {
60 (unsigned long) 0xdeadbeefbadc0dedULL,
61 (unsigned long) 0xdeadbeefbadc0dedULL
62 };
63 static const struct netlink_diag_ring ndr = {
64 .ndr_block_size = 0xfabfabdc,
65 .ndr_block_nr = 0xabcdabda,
66 .ndr_frame_size = 0xcbadbafa,
67 .ndr_frame_nr = 0xdbcafadb
68 };
69 static const uint32_t flags =
70 NDIAG_FLAG_CB_RUNNING | NDIAG_FLAG_PKTINFO;
71
72 const int fd = create_nl_socket(NETLINK_SOCK_DIAG);
73 const unsigned int hdrlen = sizeof(struct netlink_diag_msg);
74 void *const nlh0 = midtail_alloc(NLMSG_SPACE(hdrlen),
75 NLA_HDRLEN +
76 MAX(sizeof(groups), sizeof(ndr)));
77
78 static char pattern[4096];
79 fill_memory_ex(pattern, sizeof(pattern), 'a', 'z' - 'a' + 1);
80
81 TEST_NLATTR_ARRAY(fd, nlh0, hdrlen,
82 init_netlink_diag_msg, print_netlink_diag_msg,
83 NETLINK_DIAG_GROUPS, pattern, groups, print_xlong);
84
85 TEST_NLATTR_OBJECT(fd, nlh0, hdrlen,
86 init_netlink_diag_msg, print_netlink_diag_msg,
87 NETLINK_DIAG_RX_RING, pattern, ndr,
88 printf("{");
89 PRINT_FIELD_U(ndr, ndr_block_size);
90 printf(", ");
91 PRINT_FIELD_U(ndr, ndr_block_nr);
92 printf(", ");
93 PRINT_FIELD_U(ndr, ndr_frame_size);
94 printf(", ");
95 PRINT_FIELD_U(ndr, ndr_frame_nr);
96 printf("}"));
97
98 TEST_NLATTR_OBJECT(fd, nlh0, hdrlen,
99 init_netlink_diag_msg, print_netlink_diag_msg,
100 NETLINK_DIAG_FLAGS, pattern, flags,
101 printf("NDIAG_FLAG_CB_RUNNING|NDIAG_FLAG_PKTINFO"));
102
103 puts("+++ exited with 0 +++");
104 return 0;
105 }