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