1 /*
2 * Copyright (c) 2021-2022 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 "uds_server.h"
17
18 #include <cinttypes>
19 #include <list>
20
21 #include <sys/socket.h>
22
23 #include "dfx_hisysevent.h"
24 #include "i_multimodal_input_connect.h"
25 #include "mmi_log.h"
26 #include "util.h"
27 #include "util_ex.h"
28
29 namespace OHOS {
30 namespace MMI {
31 namespace {
32 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, MMI_LOG_DOMAIN, "UDSServer"};
33 } // namespace
UDSServer()34 UDSServer::UDSServer() {}
35
~UDSServer()36 UDSServer::~UDSServer()
37 {
38 CALL_DEBUG_ENTER;
39 UdsStop();
40 }
41
UdsStop()42 void UDSServer::UdsStop()
43 {
44 if (epollFd_ != -1) {
45 close(epollFd_);
46 epollFd_ = -1;
47 }
48
49 for (const auto &item : sessionsMap_) {
50 item.second->Close();
51 }
52 sessionsMap_.clear();
53 }
54
GetClientFd(int32_t pid) const55 int32_t UDSServer::GetClientFd(int32_t pid) const
56 {
57 auto it = idxPidMap_.find(pid);
58 if (it == idxPidMap_.end()) {
59 return INVALID_FD;
60 }
61 return it->second;
62 }
63
GetClientPid(int32_t fd) const64 int32_t UDSServer::GetClientPid(int32_t fd) const
65 {
66 auto it = sessionsMap_.find(fd);
67 if (it == sessionsMap_.end()) {
68 return INVALID_PID;
69 }
70 return it->second->GetPid();
71 }
72
SendMsg(int32_t fd,NetPacket & pkt)73 bool UDSServer::SendMsg(int32_t fd, NetPacket& pkt)
74 {
75 if (fd < 0) {
76 MMI_HILOGE("The fd is less than 0");
77 return false;
78 }
79 auto ses = GetSession(fd);
80 if (ses == nullptr) {
81 MMI_HILOGE("The fd:%{public}d not found, The message was discarded. errCode:%{public}d",
82 fd, SESSION_NOT_FOUND);
83 return false;
84 }
85 return ses->SendMsg(pkt);
86 }
87
Multicast(const std::vector<int32_t> & fdList,NetPacket & pkt)88 void UDSServer::Multicast(const std::vector<int32_t>& fdList, NetPacket& pkt)
89 {
90 for (const auto &item : fdList) {
91 SendMsg(item, pkt);
92 }
93 }
94
AddSocketPairInfo(const std::string & programName,const int32_t moduleType,const int32_t uid,const int32_t pid,int32_t & serverFd,int32_t & toReturnClientFd,int32_t & tokenType)95 int32_t UDSServer::AddSocketPairInfo(const std::string& programName,
96 const int32_t moduleType, const int32_t uid, const int32_t pid,
97 int32_t& serverFd, int32_t& toReturnClientFd, int32_t& tokenType)
98 {
99 CALL_DEBUG_ENTER;
100 int32_t sockFds[2] = {};
101
102 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockFds) != 0) {
103 MMI_HILOGE("Call socketpair failed, errno:%{public}d", errno);
104 return RET_ERR;
105 }
106
107 serverFd = sockFds[0];
108 toReturnClientFd = sockFds[1];
109 if (toReturnClientFd < 0) {
110 MMI_HILOGE("Call fcntl failed, errno:%{public}d", errno);
111 return RET_ERR;
112 }
113
114 static constexpr size_t bufferSize = 32 * 1024;
115 setsockopt(sockFds[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
116 setsockopt(sockFds[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
117 if (tokenType == TokenType::TOKEN_NATIVE) {
118 static constexpr size_t nativeBufferSize = 64 * 1024;
119 setsockopt(sockFds[1], SOL_SOCKET, SO_SNDBUF, &nativeBufferSize, sizeof(nativeBufferSize));
120 setsockopt(sockFds[1], SOL_SOCKET, SO_RCVBUF, &nativeBufferSize, sizeof(nativeBufferSize));
121 } else {
122 setsockopt(sockFds[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
123 setsockopt(sockFds[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
124 }
125 MMI_HILOGD("Alloc socketpair, serverFd:%{public}d,clientFd:%{public}d(%{public}d)",
126 serverFd, toReturnClientFd, sockFds[1]);
127 auto closeSocketFdWhenError = [&serverFd, &toReturnClientFd] {
128 close(serverFd);
129 close(toReturnClientFd);
130 serverFd = IMultimodalInputConnect::INVALID_SOCKET_FD;
131 toReturnClientFd = IMultimodalInputConnect::INVALID_SOCKET_FD;
132 };
133
134 std::list<std::function<void()> > cleanTaskList;
135 auto cleanTaskWhenError = [cleanTaskList] {
136 for (const auto &item : cleanTaskList) {
137 item();
138 }
139 };
140
141 cleanTaskList.push_back(closeSocketFdWhenError);
142
143 int32_t ret = RET_OK;
144 ret = AddEpoll(EPOLL_EVENT_SOCKET, serverFd);
145 if (ret != RET_OK) {
146 cleanTaskWhenError();
147 MMI_HILOGE("epoll_ctl EPOLL_CTL_ADD return %{public}d,errCode:%{public}d", ret, EPOLL_MODIFY_FAIL);
148 return ret;
149 }
150
151 SessionPtr sess = std::make_shared<UDSSession>(programName, moduleType, serverFd, uid, pid);
152 if (sess == nullptr) {
153 cleanTaskWhenError();
154 MMI_HILOGE("make_shared fail. progName:%{public}s,pid:%{public}d,errCode:%{public}d",
155 programName.c_str(), pid, MAKE_SHARED_FAIL);
156 return RET_ERR;
157 }
158 sess->SetTokenType(tokenType);
159
160 if (!AddSession(sess)) {
161 cleanTaskWhenError();
162 MMI_HILOGE("AddSession fail errCode:%{public}d", ADD_SESSION_FAIL);
163 return RET_ERR;
164 }
165 OnConnected(sess);
166 return RET_OK;
167 }
168
Dump(int32_t fd,const std::vector<std::string> & args)169 void UDSServer::Dump(int32_t fd, const std::vector<std::string> &args)
170 {
171 CALL_DEBUG_ENTER;
172 mprintf(fd, "Uds_server information:\t");
173 mprintf(fd, "uds_server: count=%d", sessionsMap_.size());
174 for (const auto &item : sessionsMap_) {
175 std::shared_ptr<UDSSession> udsSession = item.second;
176 CHKPV(udsSession);
177 mprintf(fd,
178 "Uid:%d | Pid:%d | Fd:%d | TokenType:%d | Descript:%s\t",
179 udsSession->GetUid(), udsSession->GetPid(), udsSession->GetFd(),
180 udsSession->GetTokenType(), udsSession->GetDescript().c_str());
181 }
182 }
183
OnConnected(SessionPtr sess)184 void UDSServer::OnConnected(SessionPtr sess)
185 {
186 CHKPV(sess);
187 MMI_HILOGI("Session desc:%{public}s", sess->GetDescript().c_str());
188 }
189
OnDisconnected(SessionPtr sess)190 void UDSServer::OnDisconnected(SessionPtr sess)
191 {
192 CHKPV(sess);
193 MMI_HILOGI("Session desc:%{public}s", sess->GetDescript().c_str());
194 }
195
AddEpoll(EpollEventType type,int32_t fd)196 int32_t UDSServer::AddEpoll(EpollEventType type, int32_t fd)
197 {
198 MMI_HILOGE("This information should not exist. Subclasses should implement this function.");
199 return RET_ERR;
200 }
201
SetRecvFun(MsgServerFunCallback fun)202 void UDSServer::SetRecvFun(MsgServerFunCallback fun)
203 {
204 recvFun_ = fun;
205 }
206
ReleaseSession(int32_t fd,epoll_event & ev)207 void UDSServer::ReleaseSession(int32_t fd, epoll_event& ev)
208 {
209 auto secPtr = GetSession(fd);
210 if (secPtr != nullptr) {
211 OnDisconnected(secPtr);
212 DelSession(fd);
213 } else {
214 DfxHisysevent::OnClientDisconnect(secPtr, fd, OHOS::HiviewDFX::HiSysEvent::EventType::FAULT);
215 }
216 if (ev.data.ptr) {
217 free(ev.data.ptr);
218 ev.data.ptr = nullptr;
219 }
220 if (auto it = circleBufMap_.find(fd); it != circleBufMap_.end()) {
221 circleBufMap_.erase(it);
222 }
223 if (close(fd) == RET_OK) {
224 DfxHisysevent::OnClientDisconnect(secPtr, fd, OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR);
225 } else {
226 DfxHisysevent::OnClientDisconnect(secPtr, fd, OHOS::HiviewDFX::HiSysEvent::EventType::FAULT);
227 }
228 }
229
OnPacket(int32_t fd,NetPacket & pkt)230 void UDSServer::OnPacket(int32_t fd, NetPacket& pkt)
231 {
232 auto sess = GetSession(fd);
233 CHKPV(sess);
234 recvFun_(sess, pkt);
235 }
236
OnEpollRecv(int32_t fd,epoll_event & ev)237 void UDSServer::OnEpollRecv(int32_t fd, epoll_event& ev)
238 {
239 if (fd < 0) {
240 MMI_HILOGE("Invalid input param fd:%{public}d", fd);
241 return;
242 }
243 auto& buf = circleBufMap_[fd];
244 char szBuf[MAX_PACKET_BUF_SIZE] = {};
245 for (int32_t i = 0; i < MAX_RECV_LIMIT; i++) {
246 auto size = recv(fd, szBuf, MAX_PACKET_BUF_SIZE, MSG_DONTWAIT | MSG_NOSIGNAL);
247 if (size > 0) {
248 if (!buf.Write(szBuf, size)) {
249 MMI_HILOGW("Write data failed. size:%{public}zu", size);
250 }
251 OnReadPackets(buf, std::bind(&UDSServer::OnPacket, this, fd, std::placeholders::_1));
252 } else if (size < 0) {
253 if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) {
254 MMI_HILOGD("Continue for errno EAGAIN|EINTR|EWOULDBLOCK size:%{public}zu errno:%{public}d",
255 size, errno);
256 continue;
257 }
258 MMI_HILOGE("Recv return %{public}zu errno:%{public}d", size, errno);
259 break;
260 } else {
261 MMI_HILOGE("The client side disconnect with the server. size:0 errno:%{public}d", errno);
262 ReleaseSession(fd, ev);
263 break;
264 }
265 if (size < MAX_PACKET_BUF_SIZE) {
266 break;
267 }
268 }
269 }
270
OnEpollEvent(epoll_event & ev)271 void UDSServer::OnEpollEvent(epoll_event& ev)
272 {
273 CHKPV(ev.data.ptr);
274 auto fd = *static_cast<int32_t*>(ev.data.ptr);
275 if (fd < 0) {
276 MMI_HILOGE("The fd less than 0, errCode:%{public}d", PARAM_INPUT_INVALID);
277 return;
278 }
279 if ((ev.events & EPOLLERR) || (ev.events & EPOLLHUP)) {
280 MMI_HILOGI("EPOLLERR or EPOLLHUP fd:%{public}d,ev.events:0x%{public}x", fd, ev.events);
281 ReleaseSession(fd, ev);
282 } else if (ev.events & EPOLLIN) {
283 OnEpollRecv(fd, ev);
284 }
285 }
286
DumpSession(const std::string & title)287 void UDSServer::DumpSession(const std::string &title)
288 {
289 MMI_HILOGD("in %s: %s", __func__, title.c_str());
290 int32_t i = 0;
291 for (auto &[key, value] : sessionsMap_) {
292 CHKPV(value);
293 MMI_HILOGD("%d, %s", i, value->GetDescript().c_str());
294 i++;
295 }
296 }
297
GetSession(int32_t fd) const298 SessionPtr UDSServer::GetSession(int32_t fd) const
299 {
300 auto it = sessionsMap_.find(fd);
301 if (it == sessionsMap_.end()) {
302 MMI_HILOGE("Session not found.fd:%{public}d", fd);
303 return nullptr;
304 }
305 CHKPP(it->second);
306 return it->second->GetSharedPtr();
307 }
308
GetSessionByPid(int32_t pid) const309 SessionPtr UDSServer::GetSessionByPid(int32_t pid) const
310 {
311 int32_t fd = GetClientFd(pid);
312 if (fd <= 0) {
313 MMI_HILOGE("Session not found.pid:%{public}d", pid);
314 return nullptr;
315 }
316 return GetSession(fd);
317 }
318
AddSession(SessionPtr ses)319 bool UDSServer::AddSession(SessionPtr ses)
320 {
321 CHKPF(ses);
322 MMI_HILOGI("pid:%{public}d,fd:%{public}d", ses->GetPid(), ses->GetFd());
323 auto fd = ses->GetFd();
324 if (fd < 0) {
325 MMI_HILOGE("The fd is less than 0");
326 return false;
327 }
328 auto pid = ses->GetPid();
329 if (pid <= 0) {
330 MMI_HILOGE("Get process failed");
331 return false;
332 }
333 idxPidMap_[pid] = fd;
334 sessionsMap_[fd] = ses;
335 DumpSession("AddSession");
336 if (sessionsMap_.size() > MAX_SESSON_ALARM) {
337 MMI_HILOGW("Too many clients. Warning Value:%{public}d,Current Value:%{public}zd",
338 MAX_SESSON_ALARM, sessionsMap_.size());
339 }
340 MMI_HILOGI("AddSession end");
341 return true;
342 }
343
DelSession(int32_t fd)344 void UDSServer::DelSession(int32_t fd)
345 {
346 CALL_DEBUG_ENTER;
347 MMI_HILOGI("fd:%{public}d", fd);
348 if (fd < 0) {
349 MMI_HILOGE("The fd less than 0, errCode:%{public}d", PARAM_INPUT_INVALID);
350 return;
351 }
352 auto pid = GetClientPid(fd);
353 if (pid > 0) {
354 idxPidMap_.erase(pid);
355 }
356 auto it = sessionsMap_.find(fd);
357 if (it != sessionsMap_.end()) {
358 NotifySessionDeleted(it->second);
359 sessionsMap_.erase(it);
360 }
361 DumpSession("DelSession");
362 }
363
AddSessionDeletedCallback(std::function<void (SessionPtr)> callback)364 void UDSServer::AddSessionDeletedCallback(std::function<void(SessionPtr)> callback)
365 {
366 CALL_DEBUG_ENTER;
367 callbacks_.push_back(callback);
368 }
369
NotifySessionDeleted(SessionPtr ses)370 void UDSServer::NotifySessionDeleted(SessionPtr ses)
371 {
372 CALL_DEBUG_ENTER;
373 for (const auto &callback : callbacks_) {
374 callback(ses);
375 }
376 }
377 } // namespace MMI
378 } // namespace OHOS
379