liyujie
2025-08-28 b3810562527858a3b3d98ffa6e9c9c5b0f4a9a8e
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
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
#include "ClatUtils.h"
 
#include <arpa/inet.h>
#include <errno.h>
#include <linux/if.h>
#include <linux/netlink.h>
#include <linux/pkt_cls.h>
#include <linux/pkt_sched.h>
#include <linux/rtnetlink.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
 
#define LOG_TAG "ClatUtils"
#include <log/log.h>
 
#include "NetlinkCommands.h"
#include "android-base/unique_fd.h"
#include "bpf/BpfUtils.h"
#include "netdbpf/bpf_shared.h"
 
namespace android {
namespace net {
 
int hardwareAddressType(const std::string& interface) {
    base::unique_fd ufd(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
 
    if (ufd < 0) {
        const int err = errno;
        ALOGE("socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0)");
        return -err;
    };
 
    struct ifreq ifr = {};
    // We use strncpy() instead of strlcpy() since kernel has to be able
    // to handle non-zero terminated junk passed in by userspace anyway,
    // and this way too long interface names (more than IFNAMSIZ-1 = 15
    // characters plus terminating NULL) will not get truncated to 15
    // characters and zero-terminated and thus potentially erroneously
    // match a truncated interface if one were to exist.
    strncpy(ifr.ifr_name, interface.c_str(), sizeof(ifr.ifr_name));
 
    if (ioctl(ufd, SIOCGIFHWADDR, &ifr, sizeof(ifr))) return -errno;
 
    return ifr.ifr_hwaddr.sa_family;
}
 
int getClatIngressMapFd(void) {
    const int fd = bpf::bpfFdGet(CLAT_INGRESS_MAP_PATH, 0);
    return (fd == -1) ? -errno : fd;
}
 
int getClatIngressProgFd(bool with_ethernet_header) {
    const int fd = bpf::bpfFdGet(
            with_ethernet_header ? CLAT_INGRESS_PROG_ETHER_PATH : CLAT_INGRESS_PROG_RAWIP_PATH, 0);
    return (fd == -1) ? -errno : fd;
}
 
// TODO: use //system/netd/server/NetlinkCommands.cpp:openNetlinkSocket(protocol)
int openNetlinkSocket(void) {
    base::unique_fd fd(socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE));
    if (fd == -1) {
        const int err = errno;
        ALOGE("socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE)");
        return -err;
    }
 
    int rv;
 
    const int on = 1;
    rv = setsockopt(fd, SOL_NETLINK, NETLINK_CAP_ACK, &on, sizeof(on));
    if (rv) ALOGE("setsockopt(fd, SOL_NETLINK, NETLINK_CAP_ACK, %d)", on);
 
    // this is needed to get sane strace netlink parsing, it allocates the pid
    rv = bind(fd, (const struct sockaddr*)&KERNEL_NLADDR, sizeof(KERNEL_NLADDR));
    if (rv) {
        const int err = errno;
        ALOGE("bind(fd, {AF_NETLINK, 0, 0})");
        return -err;
    }
 
    // we do not want to receive messages from anyone besides the kernel
    rv = connect(fd, (const struct sockaddr*)&KERNEL_NLADDR, sizeof(KERNEL_NLADDR));
    if (rv) {
        const int err = errno;
        ALOGE("connect(fd, {AF_NETLINK, 0, 0})");
        return -err;
    }
 
    return fd.release();
}
 
// TODO: merge with //system/netd/server/SockDiag.cpp:checkError(fd)
int processNetlinkResponse(int fd) {
    struct {
        nlmsghdr h;
        nlmsgerr e;
        char buf[256];
    } resp = {};
 
    const int rv = recv(fd, &resp, sizeof(resp), MSG_TRUNC);
 
    if (rv == -1) {
        const int err = errno;
        ALOGE("recv() failed");
        return -err;
    }
 
    if (rv < (int)NLMSG_SPACE(sizeof(struct nlmsgerr))) {
        ALOGE("recv() returned short packet: %d", rv);
        return -EMSGSIZE;
    }
 
    if (resp.h.nlmsg_len != (unsigned)rv) {
        ALOGE("recv() returned invalid header length: %d != %d", resp.h.nlmsg_len, rv);
        return -EBADMSG;
    }
 
    if (resp.h.nlmsg_type != NLMSG_ERROR) {
        ALOGE("recv() did not return NLMSG_ERROR message: %d", resp.h.nlmsg_type);
        return -EBADMSG;
    }
 
    return resp.e.error;  // returns 0 on success
}
 
// ADD:     nlMsgType=RTM_NEWQDISC nlMsgFlags=NLM_F_EXCL|NLM_F_CREATE
// REPLACE: nlMsgType=RTM_NEWQDISC nlMsgFlags=NLM_F_CREATE|NLM_F_REPLACE
// DEL:     nlMsgType=RTM_DELQDISC nlMsgFlags=0
int doTcQdiscClsact(int fd, int ifIndex, __u16 nlMsgType, __u16 nlMsgFlags) {
    // This is the name of the qdisc we are attaching.
    // Some hoop jumping to make this compile time constant with known size,
    // so that the structure declaration is well defined at compile time.
#define CLSACT "clsact"
    static const char clsact[] = CLSACT;
    // sizeof() includes the terminating NULL
#define ASCIIZ_LEN_CLSACT sizeof(clsact)
 
    const struct {
        nlmsghdr n;
        tcmsg t;
        struct {
            nlattr attr;
            char str[NLMSG_ALIGN(ASCIIZ_LEN_CLSACT)];
        } kind;
    } req = {
            .n =
                    {
                            .nlmsg_len = sizeof(req),
                            .nlmsg_type = nlMsgType,
                            .nlmsg_flags = static_cast<__u16>(NETLINK_REQUEST_FLAGS | nlMsgFlags),
                    },
            .t =
                    {
                            .tcm_family = AF_UNSPEC,
                            .tcm_ifindex = ifIndex,
                            .tcm_handle = TC_H_MAKE(TC_H_CLSACT, 0),
                            .tcm_parent = TC_H_CLSACT,
                    },
            .kind =
                    {
                            .attr =
                                    {
                                            .nla_len = NLA_HDRLEN + ASCIIZ_LEN_CLSACT,
                                            .nla_type = TCA_KIND,
                                    },
                            .str = CLSACT,
                    },
    };
#undef ASCIIZ_LEN_CLSACT
#undef CLSACT
 
    const int rv = send(fd, &req, sizeof(req), 0);
    if (rv == -1) return -errno;
    if (rv != sizeof(req)) return -EMSGSIZE;
 
    return processNetlinkResponse(fd);
}
 
int tcQdiscAddDevClsact(int fd, int ifIndex) {
    return doTcQdiscClsact(fd, ifIndex, RTM_NEWQDISC, NLM_F_EXCL | NLM_F_CREATE);
}
 
int tcQdiscReplaceDevClsact(int fd, int ifIndex) {
    return doTcQdiscClsact(fd, ifIndex, RTM_NEWQDISC, NLM_F_CREATE | NLM_F_REPLACE);
}
 
int tcQdiscDelDevClsact(int fd, int ifIndex) {
    return doTcQdiscClsact(fd, ifIndex, RTM_DELQDISC, 0);
}
 
// tc filter add dev .. ingress prio 1 protocol ipv6 bpf object-pinned /sys/fs/bpf/... direct-action
int tcFilterAddDevBpf(int fd, int ifIndex, int bpfFd, bool ethernet) {
    // The priority doesn't matter until we actually start attaching multiple
    // things to the same interface's ingress point.
    const int prio = 1;
 
    // This is the name of the filter we're attaching (ie. this is the 'bpf'
    // packet classifier enabled by kernel config option CONFIG_NET_CLS_BPF.
    //
    // We go through some hoops in order to make this compile time constants
    // so that we can define the struct further down the function with the
    // field for this sized correctly already during the build.
#define BPF "bpf"
    const char bpf[] = BPF;
    // sizeof() includes the terminating NULL
#define ASCIIZ_LEN_BPF sizeof(bpf)
 
    // This is to replicate program name suffix used by 'tc' Linux cli
    // when it attaches programs.
#define FSOBJ_SUFFIX ":[*fsobj]"
 
    // This macro expands (from header files) to:
    //   prog_clatd_schedcls_ingress_clat_rawip:[*fsobj]
    // and is the name of the pinned ebpf program for ARPHRD_RAWIP interfaces.
    // (also compatible with anything that has 0 size L2 header)
#define NAME_RAWIP CLAT_INGRESS_PROG_RAWIP_NAME FSOBJ_SUFFIX
    const char name_rawip[] = NAME_RAWIP;
 
    // This macro expands (from header files) to:
    //   prog_clatd_schedcls_ingress_clat_ether:[*fsobj]
    // and is the name of the pinned ebpf program for ARPHRD_ETHER interfaces.
    // (also compatible with anything that has standard ethernet header)
#define NAME_ETHER CLAT_INGRESS_PROG_ETHER_NAME FSOBJ_SUFFIX
    const char name_ether[] = NAME_ETHER;
 
    // The actual name we'll use is determined at run time via 'ethernet'
    // boolean.  We need to compile time allocate enough space in the struct
    // hence this macro magic to make sure we have enough space for either
    // possibility.  In practice both are actually the same size.
#define ASCIIZ_MAXLEN_NAME \
    ((sizeof(name_rawip) > sizeof(name_ether)) ? sizeof(name_rawip) : sizeof(name_ether))
 
    // This is not a compile time constant and is used in strcpy below
#define NAME (ethernet ? NAME_ETHER : NAME_RAWIP)
 
    struct {
        nlmsghdr n;
        tcmsg t;
        struct {
            nlattr attr;
            char str[NLMSG_ALIGN(ASCIIZ_LEN_BPF)];
        } kind;
        struct {
            nlattr attr;
            struct {
                nlattr attr;
                __u32 u32;
            } fd;
            struct {
                nlattr attr;
                char str[NLMSG_ALIGN(ASCIIZ_MAXLEN_NAME)];
            } name;
            struct {
                nlattr attr;
                __u32 u32;
            } flags;
        } options;
    } req = {
            .n =
                    {
                            .nlmsg_len = sizeof(req),
                            .nlmsg_type = RTM_NEWTFILTER,
                            .nlmsg_flags = NETLINK_REQUEST_FLAGS | NLM_F_EXCL | NLM_F_CREATE,
                    },
            .t =
                    {
                            .tcm_family = AF_UNSPEC,
                            .tcm_ifindex = ifIndex,
                            .tcm_handle = TC_H_UNSPEC,
                            .tcm_parent = TC_H_MAKE(TC_H_CLSACT, TC_H_MIN_INGRESS),
                            .tcm_info = (prio << 16) | htons(ETH_P_IPV6),
                    },
            .kind =
                    {
                            .attr =
                                    {
                                            .nla_len = sizeof(req.kind),
                                            .nla_type = TCA_KIND,
                                    },
                            .str = BPF,
                    },
            .options =
                    {
                            .attr =
                                    {
                                            .nla_len = sizeof(req.options),
                                            .nla_type = TCA_OPTIONS,
                                    },
                            .fd =
                                    {
                                            .attr =
                                                    {
                                                            .nla_len = sizeof(req.options.fd),
                                                            .nla_type = TCA_BPF_FD,
                                                    },
                                            .u32 = static_cast<__u32>(bpfFd),
                                    },
                            .name =
                                    {
                                            .attr =
                                                    {
                                                            .nla_len = sizeof(req.options.name),
                                                            .nla_type = TCA_BPF_NAME,
                                                    },
                                            // Visible via 'tc filter show', but
                                            // is overwritten by strcpy below
                                            .str = "placeholder",
                                    },
                            .flags =
                                    {
                                            .attr =
                                                    {
                                                            .nla_len = sizeof(req.options.flags),
                                                            .nla_type = TCA_BPF_FLAGS,
                                                    },
                                            .u32 = TCA_BPF_FLAG_ACT_DIRECT,
                                    },
                    },
    };
 
    strncpy(req.options.name.str, NAME, sizeof(req.options.name.str));
 
#undef NAME
#undef ASCIIZ_MAXLEN_NAME
#undef NAME_ETHER
#undef NAME_RAWIP
#undef NAME
#undef ASCIIZ_LEN_BPF
#undef BPF
 
    const int rv = send(fd, &req, sizeof(req), 0);
    if (rv == -1) return -errno;
    if (rv != sizeof(req)) return -EMSGSIZE;
 
    return processNetlinkResponse(fd);
}
 
}  // namespace net
}  // namespace android