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 "dbinder_service.h"
17 #include "securec.h"
18 #include "string_ex.h"
19 #include "ipc_skeleton.h"
20 #include "ipc_thread_skeleton.h"
21
22 #include "dbinder_log.h"
23 #include "dbinder_service_stub.h"
24 #include "dbinder_remote_listener.h"
25 #include "dbinder_error_code.h"
26 #include "dbinder_sa_death_recipient.h"
27 #include "rpc_feature_set.h"
28 #include "softbus_bus_center.h"
29
30 namespace OHOS {
31 using namespace Communication;
32
33 static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, LOG_ID_RPC, "DbinderService" };
34
35 sptr<DBinderService> DBinderService::instance_ = nullptr;
36 bool DBinderService::mainThreadCreated_ = false;
37 std::mutex DBinderService::instanceMutex_;
38 std::shared_ptr<DBinderRemoteListener> DBinderService::remoteListener_ = nullptr;
39 constexpr int32_t DBINDER_UID_START_INDEX = 7;
40
DBinderService()41 DBinderService::DBinderService()
42 {
43 DBINDER_LOGI(LOG_LABEL, "create dbinder service");
44 }
45
~DBinderService()46 DBinderService::~DBinderService()
47 {
48 StopRemoteListener();
49
50 DBinderStubRegisted_.clear();
51 mapRemoteBinderObjects_.clear();
52 threadLockInfo_.clear();
53 proxyObject_.clear();
54 sessionObject_.clear();
55 noticeProxy_.clear();
56 deathRecipients_.clear();
57 busNameObject_.clear();
58 loadSaReply_.clear();
59 dbinderCallback_ = nullptr;
60
61 DBINDER_LOGI(LOG_LABEL, "dbinder service died");
62 }
63
GetLocalDeviceID()64 std::string DBinderService::GetLocalDeviceID()
65 {
66 std::string pkgName = "DBinderService";
67 NodeBasicInfo nodeBasicInfo;
68 if (GetLocalNodeDeviceInfo(pkgName.c_str(), &nodeBasicInfo) != 0) {
69 DBINDER_LOGE(LOG_LABEL, "Get local node device info failed");
70 return "";
71 }
72 std::string networkId(nodeBasicInfo.networkId);
73 return networkId;
74 }
75
StartDBinderService(std::shared_ptr<RpcSystemAbilityCallback> & callbackImpl)76 bool DBinderService::StartDBinderService(std::shared_ptr<RpcSystemAbilityCallback> &callbackImpl)
77 {
78 if (mainThreadCreated_) {
79 return ReStartRemoteListener();
80 }
81
82 bool result = StartRemoteListener();
83 if (!result) {
84 return false;
85 }
86 mainThreadCreated_ = true;
87 dbinderCallback_ = callbackImpl;
88
89 return true;
90 }
91
StartRemoteListener()92 bool DBinderService::StartRemoteListener()
93 {
94 if (remoteListener_ != nullptr) {
95 DBINDER_LOGI(LOG_LABEL, "remote listener started");
96 return true;
97 }
98
99 remoteListener_ = std::make_shared<DBinderRemoteListener>(GetInstance());
100 if (remoteListener_ == nullptr) {
101 DBINDER_LOGE(LOG_LABEL, "failed to create remote listener");
102 return false;
103 }
104
105 if (remoteListener_->StartListener(remoteListener_) != true) {
106 StopRemoteListener();
107 return false;
108 }
109
110 DBINDER_LOGI(LOG_LABEL, "start remote listener ok");
111 return true;
112 }
113
ReStartRemoteListener()114 bool DBinderService::ReStartRemoteListener()
115 {
116 if (remoteListener_ == nullptr) {
117 DBINDER_LOGE(LOG_LABEL, "restart remote listener got null");
118 return false;
119 }
120 if (remoteListener_->StartListener(remoteListener_) != true) {
121 DBINDER_LOGE(LOG_LABEL, "restart dbinder server failed");
122 StopRemoteListener();
123 return false;
124 }
125
126 auto it = busNameObject_.begin();
127 while (it != busNameObject_.end()) {
128 std::string sessionName = it->second;
129 if (ReGrantPermission(sessionName) != true) {
130 DBINDER_LOGE(LOG_LABEL, "%s grant permission failed", sessionName.c_str());
131 }
132 ++it;
133 }
134 return true;
135 }
136
StopRemoteListener()137 void DBinderService::StopRemoteListener()
138 {
139 if (remoteListener_ != nullptr) {
140 remoteListener_->StopListener();
141 remoteListener_ = nullptr;
142 }
143 }
144
GetRemoteListener()145 std::shared_ptr<DBinderRemoteListener> DBinderService::GetRemoteListener()
146 {
147 if (remoteListener_ == nullptr && !StartRemoteListener()) {
148 return nullptr;
149 }
150 return remoteListener_;
151 }
152
GetInstance()153 sptr<DBinderService> DBinderService::GetInstance()
154 {
155 if (instance_ == nullptr) {
156 std::lock_guard<std::mutex> lockGuard(instanceMutex_);
157 if (instance_ == nullptr) {
158 sptr<DBinderService> temp = new DBinderService();
159 instance_ = temp;
160 }
161 }
162 return instance_;
163 }
164
GetSeqNumber()165 uint32_t DBinderService::GetSeqNumber()
166 {
167 std::lock_guard<std::mutex> lockGuard(instanceMutex_);
168 seqNumber_++; // can be overflow
169 return seqNumber_;
170 }
171
IsDeviceIdIllegal(const std::string & deviceID)172 bool DBinderService::IsDeviceIdIllegal(const std::string &deviceID)
173 {
174 if (deviceID.empty() || deviceID.length() > DEVICEID_LENGTH) {
175 return true;
176 }
177 return false;
178 }
179
CheckBinderObject(const sptr<DBinderServiceStub> & stub,binder_uintptr_t binderObject)180 bool DBinderService::CheckBinderObject(const sptr<DBinderServiceStub> &stub, binder_uintptr_t binderObject)
181 {
182 if (stub == nullptr) {
183 return false;
184 }
185
186 if (stub->GetBinderObject() == binderObject) {
187 DBINDER_LOGI(LOG_LABEL, "found registered stub");
188 return true;
189 }
190 return false;
191 }
192
HasDBinderStub(binder_uintptr_t binderObject)193 bool DBinderService::HasDBinderStub(binder_uintptr_t binderObject)
194 {
195 auto checkStub = [&binderObject, this](const sptr<DBinderServiceStub> &stub) {
196 return CheckBinderObject(stub, binderObject);
197 };
198
199 std::lock_guard<std::mutex> lockGuard(handleEntryMutex_);
200 auto it = std::find_if(DBinderStubRegisted_.begin(), DBinderStubRegisted_.end(), checkStub);
201 if (it != DBinderStubRegisted_.end()) {
202 return true;
203 }
204 return false;
205 }
206
IsSameStubObject(const sptr<DBinderServiceStub> & stub,const std::u16string & service,const std::string & device)207 bool DBinderService::IsSameStubObject(const sptr<DBinderServiceStub> &stub, const std::u16string &service,
208 const std::string &device)
209 {
210 if (stub == nullptr) {
211 return false;
212 }
213 if (IsSameTextStr(stub->GetServiceName(), Str16ToStr8(service)) && IsSameTextStr(stub->GetDeviceID(), device)) {
214 DBINDER_LOGI(LOG_LABEL, "found registered service with name = %{public}s", Str16ToStr8(service).c_str());
215 return true;
216 }
217 return false;
218 }
FindDBinderStub(const std::u16string & service,const std::string & device)219 sptr<DBinderServiceStub> DBinderService::FindDBinderStub(const std::u16string &service, const std::string &device)
220 {
221 auto checkStub = [&service, &device, this](const sptr<DBinderServiceStub> &stub) {
222 return IsSameStubObject(stub, service, device);
223 };
224
225 std::lock_guard<std::mutex> lockGuard(handleEntryMutex_);
226 auto it = std::find_if(DBinderStubRegisted_.begin(), DBinderStubRegisted_.end(), checkStub);
227 if (it == DBinderStubRegisted_.end()) {
228 return nullptr;
229 }
230 return (*it);
231 }
232
DeleteDBinderStub(const std::u16string & service,const std::string & device)233 bool DBinderService::DeleteDBinderStub(const std::u16string &service, const std::string &device)
234 {
235 auto checkStub = [&service, &device, this](const sptr<DBinderServiceStub> &stub) {
236 return IsSameStubObject(stub, service, device);
237 };
238
239 std::lock_guard<std::mutex> lockGuard(handleEntryMutex_);
240 auto it = std::find_if(DBinderStubRegisted_.begin(), DBinderStubRegisted_.end(), checkStub);
241 if (it == DBinderStubRegisted_.end()) {
242 return false;
243 }
244 DBinderStubRegisted_.erase(it);
245 return true;
246 }
247
FindOrNewDBinderStub(const std::u16string & service,const std::string & device,binder_uintptr_t binderObject)248 sptr<DBinderServiceStub> DBinderService::FindOrNewDBinderStub(const std::u16string &service, const std::string &device,
249 binder_uintptr_t binderObject)
250 {
251 auto checkStub = [&service, &device, this](const sptr<DBinderServiceStub> &stub) {
252 return IsSameStubObject(stub, service, device);
253 };
254
255 std::lock_guard<std::mutex> lockGuard(handleEntryMutex_);
256 auto it = std::find_if(DBinderStubRegisted_.begin(), DBinderStubRegisted_.end(), checkStub);
257 if (it != DBinderStubRegisted_.end()) {
258 return (*it);
259 }
260
261 sptr<DBinderServiceStub> dBinderServiceStub = new DBinderServiceStub(Str16ToStr8(service), device, binderObject);
262 DBinderStubRegisted_.push_back(dBinderServiceStub);
263 return dBinderServiceStub;
264 }
265
MakeRemoteBinder(const std::u16string & serviceName,const std::string & deviceID,binder_uintptr_t binderObject,uint32_t pid,uint32_t uid)266 sptr<DBinderServiceStub> DBinderService::MakeRemoteBinder(const std::u16string &serviceName,
267 const std::string &deviceID, binder_uintptr_t binderObject, uint32_t pid, uint32_t uid)
268 {
269 if (IsDeviceIdIllegal(deviceID) || serviceName.length() == 0) {
270 DBINDER_LOGE(LOG_LABEL, "para is wrong device id length = %zu, service name length = %zu", deviceID.length(),
271 serviceName.length());
272 return nullptr;
273 }
274 DBINDER_LOGI(LOG_LABEL, "name = %{public}s, deviceID = %{public}s", Str16ToStr8(serviceName).c_str(),
275 DBinderService::ConvertToSecureDeviceID(deviceID).c_str());
276
277 sptr<DBinderServiceStub> dBinderServiceStub = FindOrNewDBinderStub(serviceName, deviceID, binderObject);
278 if (dBinderServiceStub == nullptr) {
279 DBINDER_LOGE(LOG_LABEL, "fail to find or new service, service name = %{public}s",
280 Str16ToStr8(serviceName).c_str());
281 return nullptr;
282 }
283
284 /* if not found dBinderServiceStub, should send msg to toDeviceID
285 * to invoker socket thread and add authentication info for create softbus session
286 */
287 int retryTimes = 0;
288 bool ret = false;
289 do {
290 ret = InvokerRemoteDBinder(dBinderServiceStub, GetSeqNumber(), pid, uid);
291 retryTimes++;
292 } while (!ret && (retryTimes < RETRY_TIMES));
293 if (!ret) {
294 DBINDER_LOGE(LOG_LABEL, "fail to invoke service, service name = %{public}s, device = %{public}s "
295 "DBinderServiceStub refcount = %{public}d",
296 Str16ToStr8(serviceName).c_str(), DBinderService::ConvertToSecureDeviceID(deviceID).c_str(),
297 dBinderServiceStub->GetSptrRefCount());
298 /* invoke fail, delete dbinder stub info */
299 (void)DeleteDBinderStub(serviceName, deviceID);
300 (void)DetachSessionObject(reinterpret_cast<binder_uintptr_t>(dBinderServiceStub.GetRefPtr()));
301 return nullptr;
302 }
303 return dBinderServiceStub;
304 }
305
SendEntryToRemote(const sptr<DBinderServiceStub> stub,uint32_t seqNumber,uint32_t pid,uint32_t uid)306 bool DBinderService::SendEntryToRemote(const sptr<DBinderServiceStub> stub, uint32_t seqNumber, uint32_t pid,
307 uint32_t uid)
308 {
309 const std::string deviceID = stub->GetDeviceID();
310 const std::string localDevID = GetLocalDeviceID();
311 if (IsDeviceIdIllegal(deviceID) || IsDeviceIdIllegal(localDevID)) {
312 DBINDER_LOGE(LOG_LABEL, "wrong device ID");
313 return false;
314 }
315
316 std::shared_ptr<struct DHandleEntryTxRx> message = std::make_shared<struct DHandleEntryTxRx>();
317 message->head.len = sizeof(DHandleEntryTxRx);
318 message->head.version = VERSION_NUM;
319 message->dBinderCode = MESSAGE_AS_INVOKER;
320 message->transType = GetRemoteTransType();
321 message->rpcFeatureSet = GetLocalRpcFeature();
322 message->stubIndex = static_cast<uint64_t>(std::atoi(stub->GetServiceName().c_str()));
323 message->seqNumber = seqNumber;
324 message->binderObject = stub->GetBinderObject();
325 message->stub = reinterpret_cast<binder_uintptr_t>(stub.GetRefPtr());
326 message->deviceIdInfo.afType = DATABBUS_TYPE;
327 message->pid = pid;
328 message->uid = uid;
329 if (memcpy_s(message->deviceIdInfo.fromDeviceId, DEVICEID_LENGTH, localDevID.data(), localDevID.length()) != 0 ||
330 memcpy_s(message->deviceIdInfo.toDeviceId, DEVICEID_LENGTH, deviceID.data(), deviceID.length()) != 0) {
331 DBINDER_LOGE(LOG_LABEL, "fail to copy memory");
332 return false;
333 }
334 message->deviceIdInfo.fromDeviceId[localDevID.length()] = '\0';
335 message->deviceIdInfo.toDeviceId[deviceID.length()] = '\0';
336
337 std::shared_ptr<DBinderRemoteListener> remoteListener = GetRemoteListener();
338 if (remoteListener == nullptr) {
339 DBINDER_LOGE(LOG_LABEL, "remoteListener is null");
340 return false;
341 }
342 bool result = remoteListener->SendDataToRemote(deviceID, message.get());
343 if (result != true) {
344 DBINDER_LOGE(LOG_LABEL, "send to remote dbinderService failed");
345 return false;
346 }
347 return true;
348 }
349
InvokerRemoteDBinder(const sptr<DBinderServiceStub> stub,uint32_t seqNumber,uint32_t pid,uint32_t uid)350 bool DBinderService::InvokerRemoteDBinder(const sptr<DBinderServiceStub> stub, uint32_t seqNumber,
351 uint32_t pid, uint32_t uid)
352 {
353 if (stub == nullptr) {
354 DBINDER_LOGE(LOG_LABEL, "stub is nullptr");
355 return false;
356 }
357 bool result = SendEntryToRemote(stub, seqNumber, pid, uid);
358 if (!result) {
359 DBINDER_LOGE(LOG_LABEL, "send entry to remote dbinderService fail");
360 return false;
361 }
362
363 /* pend to wait reply */
364 std::shared_ptr<struct ThreadLockInfo> threadLockInfo = std::make_shared<struct ThreadLockInfo>();
365 result = AttachThreadLockInfo(seqNumber, stub->GetDeviceID(), threadLockInfo);
366 if (result != true) {
367 DBINDER_LOGE(LOG_LABEL, "attach lock info fail");
368 return false;
369 }
370
371 std::unique_lock<std::mutex> lock(threadLockInfo->mutex);
372 if (threadLockInfo->condition.wait_for(lock, std::chrono::seconds(WAIT_FOR_REPLY_MAX_SEC),
373 [&threadLockInfo] { return threadLockInfo->ready; }) == false) {
374 DBINDER_LOGE(LOG_LABEL, "get remote data failed");
375 DetachThreadLockInfo(seqNumber);
376 threadLockInfo->ready = false;
377 return false;
378 }
379 /* if can not find session, means invoke failed or nothing in OnRemoteReplyMessage() */
380 auto session = QuerySessionObject(reinterpret_cast<binder_uintptr_t>(stub.GetRefPtr()));
381 if (session == nullptr) {
382 DBINDER_LOGE(LOG_LABEL, "client find session is null");
383 return false;
384 }
385 return true;
386 }
387
CheckSystemAbilityId(int32_t systemAbilityId)388 bool DBinderService::CheckSystemAbilityId(int32_t systemAbilityId)
389 {
390 return systemAbilityId >= FIRST_SYS_ABILITY_ID && systemAbilityId <= LAST_SYS_ABILITY_ID;
391 }
392
AllocFreeSocketPort()393 uint16_t DBinderService::AllocFreeSocketPort()
394 {
395 /* alloc port by system */
396 return 0;
397 }
398
IsSameLoadSaItem(const std::string & srcNetworkId,int32_t systemAbilityId,std::shared_ptr<DHandleEntryTxRx> loadSaItem)399 bool DBinderService::IsSameLoadSaItem(const std::string& srcNetworkId, int32_t systemAbilityId,
400 std::shared_ptr<DHandleEntryTxRx> loadSaItem)
401 {
402 if (static_cast<int32_t>(loadSaItem->stubIndex) == systemAbilityId &&
403 loadSaItem->deviceIdInfo.fromDeviceId == srcNetworkId) {
404 DBINDER_LOGI(LOG_LABEL, "match succeed");
405 return true;
406 }
407 return false;
408 }
409
PopLoadSaItem(const std::string & srcNetworkId,int32_t systemAbilityId)410 std::shared_ptr<DHandleEntryTxRx> DBinderService::PopLoadSaItem(const std::string& srcNetworkId,
411 int32_t systemAbilityId)
412 {
413 auto checkSaItem = [srcNetworkId, systemAbilityId, this](std::shared_ptr<DHandleEntryTxRx> loadSaItem) {
414 return IsSameLoadSaItem(srcNetworkId, systemAbilityId, loadSaItem);
415 };
416
417 auto it = std::find_if(loadSaReply_.begin(), loadSaReply_.end(), checkSaItem);
418 if (it == loadSaReply_.end()) {
419 DBINDER_LOGE(LOG_LABEL, "findSaItem failed");
420 return nullptr;
421 }
422 std::shared_ptr<DHandleEntryTxRx> replymsg = (*it);
423 it = loadSaReply_.erase(it);
424 return replymsg;
425 }
426
LoadSystemAbilityComplete(const std::string & srcNetworkId,int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)427 void DBinderService::LoadSystemAbilityComplete(const std::string& srcNetworkId, int32_t systemAbilityId,
428 const sptr<IRemoteObject>& remoteObject)
429 {
430 std::lock_guard<std::shared_mutex> lockGuard(loadSaMutex_);
431 while (true) {
432 std::shared_ptr<struct DHandleEntryTxRx> replyMessage = PopLoadSaItem(srcNetworkId, systemAbilityId);
433 if (replyMessage == nullptr) {
434 break;
435 }
436 if (remoteObject == nullptr) {
437 SendMessageToRemote(MESSAGE_AS_REMOTE_ERROR, replyMessage);
438 DBINDER_LOGE(LOG_LABEL, "GetSystemAbility from samgr error, saId:%{public}d", systemAbilityId);
439 continue;
440 }
441 binder_uintptr_t binderObject = replyMessage->binderObject;
442 IPCObjectProxy *saProxy = reinterpret_cast<IPCObjectProxy *>(remoteObject.GetRefPtr());
443 if (QueryProxyObject(binderObject) == nullptr) {
444 /* When the stub object dies, you need to delete the corresponding busName information */
445 sptr<IRemoteObject::DeathRecipient> death(new DbinderSaDeathRecipient(binderObject));
446 if (!saProxy->AddDeathRecipient(death)) {
447 SendMessageToRemote(MESSAGE_AS_REMOTE_ERROR, replyMessage);
448 DBINDER_LOGE(LOG_LABEL, "fail to add death recipient");
449 continue;
450 }
451 if (!AttachProxyObject(remoteObject, binderObject)) {
452 SendMessageToRemote(MESSAGE_AS_REMOTE_ERROR, replyMessage);
453 DBINDER_LOGE(LOG_LABEL, "attach proxy object fail");
454 continue;
455 }
456 }
457 std::string deviceId = replyMessage->deviceIdInfo.fromDeviceId;
458 if (replyMessage->transType != IRemoteObject::DATABUS_TYPE) {
459 SendMessageToRemote(MESSAGE_AS_REMOTE_ERROR, replyMessage);
460 DBINDER_LOGE(LOG_LABEL, "Invalid Message Type");
461 } else {
462 if (!OnRemoteInvokerDataBusMessage(saProxy, replyMessage.get(), deviceId,
463 replyMessage->pid, replyMessage->uid)) {
464 SendMessageToRemote(MESSAGE_AS_REMOTE_ERROR, replyMessage);
465 continue;
466 }
467 SendMessageToRemote(MESSAGE_AS_REPLY, replyMessage);
468 }
469 }
470 DBINDER_LOGI(LOG_LABEL, "LoadSystemAbility complete");
471 }
472
SendMessageToRemote(uint32_t binderCode,std::shared_ptr<struct DHandleEntryTxRx> replyMessage)473 void DBinderService::SendMessageToRemote(uint32_t binderCode, std::shared_ptr<struct DHandleEntryTxRx> replyMessage)
474 {
475 std::shared_ptr<DBinderRemoteListener> remoteListener = GetRemoteListener();
476 if (remoteListener == nullptr) {
477 DBINDER_LOGE(LOG_LABEL, "remoteListener is null");
478 return;
479 }
480 replyMessage->dBinderCode = binderCode;
481 if (!remoteListener->SendDataToRemote(replyMessage->deviceIdInfo.fromDeviceId, replyMessage.get())) {
482 DBINDER_LOGE(LOG_LABEL, "fail to send data from server DBS to client DBS");
483 }
484 }
485
OnRemoteInvokerMessage(const struct DHandleEntryTxRx * message)486 bool DBinderService::OnRemoteInvokerMessage(const struct DHandleEntryTxRx *message)
487 {
488 std::shared_ptr<struct DHandleEntryTxRx> replyMessage = std::make_shared<struct DHandleEntryTxRx>();
489 if (memcpy_s(replyMessage.get(), sizeof(DHandleEntryTxRx), message, sizeof(DHandleEntryTxRx)) != 0) {
490 DBINDER_LOGE(LOG_LABEL, "fail to copy memory");
491 return false;
492 }
493
494 std::lock_guard<std::shared_mutex> lockGuard(loadSaMutex_);
495 bool isSaAvailable = dbinderCallback_->LoadSystemAbilityFromRemote(replyMessage->deviceIdInfo.fromDeviceId,
496 static_cast<int32_t>(replyMessage->stubIndex));
497 if (!isSaAvailable) {
498 DBINDER_LOGE(LOG_LABEL, "fail to call the system ability");
499 return false;
500 }
501 loadSaReply_.push_back(replyMessage);
502 return true;
503 }
504
GetDatabusNameByProxy(IPCObjectProxy * proxy,int32_t systemAbilityId)505 std::string DBinderService::GetDatabusNameByProxy(IPCObjectProxy *proxy, int32_t systemAbilityId)
506 {
507 if (proxy == nullptr) {
508 DBINDER_LOGE(LOG_LABEL, "proxy can not be null");
509 return "";
510 }
511 std::string sessionName = QueryBusNameObject(proxy);
512 if (!sessionName.empty()) {
513 DBINDER_LOGI(LOG_LABEL, "sessionName has been granded");
514 return sessionName;
515 }
516 sessionName = proxy->GetPidAndUidInfo(systemAbilityId);
517 if (sessionName.empty()) {
518 DBINDER_LOGE(LOG_LABEL, "grand session name failed");
519 return "";
520 }
521 return sessionName;
522 }
523
CreateDatabusName(int uid,int pid)524 std::string DBinderService::CreateDatabusName(int uid, int pid)
525 {
526 std::shared_ptr<ISessionService> softbusManager = ISessionService::GetInstance();
527 if (softbusManager == nullptr) {
528 DBINDER_LOGE(LOG_LABEL, "fail to get softbus service");
529 return "";
530 }
531
532 std::string sessionName = "DBinder" + std::to_string(uid) + std::string("_") + std::to_string(pid);
533 if (softbusManager->GrantPermission(uid, pid, sessionName) != ERR_NONE) {
534 DBINDER_LOGE(LOG_LABEL, "fail to Grant Permission softbus name");
535 return "";
536 }
537
538 return sessionName;
539 }
540
HandleInvokeListenThread(IPCObjectProxy * proxy,uint64_t stubIndex,std::string serverSessionName,struct DHandleEntryTxRx * replyMessage)541 bool DBinderService::HandleInvokeListenThread(IPCObjectProxy *proxy, uint64_t stubIndex,
542 std::string serverSessionName, struct DHandleEntryTxRx *replyMessage)
543 {
544 if (stubIndex == 0 || serverSessionName.empty() || serverSessionName.length() > SERVICENAME_LENGTH) {
545 DBINDER_LOGE(LOG_LABEL, "stubindex or session name invalid");
546 return false;
547 }
548
549 replyMessage->dBinderCode = MESSAGE_AS_REPLY;
550 replyMessage->stubIndex = stubIndex;
551 replyMessage->serviceNameLength = serverSessionName.length();
552 if (memcpy_s(replyMessage->serviceName, SERVICENAME_LENGTH, serverSessionName.data(),
553 replyMessage->serviceNameLength) != 0) {
554 DBINDER_LOGE(LOG_LABEL, "fail to copy memory");
555 return false;
556 }
557 replyMessage->serviceName[replyMessage->serviceNameLength] = '\0';
558 replyMessage->rpcFeatureSet = GetLocalRpcFeature() | GetRpcFeatureAck();
559
560 (void)AttachBusNameObject(proxy, serverSessionName);
561 return true;
562 }
563
OnRemoteInvokerDataBusMessage(IPCObjectProxy * proxy,struct DHandleEntryTxRx * replyMessage,std::string & remoteDeviceId,int pid,int uid)564 bool DBinderService::OnRemoteInvokerDataBusMessage(IPCObjectProxy *proxy, struct DHandleEntryTxRx *replyMessage,
565 std::string &remoteDeviceId, int pid, int uid)
566 {
567 if (IsDeviceIdIllegal(remoteDeviceId)) {
568 DBINDER_LOGE(LOG_LABEL, "remote device id is error");
569 return false;
570 }
571 std::string sessionName = GetDatabusNameByProxy(proxy, replyMessage->stubIndex);
572 if (sessionName.empty()) {
573 DBINDER_LOGE(LOG_LABEL, "get bus name fail");
574 return false;
575 }
576
577 uint32_t featureSet = replyMessage->rpcFeatureSet & GetLocalRpcFeature();
578 MessageParcel data;
579 MessageParcel reply;
580 if (!data.WriteUint16(IRemoteObject::DATABUS_TYPE) || !data.WriteString(GetLocalDeviceID()) ||
581 !data.WriteUint32(pid) || !data.WriteUint32(uid) || !data.WriteString(remoteDeviceId) ||
582 !data.WriteString(sessionName) || !data.WriteUint32(featureSet)) {
583 DBINDER_LOGE(LOG_LABEL, "write to parcel fail");
584 return false;
585 }
586 int err = proxy->InvokeListenThread(data, reply);
587 if (err != ERR_NONE) {
588 DBINDER_LOGE(LOG_LABEL, "start service listen error = %d", err);
589 return false;
590 }
591 uint64_t stubIndex = reply.ReadUint64();
592 std::string serverSessionName = reply.ReadString();
593 return HandleInvokeListenThread(proxy, stubIndex, serverSessionName, replyMessage);
594 }
595
GetRegisterService(binder_uintptr_t binderObject)596 std::u16string DBinderService::GetRegisterService(binder_uintptr_t binderObject)
597 {
598 DBINDER_LOGI(LOG_LABEL, "get service binderObject");
599 std::shared_lock<std::shared_mutex> lockGuard(remoteBinderMutex_);
600 for (auto it = mapRemoteBinderObjects_.begin(); it != mapRemoteBinderObjects_.end(); it++) {
601 if (it->second == binderObject) {
602 return it->first;
603 }
604 }
605 return std::u16string();
606 }
607
RegisterRemoteProxy(std::u16string serviceName,sptr<IRemoteObject> binderObject)608 bool DBinderService::RegisterRemoteProxy(std::u16string serviceName, sptr<IRemoteObject> binderObject)
609 {
610 DBINDER_LOGI(LOG_LABEL, "register remote proxy, service name = %{public}s", Str16ToStr8(serviceName).c_str());
611
612 if (serviceName.length() == 0 || binderObject == nullptr) {
613 DBINDER_LOGE(LOG_LABEL, "serviceName.length() = %zu", serviceName.length());
614 return false;
615 }
616
617 binder_uintptr_t binder = (binder_uintptr_t)binderObject.GetRefPtr();
618 DBINDER_LOGI(LOG_LABEL, "register remote proxy");
619 return RegisterRemoteProxyInner(serviceName, binder);
620 }
621
RegisterRemoteProxy(std::u16string serviceName,int32_t systemAbilityId)622 bool DBinderService::RegisterRemoteProxy(std::u16string serviceName, int32_t systemAbilityId)
623 {
624 DBINDER_LOGI(LOG_LABEL, "register remote proxy, service name = %{public}s", Str16ToStr8(serviceName).c_str());
625
626 if (serviceName.length() == 0 || systemAbilityId <= 0) {
627 DBINDER_LOGE(LOG_LABEL, "serviceName.length() = %zu", serviceName.length());
628 return false;
629 }
630
631 binder_uintptr_t binder = (binder_uintptr_t)systemAbilityId;
632 return RegisterRemoteProxyInner(serviceName, binder);
633 }
634
RegisterRemoteProxyInner(std::u16string serviceName,binder_uintptr_t binder)635 bool DBinderService::RegisterRemoteProxyInner(std::u16string serviceName, binder_uintptr_t binder)
636 {
637 std::unique_lock<std::shared_mutex> lockGuard(remoteBinderMutex_);
638 // clear historical remnants, Don't care if it succeeds
639 (void)mapRemoteBinderObjects_.erase(serviceName);
640 auto result = mapRemoteBinderObjects_.insert(std::pair<std::u16string, binder_uintptr_t>(serviceName, binder));
641 return result.second;
642 }
643
OnRemoteMessageTask(const struct DHandleEntryTxRx * message)644 bool DBinderService::OnRemoteMessageTask(const struct DHandleEntryTxRx *message)
645 {
646 if (message == nullptr) {
647 DBINDER_LOGE(LOG_LABEL, "message is null");
648 return false;
649 }
650
651 bool result = true;
652 switch (message->dBinderCode) {
653 case MESSAGE_AS_INVOKER: {
654 result = OnRemoteInvokerMessage(message);
655 break;
656 }
657 case MESSAGE_AS_REPLY: {
658 OnRemoteReplyMessage(message);
659 break;
660 }
661 case MESSAGE_AS_REMOTE_ERROR: {
662 OnRemoteErrorMessage(message);
663 break;
664 }
665 default: {
666 DBINDER_LOGE(LOG_LABEL, "ERROR! DbinderCode is wrong value, code =%u", message->dBinderCode);
667 result = false;
668 break;
669 }
670 }
671 return result;
672 }
673
ProcessOnSessionClosed(std::shared_ptr<Session> session)674 bool DBinderService::ProcessOnSessionClosed(std::shared_ptr<Session> session)
675 {
676 if (session == nullptr) {
677 DBINDER_LOGE(LOG_LABEL, "ERROR!Session is nullptr!");
678 return false;
679 }
680 std::lock_guard<std::mutex> lock(threadLockMutex_);
681 for (auto it = threadLockInfo_.begin(); it != threadLockInfo_.end();) {
682 if (it->second->networkId != session->GetPeerDeviceId()) {
683 continue;
684 }
685 std::unique_lock<std::mutex> lock(it->second->mutex);
686 it->second->ready = true;
687 it->second->condition.notify_all();
688 it = threadLockInfo_.erase(it);
689 }
690 return true;
691 }
692
OnRemoteErrorMessage(const struct DHandleEntryTxRx * replyMessage)693 void DBinderService::OnRemoteErrorMessage(const struct DHandleEntryTxRx *replyMessage)
694 {
695 DBINDER_LOGI(LOG_LABEL, "invoke remote stub = %{public}d error, seq = %{public}u",
696 static_cast<int32_t>(replyMessage->stubIndex), replyMessage->seqNumber);
697 WakeupThreadByStub(replyMessage->seqNumber);
698 DetachThreadLockInfo(replyMessage->seqNumber);
699 }
700
OnRemoteReplyMessage(const struct DHandleEntryTxRx * replyMessage)701 void DBinderService::OnRemoteReplyMessage(const struct DHandleEntryTxRx *replyMessage)
702 {
703 MakeSessionByReplyMessage(replyMessage);
704 WakeupThreadByStub(replyMessage->seqNumber);
705 DetachThreadLockInfo(replyMessage->seqNumber);
706 }
707
IsSameSession(std::shared_ptr<struct SessionInfo> oldSession,std::shared_ptr<struct SessionInfo> nowSession)708 bool DBinderService::IsSameSession(std::shared_ptr<struct SessionInfo> oldSession,
709 std::shared_ptr<struct SessionInfo> nowSession)
710 {
711 if ((oldSession->stubIndex != nowSession->stubIndex) || (oldSession->type != nowSession->type)
712 ||(oldSession->serviceName != nowSession->serviceName)) {
713 return false;
714 }
715 if (strncmp(oldSession->deviceIdInfo.fromDeviceId, nowSession->deviceIdInfo.fromDeviceId, DEVICEID_LENGTH) != 0
716 || strncmp(oldSession->deviceIdInfo.toDeviceId, nowSession->deviceIdInfo.toDeviceId, DEVICEID_LENGTH) != 0) {
717 return false;
718 }
719
720 return true;
721 }
722
MakeSessionByReplyMessage(const struct DHandleEntryTxRx * replyMessage)723 void DBinderService::MakeSessionByReplyMessage(const struct DHandleEntryTxRx *replyMessage)
724 {
725 if (HasDBinderStub(replyMessage->binderObject) == false) {
726 DBINDER_LOGE(LOG_LABEL, "invalid stub object");
727 return;
728 }
729
730 std::shared_ptr<struct SessionInfo> session = std::make_shared<struct SessionInfo>();
731 if (session == nullptr) {
732 DBINDER_LOGE(LOG_LABEL, "new SessionInfo fail");
733 return;
734 }
735
736 if (memcpy_s(&session->deviceIdInfo, sizeof(struct DeviceIdInfo), &replyMessage->deviceIdInfo,
737 sizeof(struct DeviceIdInfo)) != 0) {
738 DBINDER_LOGE(LOG_LABEL, "fail to copy memory");
739 return;
740 }
741 session->seqNumber = replyMessage->seqNumber;
742 session->socketFd = 0;
743 session->stubIndex = replyMessage->stubIndex;
744 session->rpcFeatureSet = 0;
745 if (IsFeatureAck(replyMessage->rpcFeatureSet) == true) {
746 session->rpcFeatureSet = replyMessage->rpcFeatureSet & GetLocalRpcFeature();
747 }
748 session->type = replyMessage->transType;
749 session->serviceName = replyMessage->serviceName;
750
751 if (session->stubIndex == 0) {
752 DBINDER_LOGE(LOG_LABEL, "get stub index == 0, it is invalid");
753 return;
754 }
755
756 std::shared_ptr<struct SessionInfo> oldSession = QuerySessionObject(replyMessage->stub);
757 if (oldSession != nullptr) {
758 if (IsSameSession(oldSession, session)) {
759 DBINDER_LOGI(LOG_LABEL, "invoker remote session already, do nothing");
760 return;
761 }
762 if (oldSession->seqNumber < session->seqNumber) {
763 DBINDER_LOGI(LOG_LABEL, "replace oldsession %{public}s with newsession %{public}s",
764 oldSession->serviceName.c_str(), session->serviceName.c_str());
765 if (!DetachSessionObject(replyMessage->stub)) {
766 DBINDER_LOGE(LOG_LABEL, "failed to detach session object");
767 }
768 }
769 }
770
771 if (!AttachSessionObject(session, replyMessage->stub)) {
772 DBINDER_LOGE(LOG_LABEL, "attach SessionInfo fail");
773 return;
774 }
775 }
776
WakeupThreadByStub(uint32_t seqNumber)777 void DBinderService::WakeupThreadByStub(uint32_t seqNumber)
778 {
779 std::shared_ptr<struct ThreadLockInfo> threadLockInfo = QueryThreadLockInfo(seqNumber);
780 if (threadLockInfo == nullptr) {
781 DBINDER_LOGE(LOG_LABEL, "threadLockInfo is not exist");
782 return;
783 }
784 /* Wake up the client processing thread */
785 std::unique_lock<std::mutex> lock(threadLockInfo->mutex);
786 threadLockInfo->ready = true;
787 threadLockInfo->condition.notify_all();
788 }
789
DetachThreadLockInfo(uint32_t seqNumber)790 void DBinderService::DetachThreadLockInfo(uint32_t seqNumber)
791 {
792 std::lock_guard<std::mutex> lock(threadLockMutex_);
793 threadLockInfo_.erase(seqNumber);
794 }
795
AttachThreadLockInfo(uint32_t seqNumber,const std::string & networkId,std::shared_ptr<struct ThreadLockInfo> object)796 bool DBinderService::AttachThreadLockInfo(uint32_t seqNumber, const std::string &networkId,
797 std::shared_ptr<struct ThreadLockInfo> object)
798 {
799 std::lock_guard<std::mutex> lock(threadLockMutex_);
800 object->networkId = networkId;
801 auto result =
802 threadLockInfo_.insert(std::pair<uint32_t, std::shared_ptr<struct ThreadLockInfo>>(seqNumber, object));
803
804 return result.second;
805 }
806
QueryThreadLockInfo(uint32_t seqNumber)807 std::shared_ptr<struct ThreadLockInfo> DBinderService::QueryThreadLockInfo(uint32_t seqNumber)
808 {
809 std::lock_guard<std::mutex> lock(threadLockMutex_);
810
811 auto it = threadLockInfo_.find(seqNumber);
812 if (it != threadLockInfo_.end()) {
813 return it->second;
814 }
815 return nullptr;
816 }
817
DetachProxyObject(binder_uintptr_t binderObject)818 bool DBinderService::DetachProxyObject(binder_uintptr_t binderObject)
819 {
820 std::unique_lock<std::shared_mutex> lock(proxyMutex_);
821
822 return (proxyObject_.erase(binderObject) > 0);
823 }
824
AttachProxyObject(sptr<IRemoteObject> object,binder_uintptr_t binderObject)825 bool DBinderService::AttachProxyObject(sptr<IRemoteObject> object, binder_uintptr_t binderObject)
826 {
827 std::unique_lock<std::shared_mutex> lock(proxyMutex_);
828
829 auto result = proxyObject_.insert(std::pair<int, sptr<IRemoteObject>>(binderObject, object));
830 return result.second;
831 }
832
QueryProxyObject(binder_uintptr_t binderObject)833 sptr<IRemoteObject> DBinderService::QueryProxyObject(binder_uintptr_t binderObject)
834 {
835 std::shared_lock<std::shared_mutex> lock(proxyMutex_);
836
837 auto it = proxyObject_.find(binderObject);
838 if (it != proxyObject_.end()) {
839 return it->second;
840 }
841 return nullptr;
842 }
843
DetachSessionObject(binder_uintptr_t stub)844 bool DBinderService::DetachSessionObject(binder_uintptr_t stub)
845 {
846 std::unique_lock<std::shared_mutex> lock(sessionMutex_);
847
848 return (sessionObject_.erase(stub) > 0);
849 }
850
AttachSessionObject(std::shared_ptr<struct SessionInfo> object,binder_uintptr_t stub)851 bool DBinderService::AttachSessionObject(std::shared_ptr<struct SessionInfo> object, binder_uintptr_t stub)
852 {
853 std::unique_lock<std::shared_mutex> lock(sessionMutex_);
854
855 auto ret = sessionObject_.insert(std::pair<binder_uintptr_t, std::shared_ptr<struct SessionInfo>>(stub, object));
856
857 return ret.second;
858 }
859
QuerySessionObject(binder_uintptr_t stub)860 std::shared_ptr<struct SessionInfo> DBinderService::QuerySessionObject(binder_uintptr_t stub)
861 {
862 std::shared_lock<std::shared_mutex> lock(sessionMutex_);
863
864 auto it = sessionObject_.find(stub);
865 if (it != sessionObject_.end()) {
866 return it->second;
867 }
868 return nullptr;
869 }
870
DetachBusNameObject(IPCObjectProxy * proxy)871 bool DBinderService::DetachBusNameObject(IPCObjectProxy *proxy)
872 {
873 std::unique_lock<std::shared_mutex> lock(busNameMutex_);
874
875 return (busNameObject_.erase(proxy) > 0);
876 }
877
AttachBusNameObject(IPCObjectProxy * proxy,const std::string & name)878 bool DBinderService::AttachBusNameObject(IPCObjectProxy *proxy, const std::string &name)
879 {
880 std::unique_lock<std::shared_mutex> lock(busNameMutex_);
881
882 auto ret = busNameObject_.insert(std::pair<IPCObjectProxy *, std::string>(proxy, name));
883
884 return ret.second;
885 }
886
QueryBusNameObject(IPCObjectProxy * proxy)887 std::string DBinderService::QueryBusNameObject(IPCObjectProxy *proxy)
888 {
889 std::shared_lock<std::shared_mutex> lock(busNameMutex_);
890
891 auto it = busNameObject_.find(proxy);
892 if (it != busNameObject_.end()) {
893 return it->second;
894 }
895 return "";
896 }
897
DetachDeathRecipient(sptr<IRemoteObject> object)898 bool DBinderService::DetachDeathRecipient(sptr<IRemoteObject> object)
899 {
900 std::unique_lock<std::shared_mutex> lockGuard(deathRecipientMutex_);
901
902 return (deathRecipients_.erase(object) > 0);
903 }
904
AttachDeathRecipient(sptr<IRemoteObject> object,sptr<IRemoteObject::DeathRecipient> deathRecipient)905 bool DBinderService::AttachDeathRecipient(sptr<IRemoteObject> object,
906 sptr<IRemoteObject::DeathRecipient> deathRecipient)
907 {
908 std::unique_lock<std::shared_mutex> lockGuard(deathRecipientMutex_);
909
910 auto ret = deathRecipients_.insert(
911 std::pair<sptr<IRemoteObject>, sptr<IRemoteObject::DeathRecipient>>(object, deathRecipient));
912
913 return ret.second;
914 }
915
QueryDeathRecipient(sptr<IRemoteObject> object)916 sptr<IRemoteObject::DeathRecipient> DBinderService::QueryDeathRecipient(sptr<IRemoteObject> object)
917 {
918 std::shared_lock<std::shared_mutex> lockGuard(deathRecipientMutex_);
919
920 auto it = deathRecipients_.find(object);
921 if (it != deathRecipients_.end()) {
922 return it->second;
923 }
924
925 return nullptr;
926 }
927
928
DetachCallbackProxy(sptr<IRemoteObject> object)929 bool DBinderService::DetachCallbackProxy(sptr<IRemoteObject> object)
930 {
931 std::lock_guard<std::mutex> lockGuard(callbackProxyMutex_);
932
933 return (noticeProxy_.erase(object) > 0);
934 }
935
AttachCallbackProxy(sptr<IRemoteObject> object,DBinderServiceStub * dbStub)936 bool DBinderService::AttachCallbackProxy(sptr<IRemoteObject> object, DBinderServiceStub *dbStub)
937 {
938 std::lock_guard<std::mutex> lockGuard(callbackProxyMutex_);
939
940 auto result = noticeProxy_.insert(std::pair<sptr<IRemoteObject>, DBinderServiceStub *>(object, dbStub));
941
942 return result.second;
943 }
944
NoticeCallbackProxy(sptr<DBinderServiceStub> dbStub)945 bool DBinderService::NoticeCallbackProxy(sptr<DBinderServiceStub> dbStub)
946 {
947 DBINDER_LOGI(LOG_LABEL, "%{public}s: enter, service:%{public}s devicId:%{public}s",
948 __func__, dbStub->GetServiceName().c_str(),
949 DBinderService::ConvertToSecureDeviceID(dbStub->GetDeviceID()).c_str());
950 bool status = true;
951 const binder_uintptr_t binderObject = reinterpret_cast<binder_uintptr_t>(dbStub.GetRefPtr());
952 if (!DetachSessionObject(binderObject)) {
953 DBINDER_LOGE(LOG_LABEL, "fail to detach session object");
954 status = false;
955 }
956
957 if (!DeleteDBinderStub(Str8ToStr16(dbStub->GetServiceName()), dbStub->GetDeviceID())) {
958 DBINDER_LOGE(LOG_LABEL, "fail to delete DBinder stub");
959 status = false;
960 }
961
962 ProcessCallbackProxy(dbStub);
963
964 return status;
965 }
966
ProcessCallbackProxy(sptr<DBinderServiceStub> dbStub)967 void DBinderService::ProcessCallbackProxy(sptr<DBinderServiceStub> dbStub)
968 {
969 std::lock_guard<std::mutex> lockGuard(callbackProxyMutex_);
970
971 for (auto it = noticeProxy_.begin(); it != noticeProxy_.end();) {
972 if (it->second == dbStub.GetRefPtr()) {
973 IPCObjectProxy *callbackProxy = reinterpret_cast<IPCObjectProxy *>((it->first).GetRefPtr());
974 int status = callbackProxy->NoticeServiceDie();
975 if (status != ERR_NONE) {
976 DBINDER_LOGE(LOG_LABEL, "fail to notice service");
977 // do nothing, Continue to clear subsequent data
978 }
979
980 sptr<IRemoteObject::DeathRecipient> death = QueryDeathRecipient((it->first));
981 if (death != nullptr) {
982 // Continue to clear subsequent data
983 callbackProxy->RemoveDeathRecipient(death);
984 }
985
986 if (!DetachDeathRecipient((it->first))) {
987 DBINDER_LOGE(LOG_LABEL, "detaching death recipient is failed");
988 }
989
990 it = noticeProxy_.erase(it);
991 } else {
992 it++;
993 }
994 }
995 }
996
NoticeServiceDieInner(const std::u16string & serviceName,const std::string & deviceID)997 int32_t DBinderService::NoticeServiceDieInner(const std::u16string &serviceName, const std::string &deviceID)
998 {
999 if (serviceName.empty() || IsDeviceIdIllegal(deviceID)) {
1000 DBINDER_LOGE(LOG_LABEL, "service name length = %zu, deviceID length = %zu",
1001 serviceName.length(), deviceID.length());
1002 return DBINDER_SERVICE_INVALID_DATA_ERR;
1003 }
1004
1005 DBINDER_LOGI(LOG_LABEL, "%{public}s: service:%{public}s devicId:%{public}s",
1006 __func__, Str16ToStr8(serviceName).c_str(),
1007 DBinderService::ConvertToSecureDeviceID(deviceID).c_str());
1008
1009 sptr<DBinderServiceStub> dbStub = FindDBinderStub(serviceName, deviceID);
1010 if (dbStub == nullptr) {
1011 DBINDER_LOGE(LOG_LABEL, "find null stub, do not need notice death");
1012 return ERR_NONE;
1013 }
1014
1015 if (!NoticeCallbackProxy(dbStub)) {
1016 DBINDER_LOGE(LOG_LABEL, "find null proxy");
1017 return DBINDER_SERVICE_NOTICE_DIE_ERR;
1018 }
1019 return ERR_NONE;
1020 }
1021
NoticeServiceDie(const std::u16string & serviceName,const std::string & deviceID)1022 int32_t DBinderService::NoticeServiceDie(const std::u16string &serviceName, const std::string &deviceID)
1023 {
1024 std::lock_guard<std::mutex> lockGuard(deathNotificationMutex_);
1025 return NoticeServiceDieInner(serviceName, deviceID);
1026 }
1027
NoticeDeviceDie(const std::string & deviceID)1028 int32_t DBinderService::NoticeDeviceDie(const std::string &deviceID)
1029 {
1030 if (IsDeviceIdIllegal(deviceID)) {
1031 DBINDER_LOGE(LOG_LABEL, "deviceID length = %zu", deviceID.length());
1032 return DBINDER_SERVICE_INVALID_DATA_ERR;
1033 }
1034 DBINDER_LOGI(LOG_LABEL, "remote device is dead, device = %s",
1035 DBinderService::ConvertToSecureDeviceID(deviceID).c_str());
1036 if (remoteListener_ == nullptr) {
1037 DBINDER_LOGE(LOG_LABEL, "remote listener is null");
1038 return DBINDER_SERVICE_NOTICE_DIE_ERR;
1039 }
1040
1041 if (!remoteListener_->CloseDatabusSession(deviceID)) {
1042 DBINDER_LOGE(LOG_LABEL, "close databus session fail");
1043 // do nothing
1044 }
1045
1046 std::list<std::u16string> serviceNames = FindServicesByDeviceID(deviceID);
1047 if (serviceNames.empty()) {
1048 DBINDER_LOGE(LOG_LABEL, "the device does not have any registered service");
1049 return ERR_NONE;
1050 }
1051
1052 int status = ERR_NONE;
1053 std::lock_guard<std::mutex> lockGuard(deathNotificationMutex_);
1054
1055 for (auto it = serviceNames.begin(); it != serviceNames.end(); it++) {
1056 status += NoticeServiceDieInner((*it), deviceID);
1057 }
1058
1059 return status;
1060 }
1061
FindServicesByDeviceID(const std::string & deviceID)1062 std::list<std::u16string> DBinderService::FindServicesByDeviceID(const std::string &deviceID)
1063 {
1064 std::lock_guard<std::mutex> lockGuard(handleEntryMutex_);
1065 std::list<std::u16string> serviceNames;
1066 for (auto it = DBinderStubRegisted_.begin(); it != DBinderStubRegisted_.end(); it++) {
1067 if ((*it)->GetDeviceID() == deviceID) {
1068 serviceNames.push_back(Str8ToStr16((*it)->GetServiceName()));
1069 }
1070 }
1071
1072 return serviceNames;
1073 }
1074
GetRemoteTransType()1075 uint32_t DBinderService::GetRemoteTransType()
1076 {
1077 return IRemoteObject::DATABUS_TYPE;
1078 }
1079
ConvertToSecureDeviceID(const std::string & deviceID)1080 std::string DBinderService::ConvertToSecureDeviceID(const std::string &deviceID)
1081 {
1082 if (strlen(deviceID.c_str()) <= ENCRYPT_LENGTH) {
1083 return "****";
1084 }
1085 return deviceID.substr(0, ENCRYPT_LENGTH) + "****" + deviceID.substr(strlen(deviceID.c_str()) - ENCRYPT_LENGTH);
1086 }
1087
ReGrantPermission(const std::string & sessionName)1088 bool DBinderService::ReGrantPermission(const std::string &sessionName)
1089 {
1090 if (sessionName.empty()) {
1091 return false;
1092 }
1093 std::string::size_type splitIndex = sessionName.find('_');
1094 if (splitIndex == std::string::npos) {
1095 DBINDER_LOGE(LOG_LABEL, "grant permission not found _");
1096 return false;
1097 }
1098 int32_t uidLength = static_cast<int32_t>(splitIndex) - DBINDER_UID_START_INDEX;
1099 std::string uidString = sessionName.substr(DBINDER_UID_START_INDEX, uidLength);
1100 std::string pidString = sessionName.substr(splitIndex + 1);
1101 std::shared_ptr<ISessionService> softbusManager = ISessionService::GetInstance();
1102 if (softbusManager == nullptr) {
1103 DBINDER_LOGE(LOG_LABEL, "fail to get softbus service");
1104 return false;
1105 }
1106
1107 if (softbusManager->GrantPermission(std::stoi(uidString), std::stoi(pidString), sessionName) != ERR_NONE) {
1108 DBINDER_LOGE(LOG_LABEL, "fail to Grant Permission softbus name");
1109 return false;
1110 }
1111 return true;
1112 }
1113 } // namespace OHOS
1114