1 /* 2 * Copyright (C) 2021 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 #pragma once 18 19 #include <libnl++/Socket.h> 20 21 #include <mutex> 22 #include <thread> 23 24 namespace android::nlinterceptor { 25 26 class InterceptorRelay { 27 public: 28 /** 29 * Wrapper around the netlink socket and thread which relays messages. 30 * 31 * \param nlFamily - netlink family to use for the netlink socket. 32 * \param clientNlPid - pid of the client netlink socket. 33 * \param clientName - name of the client to be used for debugging. 34 */ 35 InterceptorRelay(uint32_t nlFamily, uint32_t clientNlPid, 36 const std::string& clientName); 37 38 /** 39 * Stops the relay thread if running and destroys itself. 40 */ 41 ~InterceptorRelay(); 42 43 /** 44 * Returns the PID of the internal Netlink socket. 45 * 46 * \return value of PID, 47 */ 48 uint32_t getPid(); 49 50 /** 51 * Spawns relay thread. 52 */ 53 bool start(); 54 55 /** 56 * Subscribes the internal socket to a single Netlink multicast group. 57 * 58 * \param nlGroup - Netlink group to subscribe to. 59 * \returns - true for success, false for failure. 60 */ 61 bool subscribeGroup(uint32_t nlGroup); 62 63 /** 64 * Unsubscribes the internal socket from a single Netlink multicast group. 65 * 66 * \param nlGroup - Netlink group to unsubscribe from. 67 * \returns - true for success, false for failure. 68 */ 69 bool unsubscribeGroup(uint32_t nlGroup); 70 71 private: 72 std::string mClientName; ///< Name of client (Wificond, for example). 73 std::optional<nl::Socket> mNlSocket; 74 const uint32_t mClientNlPid = 0; ///< pid of client NL socket. 75 76 /** 77 * If set to true, the relay thread should be running. Setting this to false 78 * stops the relay thread. 79 */ 80 std::atomic_bool mRunning = false; 81 82 /** 83 * Reads incoming Netlink messages destined for mNlSocket. If from the 84 * kernel, the message is relayed to the client specified in the 85 * constructor. Otherwise, the message is relayed to the kernel. This will 86 * run as long as mRunning is set to true. 87 */ 88 void relayMessages(); 89 90 std::thread mRelayThread; 91 }; 92 93 } // namespace android::nlinterceptor 94