• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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 #include "netlink_socket.h"
17 #include <iostream>
18 #include <cstdlib>
19 #include <cstring>
20 #include <unistd.h>
21 #include <arpa/inet.h>
22 #include <asm/types.h>
23 #include <sys/socket.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <linux/netlink.h>
27 #include <linux/rtnetlink.h>
28 #include "securec.h"
29 #include "netnative_log_wrapper.h"
30 
31 namespace OHOS {
32 namespace nmd {
~NetlinkSocket()33 NetlinkSocket::~NetlinkSocket()
34 {
35     close(this->socketFd);
36 }
37 
Create(int protocol)38 int NetlinkSocket::Create(int protocol)
39 {
40     return this->Create(SOCK_RAW, protocol);
41 }
42 
Create(int type,int protocol)43 int NetlinkSocket::Create(int type, int protocol)
44 {
45     this->socketFd = socket(AF_NETLINK, type, protocol);
46     if (this->socketFd == -1) {
47         NETNATIVE_LOGE("[NetlinkSocket] create socket failed: %{public}d", errno);
48         return -1;
49     }
50     return this->socketFd;
51 }
52 
SendNetlinkMsgToKernel(struct nlmsghdr * msg)53 int NetlinkSocket::SendNetlinkMsgToKernel(struct nlmsghdr *msg)
54 {
55     if (msg == nullptr) {
56         NETNATIVE_LOGE("[NetlinkSocket] msg can not be null ");
57         return -1;
58     }
59 
60     struct iovec ioVector;
61     ioVector.iov_base = msg;
62     ioVector.iov_len = msg->nlmsg_len;
63 
64     struct msghdr msgHeader;
65     (void)memset_s(&msgHeader, sizeof(msgHeader), 0, sizeof(msgHeader));
66 
67     struct sockaddr_nl kernel;
68     memset_s(&kernel, sizeof(kernel), 0, sizeof(kernel));
69     kernel.nl_family = AF_NETLINK;
70     kernel.nl_groups = 0;
71 
72     msgHeader.msg_name = &kernel;
73     msgHeader.msg_namelen = sizeof(kernel);
74     msgHeader.msg_iov = &ioVector;
75     msgHeader.msg_iovlen = 1;
76 
77     ssize_t msgState = sendmsg(this->socketFd, &msgHeader, 0);
78     if (msgState == -1) {
79         NETNATIVE_LOGE("[NetlinkSocket] msg can not be null ");
80         return -1;
81     } else if (msgState == 0) {
82         NETNATIVE_LOGE("[NetlinkSocket] 0 bytes send.");
83         return -1;
84     }
85     return msgState;
86 }
87 
Shutdown()88 int NetlinkSocket::Shutdown()
89 {
90     return close(this->socketFd);
91 }
92 } // namespace nmd
93 } // namespace OHOS