1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef INCLUDE_NETLINK_SOCK_DIAG_H 17 #define INCLUDE_NETLINK_SOCK_DIAG_H 18 19 #include <linux/netlink.h> 20 #include <linux/sock_diag.h> 21 #include <linux/inet_diag.h> 22 #include <netinet/in.h> 23 #include <sys/socket.h> 24 #include <string> 25 #include <unistd.h> 26 27 namespace OHOS { 28 namespace nmd { 29 class NetLinkSocketDiag final { 30 public: 31 NetLinkSocketDiag() = default; 32 ~NetLinkSocketDiag(); 33 34 /** 35 * Destroy all 'active' TCP sockets that no longer exist. 36 * 37 * @param ipAddr Network IP address 38 * @param excludeLoopback “true” to exclude loopback. 39 */ 40 void DestroyLiveSockets(const char *ipAddr, bool excludeLoopback); 41 42 private: 43 static bool InLookBack(uint32_t a); 44 45 bool CreateNetlinkSocket(); 46 void CloseNetlinkSocket(); 47 int32_t ExecuteDestroySocket(uint8_t proto, const inet_diag_msg *msg); 48 int32_t GetErrorFromKernel(int32_t fd); 49 bool IsLoopbackSocket(const inet_diag_msg *msg); 50 bool IsMatchNetwork(const inet_diag_msg *msg, const std::string &ipAddr); 51 int32_t ProcessSockDiagDumpResponse(uint8_t proto, const std::string &ipAddr, bool excludeLoopback); 52 int32_t SendSockDiagDumpRequest(uint8_t proto, uint8_t family, uint32_t states); 53 void SockDiagDumpCallback(uint8_t proto, const inet_diag_msg *msg, const std::string &ipAddr, bool excludeLoopback); 54 55 private: 56 struct SockDiagRequest { 57 nlmsghdr nlh_; 58 inet_diag_req_v2 req_; 59 }; 60 struct MarkMatch { 61 inet_diag_bc_op op_; 62 uint32_t mark_; 63 uint32_t mask_; 64 }; 65 struct ByteCode { 66 MarkMatch netIdMatch_; 67 MarkMatch controlMatch_; 68 inet_diag_bc_op controlJump_; 69 }; 70 struct Ack { 71 nlmsghdr hdr_; 72 nlmsgerr err_; 73 }; 74 75 int32_t dumpSock_ = -1; 76 int32_t destroySock_ = -1; 77 int32_t socketsDestroyed_ = 0; 78 }; 79 } // namespace nmd 80 } // namespace OHOS 81 #endif // INCLUDE_NETLINK_SOCK_DIAG_H