• 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 "dbinder_service.h"
17 
18 #include <cinttypes>
19 #include "securec.h"
20 #include "string_ex.h"
21 #include "ipc_skeleton.h"
22 #include "ipc_thread_skeleton.h"
23 
24 #include "dbinder_error_code.h"
25 #include "dbinder_log.h"
26 #include "dbinder_remote_listener.h"
27 #include "dbinder_sa_death_recipient.h"
28 #include "dbinder_service_stub.h"
29 #include "ffrt.h"
30 #include "dsoftbus_interface.h"
31 
32 namespace OHOS {
33 
34 static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, LOG_ID_RPC_DBINDER_SER, "DBinderService" };
35 
36 sptr<DBinderService> DBinderService::instance_ = nullptr;
37 bool DBinderService::mainThreadCreated_ = false;
38 std::mutex DBinderService::instanceMutex_;
39 std::shared_ptr<DBinderRemoteListener> DBinderService::remoteListener_ = nullptr;
40 constexpr unsigned int BINDER_MASK = 0xffff;
41 // DBinderServiceStub's reference count in a MakeRemoteBinder call.
42 constexpr int DBINDER_STUB_REF_COUNT = 2;
43 constexpr int INVOKER_NUMBER = 2;
DBinderService()44 DBinderService::DBinderService()
45 {
46     DBINDER_LOGI(LOG_LABEL, "create dbinder service");
47 }
48 
~DBinderService()49 DBinderService::~DBinderService()
50 {
51     StopRemoteListener();
52 
53     DBinderStubRegisted_.clear();
54     mapDBinderStubRegisters_.clear();
55     mapRemoteBinderObjects_.clear();
56     threadLockInfo_.clear();
57     proxyObject_.clear();
58     sessionObject_.clear();
59     noticeProxy_.clear();
60     deathRecipients_.clear();
61     loadSaReply_.clear();
62     dbinderCallback_ = nullptr;
63     DBINDER_LOGI(LOG_LABEL, "dbinder service died");
64 }
65 
GetLocalDeviceID()66 std::string DBinderService::GetLocalDeviceID()
67 {
68     std::string pkgName = "DBinderService";
69     std::string networkId;
70 
71     if (DBinderSoftbusClient::GetInstance().GetLocalNodeDeviceId(
72         pkgName.c_str(), networkId) != SOFTBUS_CLIENT_SUCCESS) {
73         DBINDER_LOGE(LOG_LABEL, "Get local node device id failed");
74     }
75 
76     return networkId;
77 }
78 
StartDBinderService(std::shared_ptr<RpcSystemAbilityCallback> & callbackImpl)79 bool DBinderService::StartDBinderService(std::shared_ptr<RpcSystemAbilityCallback> &callbackImpl)
80 {
81     if (mainThreadCreated_) {
82         return ReStartRemoteListener();
83     }
84 
85     bool result = StartRemoteListener();
86     if (!result) {
87         return false;
88     }
89     mainThreadCreated_ = true;
90     dbinderCallback_ = callbackImpl;
91 
92     return true;
93 }
94 
StartRemoteListener()95 bool DBinderService::StartRemoteListener()
96 {
97     if (remoteListener_ != nullptr) {
98         DBINDER_LOGI(LOG_LABEL, "remote listener started");
99         return true;
100     }
101 
102     remoteListener_ = std::make_shared<DBinderRemoteListener>();
103     if (remoteListener_ == nullptr) {
104         DBINDER_LOGE(LOG_LABEL, "failed to create remote listener");
105         return false;
106     }
107 
108     if (remoteListener_->StartListener() != true) {
109         StopRemoteListener();
110         return false;
111     }
112 
113     DBINDER_LOGI(LOG_LABEL, "start remote listener ok");
114     return true;
115 }
116 
ReStartRemoteListener()117 bool DBinderService::ReStartRemoteListener()
118 {
119     if (remoteListener_ == nullptr) {
120         DBINDER_LOGE(LOG_LABEL, "restart remote listener got null");
121         return false;
122     }
123     if (remoteListener_->StartListener() != true) {
124         DBINDER_LOGE(LOG_LABEL, "restart dbinder server failed");
125         StopRemoteListener();
126         return false;
127     }
128     return true;
129 }
130 
StopRemoteListener()131 void DBinderService::StopRemoteListener()
132 {
133     if (remoteListener_ != nullptr) {
134         remoteListener_->StopListener();
135         remoteListener_ = nullptr;
136     }
137 }
138 
GetRemoteListener()139 std::shared_ptr<DBinderRemoteListener> DBinderService::GetRemoteListener()
140 {
141     if (remoteListener_ == nullptr && !StartRemoteListener()) {
142         return nullptr;
143     }
144     return remoteListener_;
145 }
146 
GetInstance()147 sptr<DBinderService> DBinderService::GetInstance()
148 {
149     if (instance_ == nullptr) {
150         std::lock_guard<std::mutex> lockGuard(instanceMutex_);
151         if (instance_ == nullptr) {
152             sptr<DBinderService> temp = new DBinderService();
153             instance_ = temp;
154         }
155     }
156     return instance_;
157 }
158 
GetSeqNumber()159 uint32_t DBinderService::GetSeqNumber()
160 {
161     std::lock_guard<std::mutex> lockGuard(instanceMutex_);
162     if (seqNumber_ == std::numeric_limits<uint32_t>::max()) {
163         seqNumber_ = 0;
164     }
165     seqNumber_++;
166     return seqNumber_;
167 }
168 
IsDeviceIdIllegal(const std::string & deviceID)169 bool DBinderService::IsDeviceIdIllegal(const std::string &deviceID)
170 {
171     if (deviceID.empty() || deviceID.length() > DEVICEID_LENGTH) {
172         return true;
173     }
174     return false;
175 }
176 
AddStubByTag(binder_uintptr_t stub)177 binder_uintptr_t DBinderService::AddStubByTag(binder_uintptr_t stub)
178 {
179     std::lock_guard<std::mutex> lockGuard(handleEntryMutex_);
180 
181     // the same stub needs add stubNum to mapDBinderStubRegisters_, the previous corresponding stubNum will be returned.
182     for (auto iter = mapDBinderStubRegisters_.begin(); iter != mapDBinderStubRegisters_.end(); iter++) {
183         if (iter->second == stub) {
184             return iter->first;
185         }
186     }
187     binder_uintptr_t stubTag = stubTagNum_++;
188     auto result = mapDBinderStubRegisters_.insert(
189         std::pair<binder_uintptr_t, binder_uintptr_t>(stubTag, stub));
190     if (result.second) {
191         return stubTag;
192     } else {
193         return 0;
194     }
195 }
196 
QueryStubPtr(binder_uintptr_t stubTag)197 binder_uintptr_t DBinderService::QueryStubPtr(binder_uintptr_t stubTag)
198 {
199     std::lock_guard<std::mutex> lockGuard(handleEntryMutex_);
200 
201     auto iter = mapDBinderStubRegisters_.find(stubTag);
202     if (iter != mapDBinderStubRegisters_.end()) {
203         return iter->second;
204     }
205 
206     return 0;
207 }
208 
CheckBinderObject(const sptr<DBinderServiceStub> & stub,binder_uintptr_t stubPtr)209 bool DBinderService::CheckBinderObject(const sptr<DBinderServiceStub> &stub, binder_uintptr_t stubPtr)
210 {
211     if (stub == nullptr) {
212         return false;
213     }
214 
215     if (reinterpret_cast<binder_uintptr_t>(stub.GetRefPtr()) == stubPtr) {
216         DBINDER_LOGI(LOG_LABEL, "found registered stub");
217         return true;
218     }
219     return false;
220 }
221 
HasDBinderStub(binder_uintptr_t stubPtr)222 bool DBinderService::HasDBinderStub(binder_uintptr_t stubPtr)
223 {
224     auto checkStub = [&stubPtr, this](const sptr<DBinderServiceStub> &stub) {
225         return CheckBinderObject(stub, stubPtr);
226     };
227 
228     std::lock_guard<std::mutex> lockGuard(handleEntryMutex_);
229     auto it = std::find_if(DBinderStubRegisted_.begin(), DBinderStubRegisted_.end(), checkStub);
230     if (it != DBinderStubRegisted_.end()) {
231         return true;
232     }
233     return false;
234 }
235 
IsSameStubObject(const sptr<DBinderServiceStub> & stub,const std::u16string & service,const std::string & device)236 bool DBinderService::IsSameStubObject(const sptr<DBinderServiceStub> &stub, const std::u16string &service,
237     const std::string &device)
238 {
239     if (stub == nullptr) {
240         return false;
241     }
242     const std::string serviceStr8 = Str16ToStr8(service);
243     if (IsSameTextStr(stub->GetServiceName(), serviceStr8) && IsSameTextStr(stub->GetDeviceID(), device)) {
244         DBINDER_LOGI(LOG_LABEL, "found registered service, name:%{public}s device:%{public}s",
245             serviceStr8.c_str(), DBinderService::ConvertToSecureDeviceID(device).c_str());
246         return true;
247     }
248     return false;
249 }
250 
FindDBinderStub(const std::u16string & service,const std::string & device)251 sptr<DBinderServiceStub> DBinderService::FindDBinderStub(const std::u16string &service, const std::string &device)
252 {
253     auto checkStub = [&service, &device, this](const sptr<DBinderServiceStub> &stub) {
254         return IsSameStubObject(stub, service, device);
255     };
256 
257     std::lock_guard<std::mutex> lockGuard(handleEntryMutex_);
258     auto it = std::find_if(DBinderStubRegisted_.begin(), DBinderStubRegisted_.end(), checkStub);
259     if (it == DBinderStubRegisted_.end()) {
260         DBINDER_LOGW(LOG_LABEL, "not found, service:%{public}s device:%{public}s", Str16ToStr8(service).c_str(),
261             DBinderService::ConvertToSecureDeviceID(device).c_str());
262         return nullptr;
263     }
264     DBINDER_LOGD(LOG_LABEL, "found, service:%{public}s device:%{public}s", Str16ToStr8(service).c_str(),
265         DBinderService::ConvertToSecureDeviceID(device).c_str());
266     return (*it);
267 }
268 
DeleteDBinderStub(const std::u16string & service,const std::string & device)269 bool DBinderService::DeleteDBinderStub(const std::u16string &service, const std::string &device)
270 {
271     auto checkStub = [&service, &device, this](const sptr<DBinderServiceStub> &stub) {
272         return IsSameStubObject(stub, service, device);
273     };
274 
275     std::lock_guard<std::mutex> lockGuard(handleEntryMutex_);
276     auto it = std::find_if(DBinderStubRegisted_.begin(), DBinderStubRegisted_.end(), checkStub);
277     if (it == DBinderStubRegisted_.end()) {
278         DBINDER_LOGW(LOG_LABEL, "not found, service:%{public}s device:%{public}s", Str16ToStr8(service).c_str(),
279             DBinderService::ConvertToSecureDeviceID(device).c_str());
280         return false;
281     }
282 
283     for (auto mapIt = mapDBinderStubRegisters_.begin(); mapIt != mapDBinderStubRegisters_.end();) {
284         if (mapIt->second == reinterpret_cast<binder_uintptr_t>((*it).GetRefPtr())) {
285             mapIt = mapDBinderStubRegisters_.erase(mapIt);
286         } else {
287             ++mapIt;
288         }
289     }
290     DBinderStubRegisted_.erase(it);
291     DBINDER_LOGI(LOG_LABEL, "succ, service:%{public}s device:%{public}s", Str16ToStr8(service).c_str(),
292         DBinderService::ConvertToSecureDeviceID(device).c_str());
293     return true;
294 }
295 
FindOrNewDBinderStub(const std::u16string & service,const std::string & device,binder_uintptr_t binderObject)296 sptr<DBinderServiceStub> DBinderService::FindOrNewDBinderStub(const std::u16string &service, const std::string &device,
297     binder_uintptr_t binderObject)
298 {
299     auto checkStub = [&service, &device, this](const sptr<DBinderServiceStub> &stub) {
300         return IsSameStubObject(stub, service, device);
301     };
302 
303     std::lock_guard<std::mutex> lockGuard(handleEntryMutex_);
304     const std::string serviceStr8 = Str16ToStr8(service);
305     auto it = std::find_if(DBinderStubRegisted_.begin(), DBinderStubRegisted_.end(), checkStub);
306     if (it != DBinderStubRegisted_.end()) {
307         DBINDER_LOGD(LOG_LABEL, "found, service:%{public}s device:%{public}s", serviceStr8.c_str(),
308             DBinderService::ConvertToSecureDeviceID(device).c_str());
309         return (*it);
310     }
311 
312     sptr<DBinderServiceStub> dBinderServiceStub = new DBinderServiceStub(serviceStr8, device, binderObject);
313     DBinderStubRegisted_.push_back(dBinderServiceStub);
314     DBINDER_LOGD(LOG_LABEL, "create, service:%{public}s device:%{public}s", serviceStr8.c_str(),
315         DBinderService::ConvertToSecureDeviceID(device).c_str());
316     return dBinderServiceStub;
317 }
318 
FindOrNewConcurrentLockInfo(const sptr<DBinderServiceStub> & dBinderServiceStub,bool & isNew)319 std::shared_ptr<struct ThreadLockInfo> DBinderService::FindOrNewConcurrentLockInfo(
320     const sptr<DBinderServiceStub> &dBinderServiceStub, bool &isNew)
321 {
322     std::unique_lock<std::mutex> lockGuard(concurrentLockInfoMutex_);
323     binder_uintptr_t stub = reinterpret_cast<binder_uintptr_t>(dBinderServiceStub.GetRefPtr());
324     auto it = concurrentLockInfo_.find(stub);
325     if (it != concurrentLockInfo_.end()) {
326         return it->second;
327     }
328 
329     std::shared_ptr<struct ThreadLockInfo> info = std::make_shared<struct ThreadLockInfo>();
330     if (info == nullptr) {
331         DBINDER_LOGE(LOG_LABEL, "make_shared failed");
332         return info;
333     }
334     isNew = true;
335     concurrentLockInfo_.insert(std::make_pair(stub, info));
336     return info;
337 }
338 
MakeRemoteBinderInner(const sptr<DBinderServiceStub> & dBinderServiceStub,const std::u16string & serviceName,const std::string & deviceID,const uint32_t pid,const uint32_t uid)339 sptr<DBinderServiceStub> DBinderService::MakeRemoteBinderInner(const sptr<DBinderServiceStub> &dBinderServiceStub,
340     const std::u16string &serviceName, const std::string &deviceID, const uint32_t pid, const uint32_t uid)
341 {
342     binder_uintptr_t stub = reinterpret_cast<binder_uintptr_t>(dBinderServiceStub.GetRefPtr());
343     bool isNew = false;
344     auto threadLockInfo = FindOrNewConcurrentLockInfo(dBinderServiceStub, isNew);
345     if (threadLockInfo == nullptr) {
346         DBINDER_LOGE(LOG_LABEL, "FindOrNewConcurrentLockInfo is failed service:%{public}s device:%{public}s "
347             "refcount:%{public}d", Str16ToStr8(serviceName).c_str(),
348             DBinderService::ConvertToSecureDeviceID(deviceID).c_str(), dBinderServiceStub->GetSptrRefCount());
349         if (dBinderServiceStub->GetSptrRefCount() <= DBINDER_STUB_REF_COUNT) {
350             (void)DeleteDBinderStub(serviceName, deviceID);
351             (void)DetachSessionObject(stub);
352         }
353         return nullptr;
354     }
355     // Concurrent requests to the same SA of the same device.
356     if (!isNew) {
357         DBINDER_LOGI(LOG_LABEL, "Waiting for the same stub to complete chain building");
358         std::unique_lock<std::mutex> lock(threadLockInfo->mutex);
359         if (threadLockInfo->condition.wait_for(lock, std::chrono::seconds(INVOKER_NUMBER * WAIT_FOR_REPLY_MAX_SEC),
360             [&threadLockInfo] { return threadLockInfo->ready; }) == false) {
361             DBINDER_LOGE(LOG_LABEL, "Concurrent retrieval of remote data timeout or session closed.");
362             DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_WAIT_REPLY_TIMEOUT, __FUNCTION__);
363             threadLockInfo->ready = false;
364             return nullptr;
365         }
366         return dBinderServiceStub;
367     }
368 
369     int32_t retryTimes = 0;
370     int32_t ret = -1;
371     do {
372         ret = InvokerRemoteDBinder(dBinderServiceStub, GetSeqNumber(), pid, uid);
373         retryTimes++;
374     } while ((ret == WAIT_REPLY_TIMEOUT) && (retryTimes < RETRY_TIMES));
375 
376     if (ret != DBINDER_OK) {
377         DBINDER_LOGE(LOG_LABEL, "Failed to invoke service, service:%{public}s device:%{public}s "
378             "refcount:%{public}d", Str16ToStr8(serviceName).c_str(),
379             DBinderService::ConvertToSecureDeviceID(deviceID).c_str(), dBinderServiceStub->GetSptrRefCount());
380         WakeupConcurrentWaitingThread(stub, threadLockInfo, false);
381         if (dBinderServiceStub->GetSptrRefCount() <= DBINDER_STUB_REF_COUNT) {
382             /* invoke fail, delete dbinder stub info */
383             (void)DeleteDBinderStub(serviceName, deviceID);
384             (void)DetachSessionObject(stub);
385         }
386         return nullptr;
387     }
388     WakeupConcurrentWaitingThread(stub, threadLockInfo, true);
389     return dBinderServiceStub;
390 }
391 
MakeRemoteBinder(const std::u16string & serviceName,const std::string & deviceID,int32_t binderObject,uint32_t pid,uint32_t uid)392 sptr<DBinderServiceStub> DBinderService::MakeRemoteBinder(const std::u16string &serviceName,
393     const std::string &deviceID, int32_t binderObject, uint32_t pid, uint32_t uid)
394 {
395     if (IsDeviceIdIllegal(deviceID) || serviceName.length() == 0) {
396         DBINDER_LOGE(LOG_LABEL, "para is wrong, device length:%{public}zu, service length:%{public}zu",
397             deviceID.length(), serviceName.length());
398         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ERR_INVALID_DATA, __FUNCTION__);
399         return nullptr;
400     }
401     const std::string serviceNameStr8 = Str16ToStr8(serviceName);
402     DBINDER_LOGI(LOG_LABEL, "service:%{public}s device:%{public}s", serviceNameStr8.c_str(),
403         DBinderService::ConvertToSecureDeviceID(deviceID).c_str());
404     DfxReportDeviceEvent(DbinderErrorCode::RPC_DRIVER, DbinderErrorCode::IPC_RESULT_IDLE,
405         DBinderService::ConvertToSecureDeviceID(deviceID).c_str(), __FUNCTION__);
406 
407     sptr<DBinderServiceStub> dBinderServiceStub = FindOrNewDBinderStub(serviceName, deviceID,
408         static_cast<binder_uintptr_t>(binderObject));
409     if (dBinderServiceStub == nullptr) {
410         DBINDER_LOGE(LOG_LABEL, "FindOrNewDBinderStub fail, service:%{public}s", serviceNameStr8.c_str());
411         return nullptr;
412     }
413 
414     return MakeRemoteBinderInner(dBinderServiceStub, serviceName, deviceID, pid, uid);
415 }
416 
CheckDeviceIDsInvalid(const std::string & deviceID,const std::string & localDevID)417 bool DBinderService::CheckDeviceIDsInvalid(const std::string &deviceID, const std::string &localDevID)
418 {
419     if (IsDeviceIdIllegal(deviceID) || IsDeviceIdIllegal(localDevID)) {
420         DBINDER_LOGE(LOG_LABEL, "wrong device id length, remote:%{public}zu local:%{public}zu",
421             deviceID.length(), localDevID.length());
422         return true;
423     }
424     return false;
425 }
426 
CopyDeviceIDsToMessage(std::shared_ptr<struct DHandleEntryTxRx> message,const std::string & localDevID,const std::string & deviceID)427 bool DBinderService::CopyDeviceIDsToMessage(std::shared_ptr<struct DHandleEntryTxRx> message,
428     const std::string &localDevID, const std::string &deviceID)
429 {
430     if (memcpy_s(message->deviceIdInfo.fromDeviceId, DEVICEID_LENGTH, localDevID.data(), localDevID.length()) != 0 ||
431         memcpy_s(message->deviceIdInfo.toDeviceId, DEVICEID_LENGTH, deviceID.data(), deviceID.length()) != 0) {
432         DBINDER_LOGE(LOG_LABEL, "fail to copy memory, service:%{public}" PRIu64" seq:%{public}u",
433             message->stubIndex, message->seqNumber);
434         return false;
435     }
436     message->deviceIdInfo.fromDeviceId[localDevID.length()] = '\0';
437     message->deviceIdInfo.toDeviceId[deviceID.length()] = '\0';
438     return true;
439 }
440 
CreateMessage(const sptr<DBinderServiceStub> & stub,uint32_t seqNumber,uint32_t pid,uint32_t uid)441 std::shared_ptr<struct DHandleEntryTxRx> DBinderService::CreateMessage(const sptr<DBinderServiceStub> &stub,
442     uint32_t seqNumber, uint32_t pid, uint32_t uid)
443 {
444     auto message = std::make_shared<struct DHandleEntryTxRx>();
445     if (message == nullptr) {
446         DBINDER_LOGE(LOG_LABEL, "new DHandleEntryTxRx fail");
447         return nullptr;
448     }
449 
450     message->head.len = sizeof(DHandleEntryTxRx);
451     message->head.version = RPC_TOKENID_SUPPORT_VERSION;
452     message->dBinderCode = MESSAGE_AS_INVOKER;
453     message->transType = GetRemoteTransType();
454     message->fromPort = 0;
455     message->toPort = 0;
456     message->stubIndex = static_cast<uint64_t>(std::atoi(stub->GetServiceName().c_str()));
457     message->seqNumber = seqNumber;
458     message->binderObject = stub->GetBinderObject();
459     message->stub = AddStubByTag(reinterpret_cast<binder_uintptr_t>(stub.GetRefPtr()));
460     message->deviceIdInfo.tokenId = IPCSkeleton::GetCallingTokenID();
461     message->pid = pid;
462     message->uid = uid;
463 
464     return message;
465 }
466 
SendEntryToRemote(const sptr<DBinderServiceStub> stub,uint32_t seqNumber,uint32_t pid,uint32_t uid)467 bool DBinderService::SendEntryToRemote(const sptr<DBinderServiceStub> stub, uint32_t seqNumber, uint32_t pid,
468     uint32_t uid)
469 {
470     const std::string deviceID = stub->GetDeviceID();
471     const std::string localDevID = GetLocalDeviceID();
472     if (CheckDeviceIDsInvalid(deviceID, localDevID)) {
473         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ERR_INVALID_DATA, __FUNCTION__);
474         return false;
475     }
476 
477     auto message = CreateMessage(stub, seqNumber, pid, uid);
478     if (message == nullptr) {
479         return false;
480     }
481 
482     if (!CopyDeviceIDsToMessage(message, localDevID, deviceID)) {
483         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ERR_MEMCPY_DATA, __FUNCTION__);
484         return false;
485     }
486 
487     DBINDER_LOGI(LOG_LABEL, "pid:%{public}u uid:%{public}u seq:%{public}u stub:%{public}llu"
488         " tokenId:%{public}u", message->pid, message->uid, message->seqNumber,
489         (message->stub & BINDER_MASK), message->deviceIdInfo.tokenId);
490     std::shared_ptr<DBinderRemoteListener> remoteListener = GetRemoteListener();
491     if (remoteListener == nullptr) {
492         DBINDER_LOGE(LOG_LABEL, "remoteListener is null, service:%{public}" PRIu64 " seq:%{public}u",
493             message->stubIndex, message->seqNumber);
494         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_GET_REMOTE_LISTENER_FAIL, __FUNCTION__);
495         return false;
496     }
497     bool result = remoteListener->SendDataToRemote(deviceID, message.get());
498     if (result != true) {
499         DBINDER_LOGE(LOG_LABEL, "SendDataToRemote failed, service:%{public}" PRIu64" seq:%{public}u",
500             message->stubIndex, message->seqNumber);
501         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_SEND_DATA_TO_REMOTE_FAIL, __FUNCTION__);
502         return false;
503     }
504     return true;
505 }
506 
InvokerRemoteDBinder(const sptr<DBinderServiceStub> stub,uint32_t seqNumber,uint32_t pid,uint32_t uid)507 int32_t DBinderService::InvokerRemoteDBinder(const sptr<DBinderServiceStub> stub, uint32_t seqNumber,
508     uint32_t pid, uint32_t uid)
509 {
510     if (stub == nullptr) {
511         DBINDER_LOGE(LOG_LABEL, "stub is nullptr");
512         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ERR_INVALID_DATA, __FUNCTION__);
513         return STUB_INVALID;
514     }
515 
516     bool result = SendEntryToRemote(stub, seqNumber, pid, uid);
517     if (!result) {
518         DBINDER_LOGE(LOG_LABEL, "SendEntryToRemote fail, seq:%{public}u", seqNumber);
519         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_SEND_ENTRY_TO_REMOTE_FAIL, __FUNCTION__);
520         return SEND_MESSAGE_FAILED;
521     }
522 
523     /* pend to wait reply */
524     std::shared_ptr<struct ThreadLockInfo> threadLockInfo = std::make_shared<struct ThreadLockInfo>();
525     result = AttachThreadLockInfo(seqNumber, stub->GetDeviceID(), threadLockInfo);
526     if (result != true) {
527         DBINDER_LOGE(LOG_LABEL, "AttachThreadLockInfo fail, seq:%{public}u", seqNumber);
528         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ATTACH_THREADLOCK_FAIL, __FUNCTION__);
529         return MAKE_THREADLOCK_FAILED;
530     }
531     std::unique_lock<std::mutex> lock(threadLockInfo->mutex);
532     if (threadLockInfo->condition.wait_for(lock, std::chrono::seconds(WAIT_FOR_REPLY_MAX_SEC),
533         [&threadLockInfo] { return threadLockInfo->ready; }) == false) {
534         DBINDER_LOGE(LOG_LABEL, "get remote data timeout or ssession is closed, seq:%{public}u", seqNumber);
535         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_WAIT_REPLY_TIMEOUT, __FUNCTION__);
536         DetachThreadLockInfo(seqNumber);
537         threadLockInfo->ready = false;
538         return WAIT_REPLY_TIMEOUT;
539     }
540     /* if can not find session, means invoke failed or nothing in OnRemoteReplyMessage() */
541     auto session = QuerySessionObject(reinterpret_cast<binder_uintptr_t>(stub.GetRefPtr()));
542     if (session == nullptr) {
543         DBINDER_LOGE(LOG_LABEL, "client find session is null, seq:%{public}u", seqNumber);
544         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_QUERY_REPLY_SESSION_FAIL, __FUNCTION__);
545         return QUERY_REPLY_SESSION_FAILED;
546     }
547     return DBINDER_OK;
548 }
549 
CheckSystemAbilityId(int32_t systemAbilityId)550 bool DBinderService::CheckSystemAbilityId(int32_t systemAbilityId)
551 {
552     return systemAbilityId >= FIRST_SYS_ABILITY_ID && systemAbilityId <= LAST_SYS_ABILITY_ID;
553 }
554 
AllocFreeSocketPort()555 uint16_t DBinderService::AllocFreeSocketPort()
556 {
557     /* alloc port by system */
558     return 0;
559 }
560 
IsSameLoadSaItem(const std::string & srcNetworkId,int32_t systemAbilityId,std::shared_ptr<DHandleEntryTxRx> loadSaItem)561 bool DBinderService::IsSameLoadSaItem(const std::string& srcNetworkId, int32_t systemAbilityId,
562     std::shared_ptr<DHandleEntryTxRx> loadSaItem)
563 {
564     if (static_cast<int32_t>(loadSaItem->stubIndex) == systemAbilityId &&
565         loadSaItem->deviceIdInfo.fromDeviceId == srcNetworkId) {
566         DBINDER_LOGI(LOG_LABEL, "match succeed");
567         return true;
568     }
569     return false;
570 }
571 
PopLoadSaItem(const std::string & srcNetworkId,int32_t systemAbilityId)572 std::shared_ptr<DHandleEntryTxRx> DBinderService::PopLoadSaItem(const std::string& srcNetworkId,
573     int32_t systemAbilityId)
574 {
575     auto checkSaItem = [srcNetworkId, systemAbilityId, this](std::shared_ptr<DHandleEntryTxRx> loadSaItem) {
576         return IsSameLoadSaItem(srcNetworkId, systemAbilityId, loadSaItem);
577     };
578 
579     std::lock_guard<std::shared_mutex> lockGuard(loadSaMutex_);
580     auto it = std::find_if(loadSaReply_.begin(), loadSaReply_.end(), checkSaItem);
581     if (it == loadSaReply_.end()) {
582         DBINDER_LOGI(LOG_LABEL, "no msg for saId:%{public}d, deviceId:%{public}s",
583             systemAbilityId, DBinderService::ConvertToSecureDeviceID(srcNetworkId).c_str());
584         return nullptr;
585     }
586     std::shared_ptr<DHandleEntryTxRx> replymsg = (*it);
587     it = loadSaReply_.erase(it);
588     return replymsg;
589 }
590 
LoadSystemAbilityComplete(const std::string & srcNetworkId,int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)591 void DBinderService::LoadSystemAbilityComplete(const std::string& srcNetworkId, int32_t systemAbilityId,
592     const sptr<IRemoteObject>& remoteObject)
593 {
594     while (true) {
595         std::shared_ptr<struct DHandleEntryTxRx> replyMessage = PopLoadSaItem(srcNetworkId, systemAbilityId);
596         if (replyMessage == nullptr) {
597             break;
598         }
599         if (remoteObject == nullptr) {
600             SendReplyMessageToRemote(MESSAGE_AS_REMOTE_ERROR, SA_NOT_FOUND, replyMessage);
601             DBINDER_LOGE(LOG_LABEL, "GetSystemAbility from samgr error, saId:%{public}d", systemAbilityId);
602             continue;
603         }
604         binder_uintptr_t binderObject = replyMessage->binderObject;
605         IPCObjectProxy *saProxy = reinterpret_cast<IPCObjectProxy *>(remoteObject.GetRefPtr());
606         if (QueryProxyObject(binderObject) == nullptr) {
607             /* When the stub object dies, you need to delete the corresponding busName information */
608             sptr<IRemoteObject::DeathRecipient> death(new DbinderSaDeathRecipient(binderObject));
609             if (!saProxy->AddDeathRecipient(death)) {
610                 SendReplyMessageToRemote(MESSAGE_AS_REMOTE_ERROR, SA_NOT_FOUND, replyMessage);
611                 DBINDER_LOGE(LOG_LABEL, "fail to add death recipient");
612                 DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ADD_DEATH_RECIPIENT_FAIL, __FUNCTION__);
613                 continue;
614             }
615             if (!AttachProxyObject(remoteObject, binderObject)) {
616                 DBINDER_LOGW(LOG_LABEL, "attach proxy object is already existed");
617             }
618         }
619         std::string deviceId = replyMessage->deviceIdInfo.fromDeviceId;
620         if (replyMessage->transType != IRemoteObject::DATABUS_TYPE) {
621             SendReplyMessageToRemote(MESSAGE_AS_REMOTE_ERROR, SA_INVOKE_FAILED, replyMessage);
622             DBINDER_LOGE(LOG_LABEL, "Invalid Message Type");
623             DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ERR_INVALID_DATA, __FUNCTION__);
624         } else {
625             // peer device rpc version == 1, not support thokenId and message->deviceIdInfo.tokenId is random value
626             uint32_t tokenId = (replyMessage->head.version < RPC_TOKENID_SUPPORT_VERSION) ?
627                 0 : replyMessage->deviceIdInfo.tokenId;
628             uint32_t result = OnRemoteInvokerDataBusMessage(saProxy, replyMessage, deviceId,
629                 replyMessage->pid, replyMessage->uid, tokenId);
630             if (result != 0) {
631                 SendReplyMessageToRemote(MESSAGE_AS_REMOTE_ERROR, result, replyMessage);
632                 continue;
633             }
634             SendReplyMessageToRemote(MESSAGE_AS_REPLY, 0, replyMessage);
635         }
636     }
637     DBINDER_LOGI(LOG_LABEL, "LoadSystemAbility complete");
638 }
639 
SendReplyMessageToRemote(uint32_t dBinderCode,uint32_t reason,std::shared_ptr<struct DHandleEntryTxRx> replyMessage)640 void DBinderService::SendReplyMessageToRemote(uint32_t dBinderCode, uint32_t reason,
641     std::shared_ptr<struct DHandleEntryTxRx> replyMessage)
642 {
643     std::shared_ptr<DBinderRemoteListener> remoteListener = GetRemoteListener();
644     if (remoteListener == nullptr) {
645         DBINDER_LOGE(LOG_LABEL, "remoteListener is null");
646         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_GET_REMOTE_LISTENER_FAIL, __FUNCTION__);
647         return;
648     }
649     replyMessage->dBinderCode = dBinderCode;
650     if (dBinderCode == MESSAGE_AS_REMOTE_ERROR) {
651         replyMessage->transType = reason; // reuse transType send back error code
652     }
653     if (!remoteListener->SendDataReply(replyMessage->deviceIdInfo.fromDeviceId, replyMessage.get())) {
654         DBINDER_LOGE(LOG_LABEL, "fail to send data from server DBS to client DBS");
655         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_SEND_DATA_REPLAY_FAIL, __FUNCTION__);
656     }
657 }
658 
CheckAndAmendSaId(std::shared_ptr<struct DHandleEntryTxRx> message)659 bool DBinderService::CheckAndAmendSaId(std::shared_ptr<struct DHandleEntryTxRx> message)
660 {
661     bool ret = true;
662     int32_t stubIndex = static_cast<int32_t>(message->stubIndex);
663     int32_t binderObject = static_cast<int32_t>(message->binderObject);
664     bool stubIndexVaild = CheckSystemAbilityId(stubIndex);
665     bool binderObjectVaild = CheckSystemAbilityId(binderObject);
666     if (stubIndexVaild && binderObjectVaild) {
667         if (stubIndex != binderObject) {
668             DBINDER_LOGW(LOG_LABEL, "stubIndex(%{public}d) != binderObject(%{public}d), update said:%{public}d",
669                 stubIndex, binderObject, stubIndex);
670             message->binderObject = message->stubIndex;
671         }
672     } else if (stubIndexVaild && !binderObjectVaild) {
673         DBINDER_LOGI(LOG_LABEL, "update said, replace binderObject:%{public}d with stubIndex:%{public}d",
674             binderObject, stubIndex);
675         message->binderObject = message->stubIndex;
676     } else if (!stubIndexVaild && binderObjectVaild) {
677         DBINDER_LOGI(LOG_LABEL, "update said, replace stubIndex:%{public}d with binderObject:%{public}d",
678             stubIndex, binderObject);
679         message->stubIndex = message->binderObject;
680     } else {
681         DBINDER_LOGE(LOG_LABEL, "invalid said, stubIndex:%{public}d binderObject:%{public}d",
682             stubIndex, binderObject);
683         ret = false;
684     }
685     return ret;
686 }
687 
OnRemoteInvokerMessage(std::shared_ptr<struct DHandleEntryTxRx> message)688 bool DBinderService::OnRemoteInvokerMessage(std::shared_ptr<struct DHandleEntryTxRx> message)
689 {
690     if (!CheckAndAmendSaId(message)) {
691         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_INVALID_SAID, __FUNCTION__);
692         SendReplyMessageToRemote(MESSAGE_AS_REMOTE_ERROR, SAID_INVALID_ERR, message);
693         return false;
694     }
695 
696     DBINDER_LOGI(LOG_LABEL,
697         "invoke business service:%{public}d seq:%{public}u stub:%{public}llu tokenId:%{public}u",
698         static_cast<int32_t>(message->stubIndex), message->seqNumber,
699         (message->stub & BINDER_MASK), message->deviceIdInfo.tokenId);
700     if (!dbinderCallback_->IsDistributedSystemAbility(message->binderObject)) {
701         DBINDER_LOGE(LOG_LABEL, "SA:%{public}llu not have distributed capability.", message->binderObject);
702         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_NOT_DISTEIBUTED_SA, __FUNCTION__);
703         SendReplyMessageToRemote(MESSAGE_AS_REMOTE_ERROR, SA_NOT_DISTRUBUTED_ERR, message);
704         return false;
705     }
706 
707     std::shared_ptr<DHandleEntryTxRx> replyMessage = message;
708     {
709         std::lock_guard<std::shared_mutex> lockGuard(loadSaMutex_);
710         loadSaReply_.push_back(replyMessage);
711     }
712     bool isSaAvailable = dbinderCallback_->LoadSystemAbilityFromRemote(replyMessage->deviceIdInfo.fromDeviceId,
713         static_cast<int32_t>(replyMessage->stubIndex));
714     if (!isSaAvailable) {
715         DBINDER_LOGE(LOG_LABEL, "fail to call the system ability:%{public}d",
716             static_cast<int32_t>(replyMessage->stubIndex));
717         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_CALL_SYSTEM_ABILITY_FAIL, __FUNCTION__);
718         PopLoadSaItem(replyMessage->deviceIdInfo.fromDeviceId, static_cast<int32_t>(replyMessage->stubIndex));
719         SendReplyMessageToRemote(MESSAGE_AS_REMOTE_ERROR, SA_NOT_AVAILABLE, replyMessage);
720         return false;
721     }
722 
723     return true;
724 }
725 
GetDatabusNameByProxy(IPCObjectProxy * proxy)726 std::string DBinderService::GetDatabusNameByProxy(IPCObjectProxy *proxy)
727 {
728     if (proxy == nullptr) {
729         DBINDER_LOGE(LOG_LABEL, "proxy can not be null");
730         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ERR_INVALID_DATA, __FUNCTION__);
731         return "";
732     }
733     std::string sessionName = proxy->GetSessionName();
734     if (sessionName.empty()) {
735         DBINDER_LOGE(LOG_LABEL, "grand session name failed");
736         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_GRT_SESSION_NAME_FAIL, __FUNCTION__);
737         return "";
738     }
739     DBINDER_LOGD(LOG_LABEL, "succ, handle:%{public}d sessionName:%{public}s",
740         proxy->GetHandle(), sessionName.c_str());
741     return sessionName;
742 }
743 
CreateDatabusName(int uid,int pid)744 std::string DBinderService::CreateDatabusName(int uid, int pid)
745 {
746     std::string sessionName = "DBinder" + std::to_string(uid) + std::string("_") + std::to_string(pid);
747     if (DBinderSoftbusClient::GetInstance().DBinderGrantPermission(uid, pid, sessionName) != ERR_NONE) {
748         DBINDER_LOGE(LOG_LABEL, "fail to Grant Permission softbus name");
749         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_GRANT_PERMISSION_FAIL, __FUNCTION__);
750         return "";
751     }
752 
753     return sessionName;
754 }
755 
CheckDeviceIdIllegal(const std::string & remoteDeviceId)756 bool DBinderService::CheckDeviceIdIllegal(const std::string &remoteDeviceId)
757 {
758     if (IsDeviceIdIllegal(remoteDeviceId)) {
759         DBINDER_LOGE(LOG_LABEL, "remote device id is error");
760         return true;
761     }
762     return false;
763 }
764 
CheckSessionNameIsEmpty(const std::string & sessionName)765 bool DBinderService::CheckSessionNameIsEmpty(const std::string &sessionName)
766 {
767     if (sessionName.empty()) {
768         DBINDER_LOGE(LOG_LABEL, "get bus name fail");
769         return true;
770     }
771     return false;
772 }
773 
CheckInvokeListenThreadIllegal(IPCObjectProxy * proxy,MessageParcel & data,MessageParcel & reply)774 bool DBinderService::CheckInvokeListenThreadIllegal(IPCObjectProxy *proxy, MessageParcel &data, MessageParcel &reply)
775 {
776     int err = proxy->InvokeListenThread(data, reply);
777     if (err != ERR_NONE) {
778         DBINDER_LOGE(LOG_LABEL, "start service listen error:%{public}d handle:%{public}d", err, proxy->GetHandle());
779         return true;
780     }
781     return false;
782 }
783 
CheckStubIndexAndSessionNameIllegal(uint64_t stubIndex,const std::string & serverSessionName,const std::string & deviceId,IPCObjectProxy * proxy)784 bool DBinderService::CheckStubIndexAndSessionNameIllegal(uint64_t stubIndex, const std::string &serverSessionName,
785     const std::string &deviceId, IPCObjectProxy *proxy)
786 {
787     if (stubIndex == 0 || serverSessionName.empty() || serverSessionName.length() > SERVICENAME_LENGTH) {
788         DBINDER_LOGE(LOG_LABEL, "stubindex:%{public}" PRIu64 " or sessionName:%{public}s is invalid"
789             " handle:%{public}d deviceId:%{public}s", stubIndex, serverSessionName.c_str(), proxy->GetHandle(),
790             DBinderService::ConvertToSecureDeviceID(deviceId).c_str());
791         return true;
792     }
793     return false;
794 }
795 
SetReplyMessage(std::shared_ptr<struct DHandleEntryTxRx> replyMessage,uint64_t stubIndex,const std::string & serverSessionName,uint32_t selfTokenId,IPCObjectProxy * proxy)796 bool DBinderService::SetReplyMessage(std::shared_ptr<struct DHandleEntryTxRx> replyMessage, uint64_t stubIndex,
797     const std::string &serverSessionName, uint32_t selfTokenId, IPCObjectProxy *proxy)
798 {
799     replyMessage->dBinderCode = MESSAGE_AS_REPLY;
800     if (replyMessage->head.version >= RPC_TOKENID_SUPPORT_VERSION) {
801         replyMessage->dBinderCode = MESSAGE_AS_REPLY_TOKENID;
802     }
803     replyMessage->head.version = RPC_TOKENID_SUPPORT_VERSION;
804     replyMessage->stubIndex = stubIndex;
805     replyMessage->serviceNameLength = serverSessionName.length();
806     replyMessage->deviceIdInfo.tokenId = selfTokenId;
807     if (memcpy_s(replyMessage->serviceName, SERVICENAME_LENGTH, serverSessionName.data(),
808         replyMessage->serviceNameLength) != 0) {
809         DBINDER_LOGE(LOG_LABEL, "memcpy serviceName fail, handle:%{public}d", proxy->GetHandle());
810         return false;
811     }
812     replyMessage->serviceName[replyMessage->serviceNameLength] = '\0';
813     return true;
814 }
815 
OnRemoteInvokerDataBusMessage(IPCObjectProxy * proxy,std::shared_ptr<struct DHandleEntryTxRx> replyMessage,std::string & remoteDeviceId,int pid,int uid,uint32_t tokenId)816 uint32_t DBinderService::OnRemoteInvokerDataBusMessage(IPCObjectProxy *proxy,
817     std::shared_ptr<struct DHandleEntryTxRx> replyMessage,
818     std::string &remoteDeviceId, int pid, int uid, uint32_t tokenId)
819 {
820     if (CheckDeviceIdIllegal(remoteDeviceId)) {
821         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ERR_INVALID_DATA, __FUNCTION__);
822         return DEVICEID_INVALID;
823     }
824     std::string sessionName = GetDatabusNameByProxy(proxy);
825     if (CheckSessionNameIsEmpty(sessionName)) {
826         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_GET_BUS_NAME_FAIL, __FUNCTION__);
827         return SESSION_NAME_NOT_FOUND;
828     }
829 
830     MessageParcel data;
831     MessageParcel reply;
832     if (!data.WriteUint16(IRemoteObject::DATABUS_TYPE) || !data.WriteString(GetLocalDeviceID()) ||
833         !data.WriteUint32(pid) || !data.WriteUint32(uid) || !data.WriteString(remoteDeviceId) ||
834         !data.WriteString(sessionName) || !data.WriteUint32(tokenId)) {
835         DBINDER_LOGE(LOG_LABEL, "write to parcel fail, handle:%{public}d", proxy->GetHandle());
836         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, proxy->GetHandle(),
837             RADAR_WRITE_PARCEL_FAIL, __FUNCTION__);
838         return WRITE_PARCEL_FAILED;
839     }
840     if (CheckInvokeListenThreadIllegal(proxy, data, reply)) {
841         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, proxy->GetHandle(),
842             RADAR_INVOKE_STUB_THREAD_FAIL, __FUNCTION__);
843         return INVOKE_STUB_THREAD_FAILED;
844     }
845 
846     uint64_t stubIndex = reply.ReadUint64();
847     std::string serverSessionName = reply.ReadString();
848     std::string deviceId = reply.ReadString();
849     uint32_t selfTokenId = reply.ReadUint32();
850     if (CheckStubIndexAndSessionNameIllegal(stubIndex, serverSessionName, deviceId, proxy)) {
851         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, proxy->GetHandle(),
852             RADAR_SESSION_NAME_INVALID, __FUNCTION__);
853         return SESSION_NAME_INVALID;
854     }
855     if (!SetReplyMessage(replyMessage, stubIndex, serverSessionName, selfTokenId, proxy)) {
856         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, proxy->GetHandle(), RADAR_ERR_MEMCPY_DATA, __FUNCTION__);
857         return SESSION_NAME_INVALID;
858     }
859     return 0;
860 }
861 
GetRegisterService(binder_uintptr_t binderObject)862 std::u16string DBinderService::GetRegisterService(binder_uintptr_t binderObject)
863 {
864     std::shared_lock<std::shared_mutex> lockGuard(remoteBinderMutex_);
865     for (auto it = mapRemoteBinderObjects_.begin(); it != mapRemoteBinderObjects_.end(); it++) {
866         if (it->second == binderObject) {
867             DBINDER_LOGI(LOG_LABEL, "get service:%{public}s", Str16ToStr8(it->first).c_str());
868             return it->first;
869         }
870     }
871     return std::u16string();
872 }
873 
RegisterRemoteProxy(std::u16string serviceName,sptr<IRemoteObject> binderObject)874 bool DBinderService::RegisterRemoteProxy(std::u16string serviceName, sptr<IRemoteObject> binderObject)
875 {
876     if (serviceName.length() == 0 || binderObject == nullptr) {
877         DBINDER_LOGE(LOG_LABEL, "serviceName length:%{public}zu", serviceName.length());
878         return false;
879     }
880 
881     DBINDER_LOGI(LOG_LABEL, "service name:%{public}s", Str16ToStr8(serviceName).c_str());
882     binder_uintptr_t binder = (binder_uintptr_t)binderObject.GetRefPtr();
883     return RegisterRemoteProxyInner(serviceName, binder);
884 }
885 
RegisterRemoteProxy(std::u16string serviceName,int32_t systemAbilityId)886 bool DBinderService::RegisterRemoteProxy(std::u16string serviceName, int32_t systemAbilityId)
887 {
888     if (serviceName.length() == 0 || systemAbilityId <= 0) {
889         DBINDER_LOGE(LOG_LABEL, "serviceName length:%{public}zu", serviceName.length());
890         return false;
891     }
892     DBINDER_LOGI(LOG_LABEL, "service name:%{public}s saId:%{public}d",
893         Str16ToStr8(serviceName).c_str(), systemAbilityId);
894     binder_uintptr_t binder = (binder_uintptr_t)systemAbilityId;
895     return RegisterRemoteProxyInner(serviceName, binder);
896 }
897 
RegisterRemoteProxyInner(std::u16string serviceName,binder_uintptr_t binder)898 bool DBinderService::RegisterRemoteProxyInner(std::u16string serviceName, binder_uintptr_t binder)
899 {
900     std::unique_lock<std::shared_mutex> lockGuard(remoteBinderMutex_);
901     // clear historical remnants, Don't care if it succeeds
902     (void)mapRemoteBinderObjects_.erase(serviceName);
903     auto result = mapRemoteBinderObjects_.insert(std::pair<std::u16string, binder_uintptr_t>(serviceName, binder));
904     return result.second;
905 }
906 
AddAsynMessageTask(std::shared_ptr<struct DHandleEntryTxRx> message)907 void DBinderService::AddAsynMessageTask(std::shared_ptr<struct DHandleEntryTxRx> message)
908 {
909     sptr<DBinderService> servicePtr = this;
910     auto task = [servicePtr, message] {
911         if (servicePtr == nullptr) {
912             DBINDER_LOGE(LOG_LABEL, "invalid dbinder service object");
913             return;
914         }
915         servicePtr->OnRemoteMessageTask(message);
916     };
917     ffrt::submit(task);
918 }
919 
OnRemoteMessageTask(std::shared_ptr<struct DHandleEntryTxRx> message)920 bool DBinderService::OnRemoteMessageTask(std::shared_ptr<struct DHandleEntryTxRx> message)
921 {
922     if (message == nullptr) {
923         DBINDER_LOGE(LOG_LABEL, "message is null");
924         return false;
925     }
926 
927     bool result = false;
928     switch (message->dBinderCode) {
929         case MESSAGE_AS_INVOKER: {
930             result = OnRemoteInvokerMessage(message);
931             break;
932         }
933         case MESSAGE_AS_REPLY:
934         case MESSAGE_AS_REPLY_TOKENID: {
935             result = OnRemoteReplyMessage(message);
936             break;
937         }
938         case MESSAGE_AS_REMOTE_ERROR: {
939             result = OnRemoteErrorMessage(message);
940             break;
941         }
942         default: {
943             DBINDER_LOGE(LOG_LABEL, "DbinderCode:%{public}u is not support", message->dBinderCode);
944             result = false;
945             break;
946         }
947     }
948     return result;
949 }
950 
ProcessOnSessionClosed(const std::string & networkId)951 bool DBinderService::ProcessOnSessionClosed(const std::string &networkId)
952 {
953     std::lock_guard<std::mutex> lock(threadLockMutex_);
954     for (auto it = threadLockInfo_.begin(); it != threadLockInfo_.end();) {
955         if (it->second->networkId != networkId) {
956             it++;
957             continue;
958         }
959         std::unique_lock<std::mutex> lock(it->second->mutex);
960         it->second->ready = false;
961         it->second->condition.notify_all();
962         it = threadLockInfo_.erase(it);
963     }
964     return true;
965 }
966 
OnRemoteErrorMessage(std::shared_ptr<struct DHandleEntryTxRx> replyMessage)967 bool DBinderService::OnRemoteErrorMessage(std::shared_ptr<struct DHandleEntryTxRx> replyMessage)
968 {
969     DfxReportEvent(DbinderErrorCode::RPC_DRIVER, DbinderErrorCode::IPC_RESULT_IDLE, __FUNCTION__);
970     DBINDER_LOGI(LOG_LABEL, "invoke remote stubIndex:%{public}d fail, error:%{public}u seq:%{public}u",
971         static_cast<int32_t>(replyMessage->stubIndex), replyMessage->transType, replyMessage->seqNumber);
972     WakeupThreadByStub(replyMessage->seqNumber);
973     DetachThreadLockInfo(replyMessage->seqNumber);
974     return true;
975 }
976 
OnRemoteReplyMessage(std::shared_ptr<struct DHandleEntryTxRx> replyMessage)977 bool DBinderService::OnRemoteReplyMessage(std::shared_ptr<struct DHandleEntryTxRx> replyMessage)
978 {
979     DBINDER_LOGI(LOG_LABEL, "invoker remote stubIndex:%{public}d succ, seq:%{public}u stub:%{public}llu "
980         "tokenId:%{public}u dBinderCode:%{public}u", static_cast<int32_t>(replyMessage->stubIndex),
981         replyMessage->seqNumber, (replyMessage->stub & BINDER_MASK), replyMessage->deviceIdInfo.tokenId,
982         replyMessage->dBinderCode);
983     MakeSessionByReplyMessage(replyMessage);
984     WakeupThreadByStub(replyMessage->seqNumber);
985     DetachThreadLockInfo(replyMessage->seqNumber);
986     return true;
987 }
988 
IsSameSession(std::shared_ptr<struct SessionInfo> oldSession,std::shared_ptr<struct SessionInfo> newSession)989 bool DBinderService::IsSameSession(std::shared_ptr<struct SessionInfo> oldSession,
990     std::shared_ptr<struct SessionInfo> newSession)
991 {
992     if ((oldSession->stubIndex != newSession->stubIndex) || (oldSession->toPort != newSession->toPort)
993         || (oldSession->fromPort != newSession->fromPort) || (oldSession->type != newSession->type)
994         || (oldSession->serviceName != newSession->serviceName)) {
995         return false;
996     }
997     if (strncmp(oldSession->deviceIdInfo.fromDeviceId, newSession->deviceIdInfo.fromDeviceId, DEVICEID_LENGTH) != 0
998         || strncmp(oldSession->deviceIdInfo.toDeviceId, newSession->deviceIdInfo.toDeviceId, DEVICEID_LENGTH) != 0) {
999         return false;
1000     }
1001 
1002     return true;
1003 }
1004 
IsInvalidStub(std::shared_ptr<struct DHandleEntryTxRx> replyMessage)1005 bool DBinderService::IsInvalidStub(std::shared_ptr<struct DHandleEntryTxRx> replyMessage)
1006 {
1007     if (HasDBinderStub(QueryStubPtr(replyMessage->stub)) == false) {
1008         DBINDER_LOGE(LOG_LABEL, "invalid stub object");
1009         return true;
1010     }
1011     return false;
1012 }
1013 
CopyDeviceIdInfo(std::shared_ptr<struct SessionInfo> & session,std::shared_ptr<struct DHandleEntryTxRx> replyMessage)1014 bool DBinderService::CopyDeviceIdInfo(std::shared_ptr<struct SessionInfo> &session,
1015     std::shared_ptr<struct DHandleEntryTxRx> replyMessage)
1016 {
1017     if (memcpy_s(&session->deviceIdInfo, sizeof(struct DeviceIdInfo), &replyMessage->deviceIdInfo,
1018         sizeof(struct DeviceIdInfo)) != 0) {
1019         DBINDER_LOGE(LOG_LABEL, "fail to copy memory");
1020         return false;
1021     }
1022     return true;
1023 }
1024 
InitializeSession(std::shared_ptr<struct SessionInfo> & session,std::shared_ptr<struct DHandleEntryTxRx> replyMessage)1025 void DBinderService::InitializeSession(std::shared_ptr<struct SessionInfo> &session,
1026     std::shared_ptr<struct DHandleEntryTxRx> replyMessage)
1027 {
1028     session->seqNumber   = replyMessage->seqNumber;
1029     session->socketFd    = 0;
1030     session->stubIndex   = replyMessage->stubIndex;
1031     session->toPort      = replyMessage->toPort;
1032     session->fromPort    = replyMessage->fromPort;
1033     session->type        = replyMessage->transType;
1034     session->serviceName = replyMessage->serviceName;
1035 }
1036 
MakeSessionByReplyMessage(std::shared_ptr<struct DHandleEntryTxRx> replyMessage)1037 void DBinderService::MakeSessionByReplyMessage(std::shared_ptr<struct DHandleEntryTxRx> replyMessage)
1038 {
1039     if (IsInvalidStub(replyMessage)) {
1040         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_STUB_INVALID, __FUNCTION__);
1041         return;
1042     }
1043 
1044     std::shared_ptr<struct SessionInfo> session = std::make_shared<struct SessionInfo>();
1045     if (session == nullptr) {
1046         DBINDER_LOGE(LOG_LABEL, "new SessionInfo fail");
1047         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_IPC_NEW_SESSION_FAIL, __FUNCTION__);
1048         return;
1049     }
1050 
1051     if (!CopyDeviceIdInfo(session, replyMessage)) {
1052         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ERR_MEMCPY_DATA, __FUNCTION__);
1053         return;
1054     }
1055     // remote device NOT support tokenId, clear random value
1056     if (replyMessage->dBinderCode == MESSAGE_AS_REPLY) {
1057         session->deviceIdInfo.tokenId = 0;
1058     }
1059     DBINDER_LOGI(LOG_LABEL, "stubIndex:%{public}d tokenId:%{public}u",
1060         static_cast<int32_t>(replyMessage->stubIndex), session->deviceIdInfo.tokenId);
1061     InitializeSession(session, replyMessage);
1062 
1063     if (session->stubIndex == 0) {
1064         DBINDER_LOGE(LOG_LABEL, "get stubIndex == 0, it is invalid");
1065         return;
1066     }
1067     // check whether need to update session
1068     std::shared_ptr<struct SessionInfo> oldSession = QuerySessionObject(QueryStubPtr(replyMessage->stub));
1069     if (oldSession != nullptr) {
1070         if (IsSameSession(oldSession, session) == true) {
1071             DBINDER_LOGI(LOG_LABEL, "invoker remote session already, do nothing");
1072             return;
1073         }
1074         // ignore seqNumber overflow here, greater seqNumber means later request
1075         if (oldSession->seqNumber < session->seqNumber) {
1076             // remote old session
1077             if (!DetachSessionObject(QueryStubPtr(replyMessage->stub))) {
1078                 DBINDER_LOGE(LOG_LABEL, "failed to detach session object");
1079                 DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_DETACH_SESSION_FAIL, __FUNCTION__);
1080             }
1081         } else {
1082             // do nothing, use old session, discard session got this time
1083             // in this case, old session is requested later, but it comes back earlier
1084         }
1085     }
1086 
1087     if (!AttachSessionObject(session, QueryStubPtr(replyMessage->stub))) {
1088         DBINDER_LOGE(LOG_LABEL, "attach SessionInfo fail");
1089         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ATTACH_SESSION_FAIL, __FUNCTION__);
1090         return;
1091     }
1092 }
1093 
WakeupThreadByStub(uint32_t seqNumber)1094 void DBinderService::WakeupThreadByStub(uint32_t seqNumber)
1095 {
1096     std::shared_ptr<struct ThreadLockInfo> threadLockInfo = QueryThreadLockInfo(seqNumber);
1097     if (threadLockInfo == nullptr) {
1098         DBINDER_LOGE(LOG_LABEL, "threadLockInfo is not exist");
1099         return;
1100     }
1101     /* Wake up the client processing thread */
1102     std::unique_lock<std::mutex> lock(threadLockInfo->mutex);
1103     threadLockInfo->ready = true;
1104     threadLockInfo->condition.notify_all();
1105 }
1106 
WakeupConcurrentWaitingThread(const binder_uintptr_t stub,std::shared_ptr<struct ThreadLockInfo> & lockInfo,bool isNegotiationSuccessful)1107 void DBinderService::WakeupConcurrentWaitingThread(
1108     const binder_uintptr_t stub, std::shared_ptr<struct ThreadLockInfo> &lockInfo, bool isNegotiationSuccessful)
1109 {
1110     std::unique_lock<std::mutex> lockGuard(concurrentLockInfoMutex_);
1111     {
1112         std::unique_lock<std::mutex> lock(lockInfo->mutex);
1113         lockInfo->ready = isNegotiationSuccessful;
1114         lockInfo->condition.notify_all();
1115     }
1116     concurrentLockInfo_.erase(stub);
1117 }
1118 
DetachThreadLockInfo(uint32_t seqNumber)1119 void DBinderService::DetachThreadLockInfo(uint32_t seqNumber)
1120 {
1121     std::lock_guard<std::mutex> lock(threadLockMutex_);
1122     threadLockInfo_.erase(seqNumber);
1123 }
1124 
AttachThreadLockInfo(uint32_t seqNumber,const std::string & networkId,std::shared_ptr<struct ThreadLockInfo> object)1125 bool DBinderService::AttachThreadLockInfo(uint32_t seqNumber, const std::string &networkId,
1126     std::shared_ptr<struct ThreadLockInfo> object)
1127 {
1128     std::lock_guard<std::mutex> lock(threadLockMutex_);
1129     object->networkId = networkId;
1130     auto result =
1131         threadLockInfo_.insert(std::pair<uint32_t, std::shared_ptr<struct ThreadLockInfo>>(seqNumber, object));
1132     return result.second;
1133 }
1134 
QueryThreadLockInfo(uint32_t seqNumber)1135 std::shared_ptr<struct ThreadLockInfo> DBinderService::QueryThreadLockInfo(uint32_t seqNumber)
1136 {
1137     std::lock_guard<std::mutex> lock(threadLockMutex_);
1138 
1139     auto it = threadLockInfo_.find(seqNumber);
1140     if (it != threadLockInfo_.end()) {
1141         return it->second;
1142     }
1143     return nullptr;
1144 }
1145 
DetachProxyObject(binder_uintptr_t binderObject)1146 bool DBinderService::DetachProxyObject(binder_uintptr_t binderObject)
1147 {
1148     std::unique_lock<std::shared_mutex> lock(proxyMutex_);
1149 
1150     return (proxyObject_.erase(binderObject) > 0);
1151 }
1152 
AttachProxyObject(sptr<IRemoteObject> object,binder_uintptr_t binderObject)1153 bool DBinderService::AttachProxyObject(sptr<IRemoteObject> object, binder_uintptr_t binderObject)
1154 {
1155     std::unique_lock<std::shared_mutex> lock(proxyMutex_);
1156 
1157     auto result = proxyObject_.insert(std::pair<int, sptr<IRemoteObject>>(binderObject, object));
1158     return result.second;
1159 }
1160 
QueryProxyObject(binder_uintptr_t binderObject)1161 sptr<IRemoteObject> DBinderService::QueryProxyObject(binder_uintptr_t binderObject)
1162 {
1163     std::shared_lock<std::shared_mutex> lock(proxyMutex_);
1164 
1165     auto it = proxyObject_.find(binderObject);
1166     if (it != proxyObject_.end()) {
1167         return it->second;
1168     }
1169     return nullptr;
1170 }
1171 
DetachSessionObject(binder_uintptr_t stub)1172 bool DBinderService::DetachSessionObject(binder_uintptr_t stub)
1173 {
1174     std::unique_lock<std::shared_mutex> lock(sessionMutex_);
1175     return (sessionObject_.erase(stub) > 0);
1176 }
1177 
AttachSessionObject(std::shared_ptr<struct SessionInfo> object,binder_uintptr_t stub)1178 bool DBinderService::AttachSessionObject(std::shared_ptr<struct SessionInfo> object, binder_uintptr_t stub)
1179 {
1180     std::unique_lock<std::shared_mutex> lock(sessionMutex_);
1181 
1182     auto ret = sessionObject_.insert(std::pair<binder_uintptr_t, std::shared_ptr<struct SessionInfo>>(stub, object));
1183     return ret.second;
1184 }
1185 
QuerySessionObject(binder_uintptr_t stub)1186 std::shared_ptr<struct SessionInfo> DBinderService::QuerySessionObject(binder_uintptr_t stub)
1187 {
1188     std::shared_lock<std::shared_mutex> lock(sessionMutex_);
1189 
1190     auto it = sessionObject_.find(stub);
1191     if (it != sessionObject_.end()) {
1192         return it->second;
1193     }
1194     return nullptr;
1195 }
1196 
DetachDeathRecipient(sptr<IRemoteObject> object)1197 bool DBinderService::DetachDeathRecipient(sptr<IRemoteObject> object)
1198 {
1199     std::unique_lock<std::shared_mutex> lockGuard(deathRecipientMutex_);
1200 
1201     return (deathRecipients_.erase(object) > 0);
1202 }
1203 
AttachDeathRecipient(sptr<IRemoteObject> object,sptr<IRemoteObject::DeathRecipient> deathRecipient)1204 bool DBinderService::AttachDeathRecipient(sptr<IRemoteObject> object,
1205     sptr<IRemoteObject::DeathRecipient> deathRecipient)
1206 {
1207     std::unique_lock<std::shared_mutex> lockGuard(deathRecipientMutex_);
1208 
1209     auto ret = deathRecipients_.insert(
1210         std::pair<sptr<IRemoteObject>, sptr<IRemoteObject::DeathRecipient>>(object, deathRecipient));
1211 
1212     return ret.second;
1213 }
1214 
QueryDeathRecipient(sptr<IRemoteObject> object)1215 sptr<IRemoteObject::DeathRecipient> DBinderService::QueryDeathRecipient(sptr<IRemoteObject> object)
1216 {
1217     std::shared_lock<std::shared_mutex> lockGuard(deathRecipientMutex_);
1218 
1219     auto it = deathRecipients_.find(object);
1220     if (it != deathRecipients_.end()) {
1221         return it->second;
1222     }
1223 
1224     return nullptr;
1225 }
1226 
DetachCallbackProxy(sptr<IRemoteObject> object)1227 bool DBinderService::DetachCallbackProxy(sptr<IRemoteObject> object)
1228 {
1229     std::lock_guard<std::mutex> lockGuard(callbackProxyMutex_);
1230 
1231     return (noticeProxy_.erase(object) > 0);
1232 }
1233 
AttachCallbackProxy(sptr<IRemoteObject> object,DBinderServiceStub * dbStub)1234 bool DBinderService::AttachCallbackProxy(sptr<IRemoteObject> object, DBinderServiceStub *dbStub)
1235 {
1236     std::lock_guard<std::mutex> lockGuard(callbackProxyMutex_);
1237 
1238     auto result = noticeProxy_.insert(std::pair<sptr<IRemoteObject>, DBinderServiceStub *>(object, dbStub));
1239 
1240     return result.second;
1241 }
1242 
NoticeCallbackProxy(sptr<DBinderServiceStub> dbStub)1243 bool DBinderService::NoticeCallbackProxy(sptr<DBinderServiceStub> dbStub)
1244 {
1245     DBINDER_LOGI(LOG_LABEL, "service:%{public}s devicId:%{public}s",
1246         dbStub->GetServiceName().c_str(), DBinderService::ConvertToSecureDeviceID(dbStub->GetDeviceID()).c_str());
1247     bool status = true;
1248     const binder_uintptr_t binderObject = reinterpret_cast<binder_uintptr_t>(dbStub.GetRefPtr());
1249     if (!DetachSessionObject(binderObject)) {
1250         DBINDER_LOGE(LOG_LABEL, "fail to detach session object");
1251         status = false;
1252     }
1253 
1254     if (!DeleteDBinderStub(Str8ToStr16(dbStub->GetServiceName()), dbStub->GetDeviceID())) {
1255         DBINDER_LOGE(LOG_LABEL, "fail to delete DBinder stub");
1256         status = false;
1257     }
1258 
1259     ProcessCallbackProxy(dbStub);
1260 
1261     return status;
1262 }
1263 
ProcessCallbackProxy(sptr<DBinderServiceStub> dbStub)1264 void DBinderService::ProcessCallbackProxy(sptr<DBinderServiceStub> dbStub)
1265 {
1266     std::lock_guard<std::mutex> lockGuard(callbackProxyMutex_);
1267     for (auto it = noticeProxy_.begin(); it != noticeProxy_.end();) {
1268         if (it->second == dbStub.GetRefPtr()) {
1269             IPCObjectProxy *callbackProxy = reinterpret_cast<IPCObjectProxy *>((it->first).GetRefPtr());
1270             int status = callbackProxy->NoticeServiceDie();
1271             if (status != ERR_NONE) {
1272                 DBINDER_LOGE(LOG_LABEL, "fail to notice service:%{public}s die, handle:%{public}d",
1273                     dbStub->GetServiceName().c_str(), callbackProxy->GetHandle());
1274                 // do nothing, Continue to clear subsequent data
1275             }
1276 
1277             sptr<IRemoteObject::DeathRecipient> death = QueryDeathRecipient((it->first));
1278             if (death != nullptr) {
1279                 // Continue to clear subsequent data
1280                 callbackProxy->RemoveDeathRecipient(death);
1281             }
1282 
1283             if (!DetachDeathRecipient((it->first))) {
1284                 DBINDER_LOGE(LOG_LABEL, "detaching death recipient is failed, service:%{public}s handle:%{public}d",
1285                     dbStub->GetServiceName().c_str(), callbackProxy->GetHandle());
1286             }
1287 
1288             it = noticeProxy_.erase(it);
1289         } else {
1290             it++;
1291         }
1292     }
1293 }
1294 
NoticeServiceDieInner(const std::u16string & serviceName,const std::string & deviceID)1295 int32_t DBinderService::NoticeServiceDieInner(const std::u16string &serviceName, const std::string &deviceID)
1296 {
1297     if (serviceName.empty() || IsDeviceIdIllegal(deviceID)) {
1298         DBINDER_LOGE(LOG_LABEL, "service name length:%{public}zu, deviceID length:%{public}zu",
1299             serviceName.length(), deviceID.length());
1300         return DBINDER_SERVICE_INVALID_DATA_ERR;
1301     }
1302 
1303     DBINDER_LOGI(LOG_LABEL, "service:%{public}s deviceId:%{public}s",
1304         Str16ToStr8(serviceName).c_str(), DBinderService::ConvertToSecureDeviceID(deviceID).c_str());
1305     sptr<DBinderServiceStub> dbStub = FindDBinderStub(serviceName, deviceID);
1306     if (dbStub == nullptr) {
1307         DBINDER_LOGE(LOG_LABEL, "find null stub, do not need notice death");
1308         return ERR_NONE;
1309     }
1310 
1311     if (!NoticeCallbackProxy(dbStub)) {
1312         DBINDER_LOGE(LOG_LABEL, "find null proxy");
1313         return DBINDER_SERVICE_NOTICE_DIE_ERR;
1314     }
1315     return ERR_NONE;
1316 }
1317 
NoticeServiceDie(const std::u16string & serviceName,const std::string & deviceID)1318 int32_t DBinderService::NoticeServiceDie(const std::u16string &serviceName, const std::string &deviceID)
1319 {
1320     if (IsDeviceIdIllegal(deviceID)) {
1321         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ERR_INVALID_DATA, __FUNCTION__);
1322     } else {
1323         DfxReportDeviceEvent(DbinderErrorCode::RPC_DRIVER, DbinderErrorCode::IPC_RESULT_IDLE,
1324             DBinderService::ConvertToSecureDeviceID(deviceID).c_str(), __FUNCTION__);
1325     }
1326     std::lock_guard<std::mutex> lockGuard(deathNotificationMutex_);
1327     return NoticeServiceDieInner(serviceName, deviceID);
1328 }
1329 
NoticeDeviceDie(const std::string & deviceID)1330 int32_t DBinderService::NoticeDeviceDie(const std::string &deviceID)
1331 {
1332     if (IsDeviceIdIllegal(deviceID)) {
1333         DBINDER_LOGE(LOG_LABEL, "deviceID length:%{public}zu", deviceID.length());
1334         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_ERR_INVALID_DATA, __FUNCTION__);
1335         return DBINDER_SERVICE_INVALID_DATA_ERR;
1336     }
1337     DBINDER_LOGI(LOG_LABEL, "remote device:%{public}s is dead",
1338         DBinderService::ConvertToSecureDeviceID(deviceID).c_str());
1339     DfxReportDeviceEvent(DbinderErrorCode::RPC_DRIVER, DbinderErrorCode::IPC_RESULT_IDLE,
1340         DBinderService::ConvertToSecureDeviceID(deviceID).c_str(), __FUNCTION__);
1341 
1342     if (remoteListener_ == nullptr) {
1343         DBINDER_LOGE(LOG_LABEL, "remote listener is null");
1344         return DBINDER_SERVICE_NOTICE_DIE_ERR;
1345     }
1346 
1347     if (!remoteListener_->ShutdownSocket(deviceID)) {
1348         DBINDER_LOGE(LOG_LABEL, "Shutdown fail");
1349         // do nothing
1350     }
1351 
1352     std::list<std::u16string> serviceNames = FindServicesByDeviceID(deviceID);
1353     if (serviceNames.empty()) {
1354         DBINDER_LOGE(LOG_LABEL, "the device does not have any registered service");
1355         return ERR_NONE;
1356     }
1357 
1358     int status = ERR_NONE;
1359     std::lock_guard<std::mutex> lockGuard(deathNotificationMutex_);
1360 
1361     for (auto it = serviceNames.begin(); it != serviceNames.end(); it++) {
1362         status += NoticeServiceDieInner((*it), deviceID);
1363     }
1364 
1365     return status;
1366 }
1367 
FindServicesByDeviceID(const std::string & deviceID)1368 std::list<std::u16string> DBinderService::FindServicesByDeviceID(const std::string &deviceID)
1369 {
1370     std::lock_guard<std::mutex> lockGuard(handleEntryMutex_);
1371     std::list<std::u16string> serviceNames;
1372     for (auto it = DBinderStubRegisted_.begin(); it != DBinderStubRegisted_.end(); it++) {
1373         if ((*it)->GetDeviceID() == deviceID) {
1374             serviceNames.push_back(Str8ToStr16((*it)->GetServiceName()));
1375         }
1376     }
1377 
1378     DBINDER_LOGI(LOG_LABEL, "deviceId:%{public}s, service size:%{public}zu",
1379         DBinderService::ConvertToSecureDeviceID(deviceID).c_str(), serviceNames.size());
1380     return serviceNames;
1381 }
1382 
GetRemoteTransType()1383 uint32_t DBinderService::GetRemoteTransType()
1384 {
1385     return IRemoteObject::DATABUS_TYPE;
1386 }
1387 
ConvertToSecureDeviceID(const std::string & str)1388 std::string DBinderService::ConvertToSecureDeviceID(const std::string &str)
1389 {
1390     size_t len = str.size();
1391     if (len <= ENCRYPT_LENGTH) {
1392         return "****";
1393     }
1394     return str.substr(0, ENCRYPT_LENGTH) + "****" + str.substr(len - ENCRYPT_LENGTH);
1395 }
1396 } // namespace OHOS
1397