1 /*
2  * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "local_call_container.h"
17 
18 #include "hilog_tag_wrapper.h"
19 #include "ability_manager_client.h"
20 #include "os_account_manager_wrapper.h"
21 
22 namespace OHOS {
23 namespace AbilityRuntime {
StartAbilityByCallInner(const Want & want,std::shared_ptr<CallerCallBack> callback,sptr<IRemoteObject> callerToken,int32_t accountId)24 int LocalCallContainer::StartAbilityByCallInner(const Want& want, std::shared_ptr<CallerCallBack> callback,
25     sptr<IRemoteObject> callerToken, int32_t accountId)
26 {
27     AppExecFwk::ElementName element = want.GetElement();
28     TAG_LOGD(AAFwkTag::LOCAL_CALL, "element:%{public}s", element.GetURI().c_str());
29     if (callback == nullptr) {
30         TAG_LOGE(AAFwkTag::LOCAL_CALL, "callback is nullptr");
31         return ERR_INVALID_VALUE;
32     }
33     if (element.GetBundleName().empty() || element.GetAbilityName().empty()) {
34         TAG_LOGE(AAFwkTag::LOCAL_CALL, "the element of want is empty");
35         return ERR_INVALID_VALUE;
36     }
37     if (element.GetDeviceID().empty()) {
38         TAG_LOGD(AAFwkTag::LOCAL_CALL, "element:DeviceID is empty");
39     }
40 
41     int32_t oriValidUserId = GetValidUserId(accountId);
42     std::shared_ptr<LocalCallRecord> localCallRecord;
43     if (!GetCallLocalRecord(element, localCallRecord, oriValidUserId)) {
44         localCallRecord = std::make_shared<LocalCallRecord>(element);
45         localCallRecord->SetUserId(oriValidUserId);
46         TAG_LOGD(
47             AAFwkTag::LOCAL_CALL, "set user id[%{public}d] to record", oriValidUserId);
48     }
49     localCallRecord->AddCaller(callback);
50     auto remote = localCallRecord->GetRemoteObject();
51     // already finish call request.
52     if (remote) {
53         callback->InvokeCallBack(remote);
54         if (!want.GetBoolParam(Want::PARAM_RESV_CALL_TO_FOREGROUND, false)) {
55             return ERR_OK;
56         }
57     }
58     sptr<CallerConnection> connect = new (std::nothrow) CallerConnection();
59     if (connect == nullptr) {
60         TAG_LOGE(AAFwkTag::LOCAL_CALL, "connection failed");
61         return ERR_INVALID_VALUE;
62     }
63     connections_.emplace(connect);
64     connect->SetRecordAndContainer(localCallRecord, shared_from_this());
65     TAG_LOGD(AAFwkTag::LOCAL_CALL, "connections_.size is %{public}zu", connections_.size());
66     auto retval = AAFwk::AbilityManagerClient::GetInstance()->StartAbilityByCall(want, connect,
67         callerToken, oriValidUserId);
68     if (retval != ERR_OK) {
69         ClearFailedCallConnection(callback);
70     }
71     return retval;
72 }
73 
ReleaseCall(const std::shared_ptr<CallerCallBack> & callback)74 int LocalCallContainer::ReleaseCall(const std::shared_ptr<CallerCallBack>& callback)
75 {
76     TAG_LOGD(AAFwkTag::LOCAL_CALL, "begin");
77     if (callback == nullptr) {
78         TAG_LOGE(AAFwkTag::LOCAL_CALL, "input params is nullptr");
79         return ERR_INVALID_VALUE;
80     }
81     auto abilityClient = AAFwk::AbilityManagerClient::GetInstance();
82     if (abilityClient == nullptr) {
83         TAG_LOGE(AAFwkTag::LOCAL_CALL, "abilityClient is nullptr");
84         return ERR_INVALID_VALUE;
85     }
86     auto localCallRecord = callback->GetRecord();
87     if (localCallRecord == nullptr) {
88         TAG_LOGE(AAFwkTag::LOCAL_CALL, "localCallRecord is nullptr");
89         return ERR_INVALID_VALUE;
90     }
91     localCallRecord->RemoveCaller(callback);
92     if (localCallRecord->IsExistCallBack()) {
93         // just release callback.
94         TAG_LOGD(AAFwkTag::LOCAL_CALL,
95             "ust release this callback");
96         return ERR_OK;
97     }
98     auto connect = iface_cast<CallerConnection>(localCallRecord->GetConnection());
99     if (connect == nullptr) {
100         TAG_LOGE(AAFwkTag::LOCAL_CALL, "connection conversion failed");
101         return ERR_INVALID_VALUE;
102     }
103     int32_t retval = ERR_OK;
104     if (localCallRecord->IsSingletonRemote()) {
105         retval = RemoveSingletonCallLocalRecord(localCallRecord);
106     } else {
107         retval = RemoveMultipleCallLocalRecord(localCallRecord);
108     }
109 
110     if (retval != ERR_OK) {
111         TAG_LOGE(AAFwkTag::LOCAL_CALL, "Remove call local record failed");
112         return retval;
113     }
114 
115     connections_.erase(connect);
116     connect->ClearCallRecord();
117     localCallRecord->ClearData();
118     if (abilityClient->ReleaseCall(connect, localCallRecord->GetElementName()) != ERR_OK) {
119         TAG_LOGE(AAFwkTag::LOCAL_CALL, "ReleaseCall failed");
120         return ERR_INVALID_VALUE;
121     }
122     return ERR_OK;
123 }
124 
ClearFailedCallConnection(const std::shared_ptr<CallerCallBack> & callback)125 void LocalCallContainer::ClearFailedCallConnection(const std::shared_ptr<CallerCallBack> &callback)
126 {
127     TAG_LOGD(AAFwkTag::LOCAL_CALL, "called");
128     if (callback == nullptr) {
129         TAG_LOGE(AAFwkTag::LOCAL_CALL, "callback is nullptr");
130         return;
131     }
132 
133     auto localCallRecord = callback->GetRecord();
134     if (localCallRecord == nullptr) {
135         TAG_LOGE(AAFwkTag::LOCAL_CALL, "localCallRecord is nullptr");
136         return;
137     }
138 
139     auto connect = iface_cast<CallerConnection>(localCallRecord->GetConnection());
140     if (connect == nullptr) {
141         TAG_LOGE(AAFwkTag::LOCAL_CALL, "connection conversion failed");
142         return;
143     }
144 
145     connections_.erase(connect);
146 }
147 
RemoveSingletonCallLocalRecord(const std::shared_ptr<LocalCallRecord> & record)148 int32_t LocalCallContainer::RemoveSingletonCallLocalRecord(const std::shared_ptr<LocalCallRecord> &record)
149 {
150     std::lock_guard<std::mutex> lock(mutex_);
151     if (record == nullptr) {
152         TAG_LOGE(AAFwkTag::LOCAL_CALL, "input params invalid value");
153         return ERR_INVALID_VALUE;
154     }
155 
156     auto iterRecord = callProxyRecords_.find(record->GetElementName().GetURI());
157     if (iterRecord == callProxyRecords_.end()) {
158         TAG_LOGE(AAFwkTag::LOCAL_CALL, "release record in singleton not found");
159         return ERR_INVALID_VALUE;
160     }
161 
162     iterRecord->second.erase(record);
163     if (iterRecord->second.empty()) {
164         callProxyRecords_.erase(iterRecord);
165     }
166 
167     return ERR_OK;
168 }
169 
RemoveMultipleCallLocalRecord(const std::shared_ptr<LocalCallRecord> & record)170 int32_t LocalCallContainer::RemoveMultipleCallLocalRecord(const std::shared_ptr<LocalCallRecord> &record)
171 {
172     if (record == nullptr) {
173         TAG_LOGE(AAFwkTag::LOCAL_CALL, "input params invalid value");
174         return ERR_INVALID_VALUE;
175     }
176 
177     std::lock_guard<std::mutex> lock(multipleMutex_);
178     auto iterRecord = multipleCallProxyRecords_.find(record->GetElementName().GetURI());
179     if (iterRecord == multipleCallProxyRecords_.end()) {
180         TAG_LOGE(AAFwkTag::LOCAL_CALL, "release record in multiple not found");
181         return ERR_INVALID_VALUE;
182     }
183 
184     iterRecord->second.erase(record);
185     if (iterRecord->second.empty()) {
186         multipleCallProxyRecords_.erase(iterRecord);
187     }
188 
189     return ERR_OK;
190 }
191 
IsCallBackCalled(const std::vector<std::shared_ptr<CallerCallBack>> & callers) const192 bool LocalCallContainer::IsCallBackCalled(const std::vector<std::shared_ptr<CallerCallBack>> &callers) const
193 {
194     for (auto& callBack : callers) {
195         if (callBack != nullptr && !callBack->IsCallBack()) {
196             TAG_LOGE(AAFwkTag::LOCAL_CALL, "callback is not called");
197             return false;
198         }
199     }
200 
201     return true;
202 }
203 
DumpCalls(std::vector<std::string> & info)204 void LocalCallContainer::DumpCalls(std::vector<std::string>& info)
205 {
206     TAG_LOGD(AAFwkTag::LOCAL_CALL, "called");
207     info.emplace_back("          caller connections:");
208     std::lock_guard<std::mutex> lock(mutex_);
209     for (auto &item : callProxyRecords_) {
210         for (auto &itemCall : item.second) {
211             std::string tempstr = "            LocalCallRecord";
212             tempstr += " ID #" + std::to_string(itemCall->GetRecordId()) + "\n";
213             tempstr += "              callee";
214             tempstr += " uri[" + item.first + "]" + "\n";
215             tempstr += "              callers #" + std::to_string(itemCall->GetCallers().size());
216             if (IsCallBackCalled(itemCall->GetCallers())) {
217                 TAG_LOGI(AAFwkTag::LOCAL_CALL, "state: REQUESTEND");
218                 tempstr += "  state #REQUESTEND";
219             } else {
220                 TAG_LOGI(AAFwkTag::LOCAL_CALL, "state: REQUESTING");
221                 tempstr += "  state #REQUESTING";
222             }
223             info.emplace_back(tempstr);
224             }
225     }
226     return;
227 }
228 
GetCallLocalRecord(const AppExecFwk::ElementName & elementName,std::shared_ptr<LocalCallRecord> & localCallRecord,int32_t accountId)229 bool LocalCallContainer::GetCallLocalRecord(
230     const AppExecFwk::ElementName& elementName, std::shared_ptr<LocalCallRecord>& localCallRecord, int32_t accountId)
231 {
232     std::lock_guard<std::mutex> lock(mutex_);
233     for (auto pair : callProxyRecords_) {
234         AppExecFwk::ElementName callElement;
235         if (!callElement.ParseURI(pair.first)) {
236             TAG_LOGE(AAFwkTag::LOCAL_CALL,
237                 "failed elementName uri: %{private}s", pair.first.c_str());
238             continue;
239         }
240         // elementName in callProxyRecords_ has moduleName (sometimes not empty),
241         // but the moduleName of input param elementName is usually empty.
242         callElement.SetModuleName("");
243         if ((pair.first != elementName.GetURI() && callElement.GetURI() != elementName.GetURI())) {
244             continue;
245         }
246 
247         for (auto &itemCall : pair.second) {
248             if (itemCall != nullptr && itemCall->GetUserId() == accountId) {
249                 localCallRecord = itemCall;
250                 return true;
251             }
252         }
253     }
254     return false;
255 }
256 
OnCallStubDied(const wptr<IRemoteObject> & remote)257 void LocalCallContainer::OnCallStubDied(const wptr<IRemoteObject>& remote)
258 {
259     auto diedRemote = remote.promote();
260     auto isExist = [&diedRemote](auto& record) {
261         return record->IsSameObject(diedRemote);
262     };
263 
264     {
265         std::lock_guard<std::mutex> lock(mutex_);
266         for (auto &item : callProxyRecords_) {
267             auto iter = std::find_if(item.second.begin(), item.second.end(), isExist);
268             if (iter == item.second.end()) {
269                 continue;
270             }
271             TAG_LOGD(AAFwkTag::LOCAL_CALL,
272                 "singleton key[%{public}s]. notify died event", item.first.c_str());
273             (*iter)->OnCallStubDied(remote);
274             item.second.erase(iter);
275             if (item.second.empty()) {
276                 TAG_LOGD(AAFwkTag::LOCAL_CALL,
277                     "singleton key[%{public}s] empty", item.first.c_str());
278                 callProxyRecords_.erase(item.first);
279                 break;
280             }
281         }
282     }
283 
284     std::lock_guard<std::mutex> lock(multipleMutex_);
285     for (auto &item : multipleCallProxyRecords_) {
286         TAG_LOGD(
287             AAFwkTag::LOCAL_CALL, "multiple key[%{public}s].", item.first.c_str());
288         auto iterMultiple = find_if(item.second.begin(), item.second.end(), isExist);
289         if (iterMultiple == item.second.end()) {
290             continue;
291         }
292         TAG_LOGD(AAFwkTag::LOCAL_CALL, "multiple key[%{public}s]. notify died event",
293             item.first.c_str());
294         (*iterMultiple)->OnCallStubDied(remote);
295         item.second.erase(iterMultiple);
296         if (item.second.empty()) {
297             TAG_LOGD(AAFwkTag::LOCAL_CALL,
298                 "multiple key[%{public}s] empty.", item.first.c_str());
299             multipleCallProxyRecords_.erase(item.first);
300             break;
301         }
302     }
303 }
304 
SetCallLocalRecord(const AppExecFwk::ElementName & element,const std::shared_ptr<LocalCallRecord> & localCallRecord)305 void LocalCallContainer::SetCallLocalRecord(
306     const AppExecFwk::ElementName& element, const std::shared_ptr<LocalCallRecord> &localCallRecord)
307 {
308     const std::string strKey = element.GetURI();
309     std::lock_guard<std::mutex> lock(mutex_);
310     auto iter = callProxyRecords_.find(strKey);
311     if (iter == callProxyRecords_.end()) {
312         std::set<std::shared_ptr<LocalCallRecord>> records = { localCallRecord };
313         callProxyRecords_.emplace(strKey, records);
314         return;
315     }
316 
317     iter->second.emplace(localCallRecord);
318 }
319 
SetMultipleCallLocalRecord(const AppExecFwk::ElementName & element,const std::shared_ptr<LocalCallRecord> & localCallRecord)320 void LocalCallContainer::SetMultipleCallLocalRecord(
321     const AppExecFwk::ElementName& element, const std::shared_ptr<LocalCallRecord> &localCallRecord)
322 {
323     const std::string strKey = element.GetURI();
324     std::lock_guard<std::mutex> lock(multipleMutex_);
325     auto iter = multipleCallProxyRecords_.find(strKey);
326     if (iter == multipleCallProxyRecords_.end()) {
327         std::set<std::shared_ptr<LocalCallRecord>> records = { localCallRecord };
328         multipleCallProxyRecords_.emplace(strKey, records);
329         return;
330     }
331 
332     iter->second.emplace(localCallRecord);
333 }
334 
ClearCallRecord()335 void CallerConnection::ClearCallRecord()
336 {
337     localCallRecord_.reset();
338 }
339 
SetRecordAndContainer(const std::shared_ptr<LocalCallRecord> & localCallRecord,const std::weak_ptr<LocalCallContainer> & container)340 void CallerConnection::SetRecordAndContainer(const std::shared_ptr<LocalCallRecord> &localCallRecord,
341     const std::weak_ptr<LocalCallContainer> &container)
342 {
343     if (localCallRecord == nullptr) {
344         TAG_LOGD(AAFwkTag::LOCAL_CALL, "input param is nullptr");
345         return;
346     }
347     localCallRecord_ = localCallRecord;
348     container_ = container;
349     localCallRecord_->SetConnection(this->AsObject());
350 }
351 
OnAbilityConnectDone(const AppExecFwk::ElementName & element,const sptr<IRemoteObject> & remoteObject,int code)352 void CallerConnection::OnAbilityConnectDone(
353     const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int code)
354 {
355     TAG_LOGD(AAFwkTag::LOCAL_CALL,
356         "start %{public}s", element.GetURI().c_str());
357     auto container = container_.lock();
358     if (container == nullptr || localCallRecord_ == nullptr) {
359         TAG_LOGE(AAFwkTag::LOCAL_CALL, "container or record is nullptr");
360         return;
361     }
362 
363     const bool isSingleton = (code == static_cast<int32_t>(AppExecFwk::LaunchMode::SINGLETON));
364     localCallRecord_->SetIsSingleton(isSingleton);
365 
366     auto callRecipient = new (std::nothrow) CallRecipient([container](const wptr<IRemoteObject> &arg) {
367         container->OnCallStubDied(arg);
368     });
369     localCallRecord_->SetRemoteObject(remoteObject, callRecipient);
370 
371     if (isSingleton) {
372         container->SetCallLocalRecord(element, localCallRecord_);
373     } else {
374         container->SetMultipleCallLocalRecord(element, localCallRecord_);
375     }
376 
377     localCallRecord_->InvokeCallBack();
378     return;
379 }
380 
OnAbilityDisconnectDone(const AppExecFwk::ElementName & element,int code)381 void CallerConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int code)
382 {
383 }
384 
OnRemoteStateChanged(const AppExecFwk::ElementName & element,int32_t abilityState)385 void CallerConnection::OnRemoteStateChanged(const AppExecFwk::ElementName &element, int32_t abilityState)
386 {
387     if (localCallRecord_ == nullptr) {
388         TAG_LOGD(AAFwkTag::LOCAL_CALL, "local call record is nullptr.");
389         return;
390     }
391 
392     localCallRecord_->NotifyRemoteStateChanged(abilityState);
393 
394     return;
395 }
396 
GetCurrentUserId()397 int32_t LocalCallContainer::GetCurrentUserId()
398 {
399     if (currentUserId_ == DEFAULT_INVAL_VALUE) {
400         auto osAccount = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance();
401         if (osAccount == nullptr) {
402             TAG_LOGE(AAFwkTag::LOCAL_CALL, "osAccount is nullptr");
403             return DEFAULT_INVAL_VALUE;
404         }
405 
406         osAccount->GetOsAccountLocalIdFromProcess(currentUserId_);
407     }
408 
409     return currentUserId_;
410 }
411 
GetValidUserId(int32_t accountId)412 int32_t LocalCallContainer::GetValidUserId(int32_t accountId)
413 {
414     TAG_LOGD(AAFwkTag::LOCAL_CALL, "accountId is %{public}d", accountId);
415     if (accountId > 0 && accountId != GetCurrentUserId()) {
416         return accountId;
417     }
418 
419     return DEFAULT_INVAL_VALUE;
420 }
421 } // namespace AbilityRuntime
422 } // namespace OHOS
423