1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <OffloadControlTestUtils.h>
18 #include <android-base/unique_fd.h>
19 
20 using android::base::unique_fd;
21 
asSockaddr(const sockaddr_nl * nladdr)22 inline const sockaddr* asSockaddr(const sockaddr_nl* nladdr) {
23     return reinterpret_cast<const sockaddr*>(nladdr);
24 }
25 
conntrackSocket(unsigned groups)26 int conntrackSocket(unsigned groups) {
27     unique_fd s(socket(AF_NETLINK, SOCK_DGRAM, NETLINK_NETFILTER));
28     if (s.get() < 0) {
29         return -errno;
30     }
31 
32     const struct sockaddr_nl bind_addr = {
33             .nl_family = AF_NETLINK,
34             .nl_pad = 0,
35             .nl_pid = 0,
36             .nl_groups = groups,
37     };
38     if (::bind(s.get(), asSockaddr(&bind_addr), sizeof(bind_addr)) < 0) {
39         return -errno;
40     }
41 
42     const struct sockaddr_nl kernel_addr = {
43             .nl_family = AF_NETLINK,
44             .nl_pad = 0,
45             .nl_pid = 0,
46             .nl_groups = groups,
47     };
48     if (connect(s.get(), asSockaddr(&kernel_addr), sizeof(kernel_addr)) != 0) {
49         return -errno;
50     }
51 
52     return s.release();
53 }