• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021-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 "multi_sim_monitor.h"
17 
18 #include <atomic>
19 
20 #include "common_event_manager.h"
21 #include "common_event_support.h"
22 #include "os_account_manager_wrapper.h"
23 #include "operator_file_parser.h"
24 #include "radio_event.h"
25 #include "string_ex.h"
26 #include "telephony_errors.h"
27 #include "telephony_ext_wrapper.h"
28 #include "sim_account_callback_death_recipient.h"
29 
30 namespace OHOS {
31 namespace Telephony {
32 const int64_t DELAY_TIME = 1000;
33 const int64_t DELAY_THREE_SECONDS = 3000;
34 const int64_t RETRY_TIME = 3 * 60 * 1000;
35 const int32_t ACTIVE_USER_ID = 100;
36 const int INIT_TIMES = 15;
37 const int INIT_DATA_TIMES = 5;
38 constexpr const char *IS_BLOCK_LOAD_OPERATORCONFIG = "telephony.is_block_load_operatorconfig";
MultiSimMonitor(const std::shared_ptr<MultiSimController> & controller,std::vector<std::shared_ptr<Telephony::SimStateManager>> simStateManager,std::vector<std::weak_ptr<Telephony::SimFileManager>> simFileManager)39 MultiSimMonitor::MultiSimMonitor(const std::shared_ptr<MultiSimController> &controller,
40     std::vector<std::shared_ptr<Telephony::SimStateManager>> simStateManager,
41     std::vector<std::weak_ptr<Telephony::SimFileManager>> simFileManager)
42     : TelEventHandler("MultiSimMonitor"), controller_(controller), simStateManager_(simStateManager),
43       simFileManager_(simFileManager), initEsimDataRemainCount_(INIT_DATA_TIMES)
44 {
45     if (observerHandler_ == nullptr) {
46         observerHandler_ = std::make_unique<ObserverHandler>();
47     }
48 }
49 
~MultiSimMonitor()50 MultiSimMonitor::~MultiSimMonitor()
51 {
52     TELEPHONY_LOGD("destory");
53     UnSubscribeListeners();
54 }
55 
Init()56 void MultiSimMonitor::Init()
57 {
58     isSimAccountLoaded_.resize(SIM_SLOT_COUNT, 0);
59     initDataRemainCount_.resize(SIM_SLOT_COUNT, INIT_DATA_TIMES);
60     initEsimDataRemainCount_ = INIT_DATA_TIMES;
61     std::lock_guard<ffrt::shared_mutex> lock(controller_->loadedSimCardInfoMutex_);
62     controller_->loadedSimCardInfo_.clear();
63     SendEvent(MultiSimMonitor::REGISTER_SIM_NOTIFY_EVENT);
64     InitListener();
65     InitEsimData();
66 }
67 
AddExtraManagers(std::shared_ptr<Telephony::SimStateManager> simStateManager,std::shared_ptr<Telephony::SimFileManager> simFileManager)68 void MultiSimMonitor::AddExtraManagers(std::shared_ptr<Telephony::SimStateManager> simStateManager,
69     std::shared_ptr<Telephony::SimFileManager> simFileManager)
70 {
71     if (static_cast<int32_t>(simStateManager_.size()) == SIM_SLOT_COUNT) {
72         {
73             std::unique_lock<ffrt::shared_mutex> lock(simStateMgrMutex_);
74             simStateManager_.push_back(simStateManager);
75             simFileManager_.push_back(simFileManager);
76             isSimAccountLoaded_.push_back(0);
77             initDataRemainCount_.push_back(INIT_DATA_TIMES);
78         }
79         RegisterSimNotify(SIM_SLOT_2);
80     }
81 }
82 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)83 void MultiSimMonitor::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event)
84 {
85     if (event == nullptr) {
86         TELEPHONY_LOGE("start ProcessEvent but event is null!");
87         return;
88     }
89     auto eventCode = event->GetInnerEventId();
90     switch (eventCode) {
91         case MultiSimMonitor::INIT_DATA_RETRY_EVENT:{
92             InitData(event->GetParam());
93             break;
94         }
95         case MultiSimMonitor::INIT_ESIM_DATA_RETRY_EVENT:{
96             InitEsimData();
97             break;
98         }
99         case RadioEvent::RADIO_QUERY_ICCID_DONE:
100         case RadioEvent::RADIO_SIM_STATE_LOCKED:
101         case RadioEvent::RADIO_SIM_STATE_READY: {
102             RemoveEvent(MultiSimMonitor::INIT_DATA_RETRY_EVENT);
103             InitData(event->GetParam());
104             break;
105         }
106         case RadioEvent::RADIO_SIM_STATE_CHANGE: {
107             RefreshData(event->GetParam());
108             break;
109         }
110         case MultiSimMonitor::REGISTER_SIM_NOTIFY_EVENT: {
111             RemoveEvent(MultiSimMonitor::REGISTER_SIM_NOTIFY_RETRY_EVENT);
112             RegisterSimNotify();
113             break;
114         }
115         case MultiSimMonitor::REGISTER_SIM_NOTIFY_RETRY_EVENT: {
116             RegisterSimNotify();
117             break;
118         }
119         case MultiSimMonitor::RESET_OPKEY_CONFIG: {
120             RemoveEvent(MultiSimMonitor::RETRY_RESET_OPKEY_CONFIG);
121             UpdateAllOpkeyConfigs();
122             break;
123         }
124         case MultiSimMonitor::RETRY_RESET_OPKEY_CONFIG: {
125             RemoveEvent(MultiSimMonitor::RETRY_RESET_OPKEY_CONFIG);
126             CheckDataShareError();
127             CheckSimNotifyRegister();
128             break;
129         }
130         default:
131             break;
132     }
133 }
134 
CheckOpcNeedUpdata(const bool isDataShareError)135 void MultiSimMonitor::CheckOpcNeedUpdata(const bool isDataShareError)
136 {
137     TelFFRTUtils::Submit([=]() {
138         bool isOpcVersionUpdated = CheckUpdateOpcVersion() == TELEPHONY_SUCCESS;
139         if (isOpcVersionUpdated) {
140             OperatorFileParser::ClearFilesCache();
141         }
142         TELEPHONY_LOGI("CheckOpcNeedUpdata isDataShareError: %{public}d, isOpcVersionUpdated: %{public}d",
143             isDataShareError, isOpcVersionUpdated);
144         if (isOpcVersionUpdated || isDataShareError) {
145             SendEvent(MultiSimMonitor::RESET_OPKEY_CONFIG);
146         }
147     });
148 }
149 
CheckUpdateOpcVersion()150 int32_t MultiSimMonitor::CheckUpdateOpcVersion()
151 {
152     if (TELEPHONY_EXT_WRAPPER.checkOpcVersionIsUpdate_ != nullptr &&
153         TELEPHONY_EXT_WRAPPER.updateOpcVersion_ != nullptr) {
154         std::lock_guard<std::mutex> lock(mutexForData_);
155         if (TELEPHONY_EXT_WRAPPER.checkOpcVersionIsUpdate_()) {
156             TELEPHONY_LOGI("need update config");
157             SetBlockLoadOperatorConfig(true);
158             if (controller_->UpdateOpKeyInfo() != TELEPHONY_SUCCESS) {
159                 TELEPHONY_LOGW("UpdateOpKeyInfo error");
160                 return TELEPHONY_ERROR;
161             }
162             TELEPHONY_EXT_WRAPPER.updateOpcVersion_();
163             TELEPHONY_LOGI("Version updated succ");
164             return TELEPHONY_SUCCESS;
165         }
166     }
167     return TELEPHONY_ERROR;
168 }
169 
SetBlockLoadOperatorConfig(bool isBlockLoadOperatorConfig)170 void MultiSimMonitor::SetBlockLoadOperatorConfig(bool isBlockLoadOperatorConfig)
171 {
172     if (!isBlockLoadOperatorConfig) {
173         return;
174     }
175     for (int32_t slotId = 0; slotId < SIM_SLOT_COUNT; slotId++) {
176         std::string key = "";
177         SetParameter(key.append(IS_BLOCK_LOAD_OPERATORCONFIG).append(std::to_string(slotId)).c_str(), "true");
178     }
179 }
180 
GetBlockLoadOperatorConfig()181 bool MultiSimMonitor::GetBlockLoadOperatorConfig()
182 {
183     std::string key = "";
184     char isBlockLoadOperatorConfig[SYSPARA_SIZE] = {0};
185     for (int32_t slotId = 0; slotId < SIM_SLOT_COUNT; slotId++) {
186         key.clear();
187         key.append(IS_BLOCK_LOAD_OPERATORCONFIG).append(std::to_string(slotId));
188         GetParameter(key.c_str(), "false", isBlockLoadOperatorConfig, SYSPARA_SIZE);
189         if (strcmp(isBlockLoadOperatorConfig, "true") == 0) {
190             return true;
191         }
192     }
193     return false;
194 }
195 
UpdateAllOpkeyConfigs()196 void MultiSimMonitor::UpdateAllOpkeyConfigs()
197 {
198     std::shared_lock<ffrt::shared_mutex> lock(simStateMgrMutex_);
199     for (size_t slotId = 0; slotId < simFileManager_.size(); slotId++) {
200         auto simFileManager = simFileManager_[slotId].lock();
201         if (simFileManager == nullptr) {
202             TELEPHONY_LOGE("simFileManager is nullptr, slotId : %{public}zu", slotId);
203             continue;
204         }
205         simFileManager->UpdateOpkeyConfig();
206     }
207 }
208 
InitData(int32_t slotId)209 void MultiSimMonitor::InitData(int32_t slotId)
210 {
211     TELEPHONY_LOGI("MultiSimMonitor::InitData slotId = %{public}d", slotId);
212     if (!IsValidSlotId(slotId)) {
213         TELEPHONY_LOGE("MultiSimMonitor::InitData slotId is invalid");
214         return;
215     }
216     if (isSimAccountLoaded_[slotId]) {
217         TELEPHONY_LOGI("MultiSimMonitor::InitData simAccountInfo is already loaded");
218         return;
219     }
220     if (controller_ == nullptr) {
221         TELEPHONY_LOGE("MultiSimMonitor::InitData controller_ is nullptr");
222         return;
223     }
224     // InitData is triggered when the sim card file changes.
225     // However, it should not be excuted when the eSIM profile is disabled.
226     if ((simStateManager_[slotId]->GetSimState() == SimState::SIM_STATE_UNKNOWN) && controller_->IsEsim(slotId)) {
227         TELEPHONY_LOGE("MultiSimMonitor::InitData not init when esim is deactivated");
228         return;
229     }
230     if (!controller_->InitData(slotId)) {
231         TELEPHONY_LOGE("MultiSimMonitor::InitData failed");
232         if (initDataRemainCount_[slotId] > 0) {
233             SendEvent(MultiSimMonitor::INIT_DATA_RETRY_EVENT, slotId, DELAY_TIME);
234             TELEPHONY_LOGI("retry remain %{public}d", initDataRemainCount_[slotId]);
235             initDataRemainCount_[slotId]--;
236         }
237         return;
238     }
239     isSimAccountLoaded_[slotId] = 1;
240     if (observerHandler_ == nullptr) {
241         TELEPHONY_LOGE("MultiSimMonitor::InitData observerHandler_ is nullptr");
242         return;
243     }
244     NotifySimAccountChanged();
245     observerHandler_->NotifyObserver(RadioEvent::RADIO_SIM_ACCOUNT_LOADED, slotId);
246 }
247 
InitEsimData()248 void MultiSimMonitor::InitEsimData()
249 {
250     if (isAllSimAccountLoaded_) {
251         TELEPHONY_LOGE("MultiSimMonitor::InitEsimData already loaded");
252         return;
253     }
254     if (controller_ == nullptr) {
255         TELEPHONY_LOGE("MultiSimMonitor::controller_ is nullptr");
256         return;
257     }
258     if (!controller_->InitEsimData()) {
259         TELEPHONY_LOGE("MultiSimMonitor::InitEsimData failed");
260         if (initEsimDataRemainCount_ > 0) {
261             SendEvent(MultiSimMonitor::INIT_ESIM_DATA_RETRY_EVENT, DELAY_THREE_SECONDS);
262             TELEPHONY_LOGI("retry remain %{public}d", initEsimDataRemainCount_);
263             initEsimDataRemainCount_--;
264         }
265         return;
266     }
267     isAllSimAccountLoaded_ = true;
268     NotifySimAccountChanged();
269 }
270 
RefreshData(int32_t slotId)271 void MultiSimMonitor::RefreshData(int32_t slotId)
272 {
273     if (!IsValidSlotId(slotId)) {
274         TELEPHONY_LOGE("MultiSimMonitor::RefreshData slotId is invalid");
275         return;
276     }
277     std::shared_lock<ffrt::shared_mutex> lock(simStateMgrMutex_);
278     auto simFileManager = simFileManager_[slotId].lock();
279     if (controller_ == nullptr || simStateManager_[slotId] == nullptr || simFileManager == nullptr) {
280         TELEPHONY_LOGE("MultiSimMonitor::RefreshData controller_ or simStateManager_ is nullptr");
281         return;
282     }
283     if ((simStateManager_[slotId]->GetSimState() == SimState::SIM_STATE_NOT_PRESENT) ||
284         ((simStateManager_[slotId]->GetSimState() == SimState::SIM_STATE_UNKNOWN) && controller_->IsEsim(slotId))) {
285         TELEPHONY_LOGI("MultiSimMonitor::RefreshData clear data when slotId %{public}d is absent or is esim", slotId);
286         simFileManager->ClearData();
287         controller_->ForgetAllData(slotId);
288         controller_->GetListFromDataBase();
289         controller_->GetAllListFromDataBase();
290         controller_->ResetSetPrimarySlotRemain(slotId);
291         isSimAccountLoaded_[slotId] = 0;
292         initDataRemainCount_[slotId] = INIT_DATA_TIMES;
293         std::lock_guard<ffrt::shared_mutex> lock(controller_->loadedSimCardInfoMutex_);
294         controller_->loadedSimCardInfo_.erase(slotId);
295     } else if (simStateManager_[slotId]->GetSimState() == SimState::SIM_STATE_UNKNOWN &&
296                 !controller_->IsSetPrimarySlotIdInProgress()) {
297         TELEPHONY_LOGI("MultiSimMonitor::RefreshData clear data when sim is unknown");
298         simFileManager->ClearData();
299         isSimAccountLoaded_[slotId] = 0;
300     }
301     if (controller_->unInitModemSlotId_ == slotId) {
302         TELEPHONY_LOGI("need to recheck primary");
303         controller_->ReCheckPrimary();
304     }
305     NotifySimAccountChanged();
306 }
307 
RegisterCoreNotify(int32_t slotId,const std::shared_ptr<AppExecFwk::EventHandler> & handler,int what)308 void MultiSimMonitor::RegisterCoreNotify(
309     int32_t slotId, const std::shared_ptr<AppExecFwk::EventHandler> &handler, int what)
310 {
311     if (observerHandler_ == nullptr || handler == nullptr) {
312         TELEPHONY_LOGE("observerHandler_ or handler is nullptr");
313         return;
314     }
315     observerHandler_->RegObserver(what, handler);
316     if (!IsValidSlotId(slotId)) {
317         TELEPHONY_LOGE("MultiSimMonitor::RegisterCoreNotify slotId is invalid");
318         return;
319     }
320     if (isSimAccountLoaded_[slotId] || IsVSimSlotId(slotId)) {
321         TELEPHONY_LOGI("notify slotId:%{public}d sim account loaded", slotId);
322         TelEventHandler::SendTelEvent(handler, RadioEvent::RADIO_SIM_ACCOUNT_LOADED, slotId, 0);
323     }
324 }
325 
IsValidSlotId(int32_t slotId)326 bool MultiSimMonitor::IsValidSlotId(int32_t slotId)
327 {
328     return (slotId >= DEFAULT_SIM_SLOT_ID) && slotId < static_cast<int32_t>(simStateManager_.size());
329 }
330 
IsVSimSlotId(int32_t slotId)331 bool MultiSimMonitor::IsVSimSlotId(int32_t slotId)
332 {
333     if (TELEPHONY_EXT_WRAPPER.getVSimSlotId_) {
334         int vSimSlotId = DEFAULT_SIM_SLOT_ID_REMOVE;
335         TELEPHONY_EXT_WRAPPER.getVSimSlotId_(vSimSlotId);
336         return vSimSlotId == slotId;
337     }
338     return false;
339 }
340 
UnSubscribeListeners()341 void MultiSimMonitor::UnSubscribeListeners()
342 {
343     if (dataShareSubscriber_ != nullptr && CommonEventManager::UnSubscribeCommonEvent(dataShareSubscriber_)) {
344         dataShareSubscriber_ = nullptr;
345         TELEPHONY_LOGI("Unsubscribe datashare ready success");
346     }
347     if (userSwitchSubscriber_ != nullptr && CommonEventManager::UnSubscribeCommonEvent(userSwitchSubscriber_)) {
348         userSwitchSubscriber_ = nullptr;
349         TELEPHONY_LOGI("Unsubscribe UserSwitch success");
350     }
351     if (statusChangeListener_ != nullptr) {
352         auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
353         if (samgrProxy != nullptr) {
354             samgrProxy->UnSubscribeSystemAbility(OHOS::COMMON_EVENT_SERVICE_ID, statusChangeListener_);
355             statusChangeListener_ = nullptr;
356             TELEPHONY_LOGI("Unsubscribe COMMON_EVENT_SERVICE_ID success");
357         }
358     }
359 }
360 
InitListener()361 void MultiSimMonitor::InitListener()
362 {
363     auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
364     statusChangeListener_ = new (std::nothrow) SystemAbilityStatusChangeListener(*this);
365     if (samgrProxy == nullptr || statusChangeListener_ == nullptr) {
366         TELEPHONY_LOGE("samgrProxy or statusChangeListener_ is nullptr");
367         return;
368     }
369     auto ret = samgrProxy->SubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, statusChangeListener_);
370     TELEPHONY_LOGI("SubscribeSystemAbility COMMON_EVENT_SERVICE_ID result is %{public}d", ret);
371     CheckOpcNeedUpdata(false);
372 }
373 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)374 void MultiSimMonitor::SystemAbilityStatusChangeListener::OnAddSystemAbility(int32_t systemAbilityId,
375     const std::string &deviceId)
376 {
377     switch (systemAbilityId) {
378         case COMMON_EVENT_SERVICE_ID: {
379             TELEPHONY_LOGI("COMMON_EVENT_SERVICE_ID is running");
380             handler_.SubscribeDataShareReady();
381             handler_.SubscribeUserSwitch();
382             break;
383         }
384         default:
385             TELEPHONY_LOGE("systemAbilityId is invalid");
386             break;
387     }
388 }
389 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)390 void MultiSimMonitor::SystemAbilityStatusChangeListener::OnRemoveSystemAbility(int32_t systemAbilityId,
391     const std::string &deviceId)
392 {
393     switch (systemAbilityId) {
394         case COMMON_EVENT_SERVICE_ID: {
395             TELEPHONY_LOGI("COMMON_EVENT_SERVICE_ID stopped");
396             handler_.UnSubscribeListeners();
397             break;
398         }
399         default:
400             TELEPHONY_LOGE("systemAbilityId is invalid");
401             break;
402     }
403 }
404 
SubscribeDataShareReady()405 void MultiSimMonitor::SubscribeDataShareReady()
406 {
407     if (dataShareSubscriber_ != nullptr) {
408         TELEPHONY_LOGW("datashare ready has Subscribed");
409         return;
410     }
411     MatchingSkills matchingSkills;
412     matchingSkills.AddEvent(DATASHARE_READY_EVENT);
413     CommonEventSubscribeInfo subscriberInfo(matchingSkills);
414     subscriberInfo.SetThreadMode(CommonEventSubscribeInfo::COMMON);
415     dataShareSubscriber_ = std::make_shared<DataShareEventSubscriber>(subscriberInfo, *this);
416     if (CommonEventManager::SubscribeCommonEvent(dataShareSubscriber_)) {
417         TELEPHONY_LOGI("Subscribe datashare ready success");
418     } else {
419         dataShareSubscriber_ = nullptr;
420         TELEPHONY_LOGE("Subscribe datashare ready fail");
421     }
422     SendEvent(MultiSimMonitor::RETRY_RESET_OPKEY_CONFIG, 0, RETRY_TIME);
423 }
424 
SubscribeUserSwitch()425 void MultiSimMonitor::SubscribeUserSwitch()
426 {
427     if (userSwitchSubscriber_ != nullptr) {
428         TELEPHONY_LOGW("UserSwitch has Subscribed");
429         return;
430     }
431     MatchingSkills matchingSkills;
432     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
433     CommonEventSubscribeInfo subscriberInfo(matchingSkills);
434     subscriberInfo.SetThreadMode(CommonEventSubscribeInfo::COMMON);
435     userSwitchSubscriber_ = std::make_shared<UserSwitchEventSubscriber>(subscriberInfo, *this);
436     if (CommonEventManager::SubscribeCommonEvent(userSwitchSubscriber_)) {
437         TELEPHONY_LOGI("Subscribe UserSwitch success");
438     } else {
439         userSwitchSubscriber_ = nullptr;
440         TELEPHONY_LOGE("Subscribe UserSwitch fail");
441     }
442 }
443 
OnReceiveEvent(const CommonEventData & data)444 void MultiSimMonitor::DataShareEventSubscriber::OnReceiveEvent(const CommonEventData &data)
445 {
446     OHOS::EventFwk::Want want = data.GetWant();
447     std::string action = want.GetAction();
448     TELEPHONY_LOGI("action = %{public}s", action.c_str());
449     std::vector<int32_t> activeList = { 0 };
450     DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->QueryActiveOsAccountIds(activeList);
451     if (action == DATASHARE_READY_EVENT) {
452         handler_.isDataShareReady_ = true;
453         if (activeList.size() > 0 && activeList[0] == ACTIVE_USER_ID) {
454             handler_.CheckDataShareError();
455             handler_.CheckSimNotifyRegister();
456         }
457     }
458 }
459 
OnReceiveEvent(const CommonEventData & data)460 void MultiSimMonitor::UserSwitchEventSubscriber::OnReceiveEvent(const CommonEventData &data)
461 {
462     OHOS::EventFwk::Want want = data.GetWant();
463     std::string action = want.GetAction();
464     TELEPHONY_LOGI("action = %{public}s", action.c_str());
465     if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
466         int32_t userId = data.GetCode();
467         TELEPHONY_LOGI("current user id is :%{public}d", userId);
468         if (userId == ACTIVE_USER_ID && handler_.isDataShareReady_) {
469             handler_.CheckDataShareError();
470             handler_.CheckSimNotifyRegister();
471         }
472     }
473 }
474 
CheckSimNotifyRegister()475 void MultiSimMonitor::CheckSimNotifyRegister()
476 {
477     RemoveEvent(MultiSimMonitor::REGISTER_SIM_NOTIFY_RETRY_EVENT);
478     SetRemainCount(INIT_TIMES);
479     RegisterSimNotify();
480 }
481 
CheckDataShareError()482 void MultiSimMonitor::CheckDataShareError()
483 {
484     if (controller_->IsDataShareError() || GetBlockLoadOperatorConfig()) {
485         TELEPHONY_LOGI("CheckDataShareError or GetBlockLoadOperatorConfig is true, need Reset Opkey");
486         CheckOpcNeedUpdata(true);
487     }
488 }
489 
SetRemainCount(int remainCount)490 void MultiSimMonitor::SetRemainCount(int remainCount)
491 {
492     remainCount_ = remainCount;
493 }
494 
RegisterSimAccountCallback(const int32_t tokenId,const sptr<SimAccountCallback> & callback)495 int32_t MultiSimMonitor::RegisterSimAccountCallback(
496     const int32_t tokenId, const sptr<SimAccountCallback> &callback)
497 {
498     if (callback == nullptr) {
499         TELEPHONY_LOGE("callback is nullptr");
500         return TELEPHONY_ERR_ARGUMENT_NULL;
501     }
502     std::lock_guard<std::mutex> lock(mutexInner_);
503     bool isExisted = false;
504     for (auto &iter : listSimAccountCallbackRecord_) {
505         if (iter.simAccountCallback == nullptr) {
506             continue;
507         }
508         if (iter.simAccountCallback->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr()) {
509             isExisted = true;
510             break;
511         }
512     }
513     if (isExisted) {
514         TELEPHONY_LOGI("Ignore register action, since callback is existent");
515         return TELEPHONY_SUCCESS;
516     }
517 
518     SimAccountCallbackRecord simAccountRecord;
519     simAccountRecord.tokenId = tokenId;
520     simAccountRecord.simAccountCallback = callback;
521     deathRecipient_ = new (std::nothrow) SimAccountCallbackDeathRecipient(*this);
522     if (deathRecipient_ == nullptr) {
523         TELEPHONY_LOGE("deathRecipient is null");
524         return TELEPHONY_ERR_STRCPY_FAIL;
525     }
526     if (!callback->AsObject()->AddDeathRecipient(deathRecipient_)) {
527         TELEPHONY_LOGE("simAccountCallback remote server add death recipient failed");
528     }
529     listSimAccountCallbackRecord_.push_back(simAccountRecord);
530     TELEPHONY_LOGI("Register successfully, callback list size is %{public}zu", listSimAccountCallbackRecord_.size());
531     return TELEPHONY_SUCCESS;
532 }
533 
UnregisterSimAccountCallback(const sptr<SimAccountCallback> & callback)534 int32_t MultiSimMonitor::UnregisterSimAccountCallback(const sptr<SimAccountCallback> &callback)
535 {
536     if (callback == nullptr) {
537         TELEPHONY_LOGE("callback is nullptr");
538         return TELEPHONY_ERR_ARGUMENT_NULL;
539     }
540     std::lock_guard<std::mutex> lock(mutexInner_);
541     bool isSuccess = false;
542     auto iter = listSimAccountCallbackRecord_.begin();
543     for (; iter != listSimAccountCallbackRecord_.end();) {
544         if (iter->simAccountCallback == nullptr) {
545             iter++;
546             continue;
547         }
548         if (iter->simAccountCallback->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr()) {
549             iter = listSimAccountCallbackRecord_.erase(iter);
550             isSuccess = true;
551             break;
552         }
553         iter++;
554     }
555     if (!isSuccess) {
556         TELEPHONY_LOGE("Ignore unregister action, since callback is nonexistent");
557         return TELEPHONY_ERROR;
558     }
559     TELEPHONY_LOGI("Unregister successfully, callback list size is %{public}zu", listSimAccountCallbackRecord_.size());
560     return TELEPHONY_SUCCESS;
561 }
562 
GetSimAccountCallbackRecords()563 std::list<MultiSimMonitor::SimAccountCallbackRecord> MultiSimMonitor::GetSimAccountCallbackRecords()
564 {
565     std::lock_guard<std::mutex> lock(mutexInner_);
566     return listSimAccountCallbackRecord_;
567 }
568 
NotifySimAccountChanged()569 void MultiSimMonitor::NotifySimAccountChanged()
570 {
571     std::list<SimAccountCallbackRecord> CallbackRecord = GetSimAccountCallbackRecords();
572     TELEPHONY_LOGD("CallbackRecord size is %{public}zu", CallbackRecord.size());
573     for (auto iter : CallbackRecord) {
574         if (iter.simAccountCallback != nullptr) {
575             iter.simAccountCallback->OnSimAccountChanged();
576         }
577     }
578     DelayedRefSingleton<TelephonyStateRegistryClient>::GetInstance().UpdateIccAccount();
579 }
580 
RegisterSimNotify()581 void MultiSimMonitor::RegisterSimNotify()
582 {
583     if (isForgetAllDataDone_) {
584         TELEPHONY_LOGI("RegisterSimNotify has done");
585         return;
586     }
587     if (controller_ == nullptr) {
588         TELEPHONY_LOGE("MultiSimController is null");
589         return;
590     }
591     if (!controller_->ForgetAllData()) {
592         if (remainCount_ > 0) {
593             SendEvent(MultiSimMonitor::REGISTER_SIM_NOTIFY_RETRY_EVENT, 0, DELAY_TIME);
594             TELEPHONY_LOGI("retry remain %{public}d", static_cast<int32_t>(remainCount_));
595             remainCount_--;
596         }
597         return;
598     }
599     isForgetAllDataDone_ = true;
600     TELEPHONY_LOGI("Register with time left %{public}d", static_cast<int32_t>(remainCount_));
601     for (size_t slotId = 0; slotId < simFileManager_.size(); slotId++) {
602         RegisterSimNotify(static_cast<int32_t>(slotId));
603     }
604 }
605 
ResetSimLoadAccount(int32_t slotId)606 int32_t MultiSimMonitor::ResetSimLoadAccount(int32_t slotId)
607 {
608     if (!IsValidSlotId(slotId)) {
609         TELEPHONY_LOGE("ResetSimLoadAccount slotId is invalid");
610         return TELEPHONY_ERR_SLOTID_INVALID;
611     }
612     isSimAccountLoaded_[slotId] = 0;
613     initDataRemainCount_[slotId] = INIT_DATA_TIMES;
614     return TELEPHONY_SUCCESS;
615 }
616 
RegisterSimNotify(int32_t slotId)617 void MultiSimMonitor::RegisterSimNotify(int32_t slotId)
618 {
619     if (!IsValidSlotId(slotId)) {
620         TELEPHONY_LOGE("RegisterSimNotify slotId is invalid");
621         return;
622     }
623     std::shared_lock<ffrt::shared_mutex> lock(simStateMgrMutex_);
624     auto simFileManager = simFileManager_[slotId].lock();
625     if (simFileManager == nullptr) {
626         TELEPHONY_LOGE("simFileManager is null slotId : %{public}d", slotId);
627         return;
628     }
629     simFileManager->RegisterCoreNotify(shared_from_this(), RadioEvent::RADIO_QUERY_ICCID_DONE);
630     if (simStateManager_[slotId] == nullptr) {
631         TELEPHONY_LOGE("simStateManager is null slotId : %{public}d", slotId);
632         return;
633     }
634     simStateManager_[slotId]->RegisterCoreNotify(shared_from_this(), RadioEvent::RADIO_SIM_STATE_CHANGE);
635     simStateManager_[slotId]->RegisterCoreNotify(shared_from_this(), RadioEvent::RADIO_SIM_STATE_LOCKED);
636     simStateManager_[slotId]->RegisterCoreNotify(shared_from_this(), RadioEvent::RADIO_SIM_STATE_READY);
637     TELEPHONY_LOGI("RegisterSimNotify %{public}d", slotId);
638 }
639 
UnRegisterSimNotify()640 void MultiSimMonitor::UnRegisterSimNotify()
641 {
642     std::shared_lock<ffrt::shared_mutex> lock(simStateMgrMutex_);
643     for (size_t slotId = 0; slotId < simFileManager_.size(); slotId++) {
644         auto simFileManager = simFileManager_[slotId].lock();
645         if (simFileManager == nullptr) {
646             TELEPHONY_LOGE("simFileManager is null slotId : %{public}zu", slotId);
647             continue;
648         }
649         simFileManager->UnRegisterCoreNotify(shared_from_this(), RadioEvent::RADIO_QUERY_ICCID_DONE);
650         if (simStateManager_[slotId] == nullptr) {
651             TELEPHONY_LOGE("simStateManager is null slotId : %{public}zu", slotId);
652             continue;
653         }
654         simStateManager_[slotId]->UnRegisterCoreNotify(shared_from_this(), RadioEvent::RADIO_SIM_STATE_CHANGE);
655         simStateManager_[slotId]->UnRegisterCoreNotify(shared_from_this(), RadioEvent::RADIO_SIM_STATE_LOCKED);
656         simStateManager_[slotId]->UnRegisterCoreNotify(shared_from_this(), RadioEvent::RADIO_SIM_STATE_READY);
657     }
658 }
659 } // namespace Telephony
660 } // namespace OHOS
661