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