1 /*
2 * Copyright (c) 2021-2024 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/netlink_manager.h"
17
18 #include <sys/socket.h>
19 #include <linux/netlink.h>
20
21 #include "securec.h"
22 #include "storage_service_errno.h"
23 #include "storage_service_log.h"
24
25 namespace OHOS {
26 namespace StorageDaemon {
27 NetlinkManager* NetlinkManager::instance_ = nullptr;
28
Instance()29 NetlinkManager* NetlinkManager::Instance()
30 {
31 if (instance_ == nullptr) {
32 instance_ = new NetlinkManager();
33 }
34
35 return instance_;
36 }
37
Start()38 int32_t NetlinkManager::Start()
39 {
40 struct sockaddr_nl addr;
41 int32_t bufferSize = 256 * ONE_KB;
42 int32_t passCred = 1;
43
44 (void)memset_s(&addr, sizeof(addr), 0, sizeof(addr));
45 addr.nl_family = AF_NETLINK;
46 addr.nl_pid = static_cast<uint32_t>(getprocpid());
47 addr.nl_groups = 0xffffffff;
48
49 socketFd_ = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT);
50 if (socketFd_ < 0) {
51 LOGE("Create netlink socket failed, errno %{public}d", errno);
52 return E_ERR;
53 }
54
55 if (setsockopt(socketFd_, SOL_SOCKET, SO_RCVBUFFORCE, &bufferSize, sizeof(bufferSize)) != 0) {
56 LOGE("Set SO_RCVBUFFORCE failed, errno %{public}d", errno);
57 (void)close(socketFd_);
58 return E_ERR;
59 }
60
61 if (setsockopt(socketFd_, SOL_SOCKET, SO_PASSCRED, &passCred, sizeof(passCred)) != 0) {
62 LOGE("Set SO_PASSCRED failed, errno %{public}d", errno);
63 (void)close(socketFd_);
64 return E_ERR;
65 }
66
67 if (bind(socketFd_, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)) != 0) {
68 LOGE("Socket bind failed, errno %{public}d", errno);
69 (void)close(socketFd_);
70 return E_ERR;
71 }
72
73 nlHandler_ = new NetlinkHandler(socketFd_);
74 if (nlHandler_->Start()) {
75 (void)close(socketFd_);
76 return E_ERR;
77 }
78 return E_OK;
79 }
80
Stop()81 int32_t NetlinkManager::Stop()
82 {
83 int32_t ret = 0;
84 if (nlHandler_ != nullptr) {
85 if (nlHandler_->Stop()) {
86 ret = E_ERR;
87 }
88 delete nlHandler_;
89 }
90 nlHandler_ = nullptr;
91 (void)close(socketFd_);
92 socketFd_ = -1;
93
94 return ret;
95 }
96 } // StorageDaemon
97 } // OHOS
98