• 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_controller.h"
17 
18 #include <openssl/sha.h>
19 
20 #include "cellular_data_client.h"
21 #include "common_event_manager.h"
22 #include "common_event_support.h"
23 #include "core_manager_inner.h"
24 #include "core_service_errors.h"
25 #include "core_service_hisysevent.h"
26 #include "ims_core_service_client.h"
27 #include "tel_aes_crypto_util.h"
28 #include "parameters.h"
29 #include "sim_data.h"
30 #include "sim_utils.h"
31 #include "string_ex.h"
32 #include "telephony_ext_wrapper.h"
33 
34 #ifdef  CORE_SERVICE_SUPPORT_ESIM
35 #include "reset_response.h"
36 #endif
37 
38 namespace OHOS {
39 namespace Telephony {
40 const int64_t DELAY_TIME = 1000;
41 const int SET_PRIMARY_RETRY_TIMES = 5;
42 static const int32_t EVENT_CODE = 1;
43 static const int32_t IMS_SWITCH_VALUE_UNKNOWN = -1;
44 static const int32_t MODEM_ID_0 = 0;
45 static const int32_t MODEM_ID_1 = 1;
46 static const int32_t CARD_ATR_LEN = 65;
47 const int32_t SYSTEM_PARAMETER_LENGTH = 128;
48 constexpr int32_t IS_ESIM = 1;
49 constexpr int32_t PSIM1 = 1;
50 constexpr int32_t PSIM2 = 2;
51 constexpr int32_t PSIM1_PSIM2 = 0;
52 constexpr int32_t PSIM2_ESIM = 2;
53 static const std::string PARAM_SIMID = "simId";
54 static const std::string PARAM_SET_PRIMARY_STATUS = "setDone";
55 static const std::string DEFAULT_VOICE_SIMID_CHANGED = "defaultVoiceSimIdChanged";
56 static const std::string DEFAULT_SMS_SIMID_CHANGED = "defaultSmsSimIdChanged";
57 static const std::string DEFAULT_CELLULAR_DATA_SIMID_CHANGED = "defaultCellularDataSimIdChanged";
58 static const std::string DEFAULT_MAIN_SIMID_CHANGED = "defaultMainSimIdChanged";
59 static const std::string MAIN_CARD_ICCID_KEY = "persist.telephony.MainCard.Iccid";
60 static const std::string PRIMARY_SLOTID_KEY = "persist.telephony.MainSlotId";
61 static const std::string MAIN_CELLULAR_DATA_SLOTID_KEY = "persist.telephony.MainCellularDataSlotId";
62 static const std::string PRIMARY_SLOTID = "0";
63 constexpr int32_t SLOT_ID_1 = 1;
64 constexpr int32_t RIL_SET_PRIMARY_SLOT_TIMEOUT = 45 * 1000; // 45 second
65 const std::string RIL_SET_PRIMARY_SLOT_SUPPORTED = "const.vendor.ril.set_primary_slot_support";
66 static const std::string GSM_SIM_ATR = "gsm.sim.hw_atr";
67 static const std::string GSM_SIM_ATR1 = "gsm.sim.hw_atr1";
68 static const std::string SIM_LABEL_STATE_PROP = "persist.ril.sim_switch";
69 
MultiSimController(std::shared_ptr<Telephony::ITelRilManager> telRilManager,std::vector<std::shared_ptr<Telephony::SimStateManager>> simStateManager,std::vector<std::shared_ptr<Telephony::SimFileManager>> simFileManager)70 MultiSimController::MultiSimController(std::shared_ptr<Telephony::ITelRilManager> telRilManager,
71     std::vector<std::shared_ptr<Telephony::SimStateManager>> simStateManager,
72     std::vector<std::shared_ptr<Telephony::SimFileManager>> simFileManager)
73     : TelEventHandler("MultiSimController"), simStateManager_(simStateManager), simFileManager_(simFileManager)
74 {
75     TELEPHONY_LOGI("MultiSimController");
76     telRilManager_ = std::weak_ptr<ITelRilManager>(telRilManager);
77     radioProtocolController_ = std::make_shared<RadioProtocolController>(std::weak_ptr<ITelRilManager>(telRilManager));
78     InitMainCardSlotId();
79 }
80 
~MultiSimController()81 MultiSimController::~MultiSimController()
82 {
83     if (radioProtocolController_ != nullptr) {
84         radioProtocolController_->UnRegisterEvents();
85     }
86 }
87 
88 // set all data to invalid wait for InitData to rebuild
Init()89 void MultiSimController::Init()
90 {
91     if (simDbHelper_ == nullptr) {
92         simDbHelper_ = std::make_unique<SimRdbHelper>();
93     }
94     if (radioProtocolController_ != nullptr) {
95         radioProtocolController_->Init();
96     }
97     maxCount_ = SIM_SLOT_COUNT;
98     isSetActiveSimInProgress_.resize(maxCount_, 0);
99     setPrimarySlotRemainCount_.resize(maxCount_, SET_PRIMARY_RETRY_TIMES);
100     isRilSetPrimarySlotSupport_ =
101         system::GetBoolParameter(RIL_SET_PRIMARY_SLOT_SUPPORTED, false);
102     TELEPHONY_LOGI("Create SimRdbHelper count = %{public}d", maxCount_);
103 }
104 
ForgetAllData()105 bool MultiSimController::ForgetAllData()
106 {
107     if (simDbHelper_ == nullptr) {
108         TELEPHONY_LOGE("simDbHelper_ is nullptr failed");
109         return false;
110     }
111     TELEPHONY_LOGI("ForgetAllData %{public}zu", loadedSimCardInfo_.size());
112     int32_t forgetResult = simDbHelper_->ForgetAllData();
113     if (forgetResult != INVALID_VALUE) {
114         std::shared_lock<ffrt::shared_mutex> lock(loadedSimCardInfoMutex_);
115         for (auto& pair : loadedSimCardInfo_) {
116             UpdateDataByIccId(pair.first, pair.second);
117             TELEPHONY_LOGI("loadedSimCardInfo_ slotid: %{public}d", pair.first);
118         }
119         return true;
120     }
121     return false;
122 }
123 
ForgetAllData(int32_t slotId)124 bool MultiSimController::ForgetAllData(int32_t slotId)
125 {
126     if (simDbHelper_ == nullptr) {
127         TELEPHONY_LOGE("simDbHelper_ is nullptr");
128         return false;
129     }
130     bool isUpdateSimLabel = !IsEsim(slotId) && !isSimSlotsMapping_[slotId];
131     isSimSlotsMapping_[slotId] = false;
132     return simDbHelper_->ForgetAllData(slotId, isUpdateSimLabel) != INVALID_VALUE;
133 }
134 
AddExtraManagers(std::shared_ptr<Telephony::SimStateManager> simStateManager,std::shared_ptr<Telephony::SimFileManager> simFileManager)135 void MultiSimController::AddExtraManagers(std::shared_ptr<Telephony::SimStateManager> simStateManager,
136     std::shared_ptr<Telephony::SimFileManager> simFileManager)
137 {
138     if (static_cast<int>(simStateManager_.size()) == SIM_SLOT_COUNT) {
139         simStateManager_.push_back(simStateManager);
140         simFileManager_.push_back(simFileManager);
141         isSetActiveSimInProgress_.push_back(0);
142         maxCount_ = MAX_SLOT_COUNT;
143         size_t count = localCacheInfo_.size();
144         TELEPHONY_LOGI("localCacheInfo_.size() = %{public}lu, maxCount_ = %{public}d",
145             static_cast<unsigned long>(count), maxCount_);
146     }
147 }
148 
InitData(int32_t slotId)149 bool MultiSimController::InitData(int32_t slotId)
150 {
151     TELEPHONY_LOGI("slotId is %{public}d start", slotId);
152     if (!IsValidData(slotId)) {
153         TELEPHONY_LOGE("has no sim card, abandon");
154         return false;
155     }
156     if (!InitIccId(slotId)) { // check if we insert or reactive a data
157         TELEPHONY_LOGE("Can not init IccId");
158         return false;
159     }
160     if (!GetListFromDataBase()) { // init data base to local cache
161         TELEPHONY_LOGE("Can not get dataBase");
162         return false;
163     }
164     if (localCacheInfo_.size() <= 0) {
165         TELEPHONY_LOGE("sim not initialize");
166         return false;
167     }
168     if (!InitActive(slotId)) {
169         TELEPHONY_LOGE("InitActive failed");
170         return false;
171     }
172     if (!InitShowNumber(slotId)) {
173         TELEPHONY_LOGE("InitShowNumber failed");
174     }
175     if (InitPrimary()) {
176         TELEPHONY_LOGI("InitPrimary start");
177         CheckIfNeedSwitchMainSlotId();
178     }
179     GetAllListFromDataBase();
180     std::lock_guard<ffrt::shared_mutex> lock(loadedSimCardInfoMutex_);
181     std::string iccid = Str16ToStr8(simFileManager_[slotId]->GetSimIccId());
182     loadedSimCardInfo_[slotId] = iccid;
183     TELEPHONY_LOGI("sim account loaded, slotId %{public}d, simId %{public}d, loadedSimCardInfo_.size %{public}zu",
184         slotId, localCacheInfo_[slotId].simId, loadedSimCardInfo_.size());
185     return true;
186 }
187 
InitEsimData()188 bool MultiSimController::InitEsimData()
189 {
190     if (!GetAllListFromDataBase()) {
191         TELEPHONY_LOGE("cant get database");
192         return false;
193     }
194     return true;
195 }
196 
InitActive(int slotId)197 bool MultiSimController::InitActive(int slotId)
198 {
199     bool result = true;
200     if (!simStateManager_[slotId]->HasSimCard()) {
201         TELEPHONY_LOGI("has no sim and not need to active");
202         return result;
203     }
204     if (!IsSimActive(slotId)) {
205         result = (SetActiveSim(slotId, DEACTIVE, true) == TELEPHONY_ERR_SUCCESS);
206     }
207     if (IsSimActive(slotId)) {
208         result = (SetActiveSim(slotId, ACTIVE, true) == TELEPHONY_ERR_SUCCESS);
209     }
210     return result;
211 }
212 
InitPrimary()213 bool MultiSimController::InitPrimary()
214 {
215     if (maxCount_ <= 1) {
216         TELEPHONY_LOGI("no need to init");
217         return false;
218     }
219     if (!IsAllModemInitDone()) {
220         TELEPHONY_LOGI("wait for the other modem init");
221         return false;
222     }
223     unInitModemSlotId_ = INVALID_VALUE;
224     if (IsAllCardsReady() && !IsAllCardsLoaded()) {
225         TELEPHONY_LOGI("wait for the other card ready");
226         return false;
227     }
228     return true;
229 }
230 
ReCheckPrimary()231 void MultiSimController::ReCheckPrimary()
232 {
233     if (InitPrimary()) {
234         TELEPHONY_LOGI("start");
235         CheckIfNeedSwitchMainSlotId();
236     }
237 }
238 
IsAllCardsReady()239 bool MultiSimController::IsAllCardsReady()
240 {
241     for (int32_t i = 0; i < SIM_SLOT_COUNT; i++) {
242         if (simStateManager_[i] != nullptr && (simStateManager_[i]->GetSimState() == SimState::SIM_STATE_UNKNOWN
243             || simStateManager_[i]->GetSimState() == SimState::SIM_STATE_NOT_PRESENT)) {
244             TELEPHONY_LOGI("slotId %{public}d not ready", i);
245             return false;
246         }
247     }
248     return true;
249 }
250 
IsAllModemInitDone()251 bool MultiSimController::IsAllModemInitDone()
252 {
253     for (int32_t i = 0; i < SIM_SLOT_COUNT; i++) {
254         if (simStateManager_[i] != nullptr && !(simStateManager_[i]->IfModemInitDone())) {
255             TELEPHONY_LOGI("slotId %{public}d modem init not done", i);
256             unInitModemSlotId_ = i;
257             return false;
258         }
259     }
260     return true;
261 }
262 
IsDataShareError()263 bool MultiSimController::IsDataShareError()
264 {
265     return simDbHelper_ != nullptr && simDbHelper_->IsDataShareError();
266 }
267 
ResetDataShareError()268 void MultiSimController::ResetDataShareError()
269 {
270     if (simDbHelper_ != nullptr) {
271         simDbHelper_->ResetDataShareError();
272     }
273 }
274 
UpdateOpKeyInfo()275 int32_t MultiSimController::UpdateOpKeyInfo()
276 {
277     if (simDbHelper_ == nullptr) {
278         TELEPHONY_LOGE("simDbHelper is nullptr");
279         return TELEPHONY_ERROR;
280     }
281     return simDbHelper_->UpdateOpKeyInfo();
282 }
283 
IsAllCardsLoaded()284 bool MultiSimController::IsAllCardsLoaded()
285 {
286     if (localCacheInfo_.empty()) {
287         TELEPHONY_LOGI("there is no card loaded");
288         return false;
289     }
290     for (int32_t i = 0; i < SIM_SLOT_COUNT; i++) {
291         if (localCacheInfo_[i].iccId.empty()) {
292             TELEPHONY_LOGI("slotId %{public}d not loaded", i);
293             return false;
294         }
295     }
296     return true;
297 }
298 
InitIccId(int slotId)299 bool MultiSimController::InitIccId(int slotId)
300 {
301     if (simFileManager_[slotId] == nullptr) {
302         TELEPHONY_LOGE("can not get simFileManager");
303         return false;
304     }
305     std::string newIccId = Str16ToStr8(simFileManager_[slotId]->GetSimIccId());
306     if (newIccId.empty()) {
307         TELEPHONY_LOGI("iccid is empty.");
308         newIccId = "emptyiccid" + std::to_string(slotId);
309     }
310     if (simDbHelper_ == nullptr) {
311         TELEPHONY_LOGE("failed by nullptr");
312         return false;
313     }
314     int32_t result;
315     SimRdbInfo simRdbInfo;
316     std::unique_lock<ffrt::mutex> lock(writeDbMutex_);
317     if (simDbHelper_->QueryDataByIccId(newIccId, simRdbInfo) == INVALID_VALUE) {
318         TELEPHONY_LOGE("query fail");
319         return false;
320     }
321     if (!simRdbInfo.iccId.empty()) { // already have this card, reactive it
322         TELEPHONY_LOGI("old sim insert, slotId%{public}d", slotId);
323         if (IsEsim(slotId)) {
324             TELEPHONY_LOGI("esim no need update slotId");
325             result = TELEPHONY_ERR_SUCCESS;
326         }
327         result = UpdateDataByIccId(slotId, newIccId);
328     } else { // insert a new data for new IccId
329         TELEPHONY_LOGI("new sim insert, slotId%{public}d", slotId);
330         result = InsertData(slotId, newIccId);
331     }
332     if (result == INVALID_VALUE) {
333         TELEPHONY_LOGE("failed to init data");
334         return false;
335     }
336     TELEPHONY_LOGI("result is %{public}d", result);
337     return true;
338 }
339 
UpdateDataByIccId(int slotId,const std::string & newIccId)340 int32_t MultiSimController::UpdateDataByIccId(int slotId, const std::string &newIccId)
341 {
342     if (simDbHelper_ == nullptr) {
343         TELEPHONY_LOGE("failed by nullptr");
344         return INVALID_VALUE;
345     }
346     int32_t simLabelState = OHOS::system::GetIntParameter(SIM_LABEL_STATE_PROP, PSIM1_PSIM2);
347     int simLabelIndex = PSIM1;
348     if ((slotId == 0 && simLabelState == PSIM2_ESIM) || (slotId == 1 && simLabelState == PSIM1_PSIM2)) {
349         simLabelIndex = PSIM2;
350     }
351     DataShare::DataShareValuesBucket values;
352     DataShare::DataShareValueObject slotObj(slotId);
353     values.Put(SimData::SLOT_INDEX, slotObj);
354     if (!(slotId == 1 && simLabelState != PSIM1_PSIM2)) {
355         DataShare::DataShareValueObject labelIndexObj(simLabelIndex);
356         values.Put(SimData::SIM_LABEL_INDEX, labelIndexObj);
357     }
358     if (SIM_SLOT_COUNT == 1) {
359         DataShare::DataShareValueObject mainCardObj(MAIN_CARD);
360         values.Put(SimData::IS_MAIN_CARD, mainCardObj);
361         values.Put(SimData::IS_VOICE_CARD, mainCardObj);
362         values.Put(SimData::IS_MESSAGE_CARD, mainCardObj);
363         values.Put(SimData::IS_CELLULAR_DATA_CARD, mainCardObj);
364     }
365     return simDbHelper_->UpdateDataByIccId(newIccId, values);
366 }
367 
InsertData(int slotId,const std::string & newIccId)368 int32_t MultiSimController::InsertData(int slotId, const std::string &newIccId)
369 {
370     if (simDbHelper_ == nullptr) {
371         TELEPHONY_LOGE("failed by nullptr");
372         return INVALID_VALUE;
373     }
374     int32_t simLabelState = OHOS::system::GetIntParameter(SIM_LABEL_STATE_PROP, PSIM1_PSIM2);
375     int simLabelIndex = PSIM1;
376     if ((slotId == 0 && simLabelState == PSIM2_ESIM) || (slotId == 1 && simLabelState == PSIM1_PSIM2)) {
377         simLabelIndex = PSIM2;
378     }
379     DataShare::DataShareValuesBucket values;
380     DataShare::DataShareValueObject slotObj(slotId);
381     DataShare::DataShareValueObject iccidObj(newIccId);
382     DataShare::DataShareValueObject valueObj(ACTIVE);
383     DataShare::DataShareValueObject simLabelIndexObj(simLabelIndex);
384     DataShare::DataShareValueObject isEsimObj(IsEsim(slotId));
385     values.Put(SimData::SLOT_INDEX, slotObj);
386     values.Put(SimData::ICC_ID, iccidObj);
387     values.Put(SimData::CARD_ID, iccidObj); // iccId == cardId by now
388     values.Put(SimData::IS_ACTIVE, valueObj);
389     values.Put(SimData::SIM_LABEL_INDEX, simLabelIndexObj);
390     values.Put(SimData::IS_ESIM, isEsimObj);
391     if (SIM_SLOT_COUNT == 1) {
392         DataShare::DataShareValueObject mainCardObj(MAIN_CARD);
393         values.Put(SimData::IS_MAIN_CARD, mainCardObj);
394         values.Put(SimData::IS_VOICE_CARD, mainCardObj);
395         values.Put(SimData::IS_MESSAGE_CARD, mainCardObj);
396         values.Put(SimData::IS_CELLULAR_DATA_CARD, mainCardObj);
397     } else {
398         DataShare::DataShareValueObject notMainCardObj(NOT_MAIN);
399         values.Put(SimData::IS_MAIN_CARD, notMainCardObj);
400         values.Put(SimData::IS_VOICE_CARD, notMainCardObj);
401         values.Put(SimData::IS_MESSAGE_CARD, notMainCardObj);
402         values.Put(SimData::IS_CELLULAR_DATA_CARD, notMainCardObj);
403     }
404     int64_t id;
405     return simDbHelper_->InsertData(id, values);
406 }
407 
InsertEsimData(const std::string & iccId,int32_t esimLabel,const std::string & operatorName)408 int32_t MultiSimController::InsertEsimData(const std::string &iccId, int32_t esimLabel, const std::string &operatorName)
409 {
410     if (simDbHelper_ == nullptr) {
411         TELEPHONY_LOGE("failed by nullptr");
412         return INVALID_VALUE;
413     }
414     DataShare::DataShareValuesBucket values;
415     DataShare::DataShareValueObject slotObj(SLOT_ID_1);
416     DataShare::DataShareValueObject iccidObj(iccId);
417     DataShare::DataShareValueObject valueObj(DEACTIVE);
418     DataShare::DataShareValueObject simLabelIndexObj(esimLabel);
419     DataShare::DataShareValueObject isEsimObj(IS_ESIM);
420     DataShare::DataShareValueObject operatorNameObj(operatorName);
421     values.Put(SimData::SLOT_INDEX, slotObj);
422     values.Put(SimData::ICC_ID, iccidObj);
423     values.Put(SimData::CARD_ID, iccidObj); // iccId == cardId by now
424     values.Put(SimData::IS_ACTIVE, valueObj);
425     values.Put(SimData::IS_ESIM, isEsimObj);
426     values.Put(SimData::SIM_LABEL_INDEX, simLabelIndexObj);
427     values.Put(SimData::OPERATOR_NAME, operatorNameObj);
428     if (SIM_SLOT_COUNT == 1) {
429         DataShare::DataShareValueObject mainCardObj(MAIN_CARD);
430         values.Put(SimData::IS_MAIN_CARD, mainCardObj);
431         values.Put(SimData::IS_VOICE_CARD, mainCardObj);
432         values.Put(SimData::IS_MESSAGE_CARD, mainCardObj);
433         values.Put(SimData::IS_CELLULAR_DATA_CARD, mainCardObj);
434     } else {
435         DataShare::DataShareValueObject notMainCardObj(NOT_MAIN);
436         values.Put(SimData::IS_MAIN_CARD, notMainCardObj);
437         values.Put(SimData::IS_VOICE_CARD, notMainCardObj);
438         values.Put(SimData::IS_MESSAGE_CARD, notMainCardObj);
439         values.Put(SimData::IS_CELLULAR_DATA_CARD, notMainCardObj);
440     }
441     int64_t id;
442     std::unique_lock<ffrt::mutex> lock(writeDbMutex_);
443     int32_t ret = simDbHelper_->InsertData(id, values);
444     if (ret == TELEPHONY_SUCCESS) {
445         GetAllListFromDataBase();
446     }
447     return ret;
448 }
449 
SetSimLabelIndex(const std::string & iccId,int32_t labelIndex)450 int32_t MultiSimController::SetSimLabelIndex(const std::string &iccId, int32_t labelIndex)
451 {
452     if (simDbHelper_ == nullptr) {
453         TELEPHONY_LOGE("failed by nullptr");
454         return INVALID_VALUE;
455     }
456     DataShare::DataShareValuesBucket values;
457     DataShare::DataShareValueObject indexObj(labelIndex);
458     values.Put(SimData::SIM_LABEL_INDEX, indexObj);
459     if (simDbHelper_->UpdateDataByIccId(iccId, values) == TELEPHONY_ERR_SUCCESS) {
460         size_t count = allLocalCacheInfo_.size();
461         if (count <= 0) {
462             TELEPHONY_LOGE("allLocalCacheInfo_ empty");
463             return INVALID_VALUE;
464         }
465         for (size_t i = 0; i < count; i++) {
466             if (iccId == allLocalCacheInfo_[i].iccId) {
467                 allLocalCacheInfo_[i].simLabelIndex = labelIndex;
468             }
469         }
470         return TELEPHONY_ERR_SUCCESS;
471     }
472     return TELEPHONY_ERR_DATABASE_WRITE_FAIL;
473 }
474 
GetSimLabel(int32_t slotId,SimLabel & simLabel)475 int32_t MultiSimController::GetSimLabel(int32_t slotId, SimLabel &simLabel)
476 {
477     if (!IsValidData(slotId)) {
478         TELEPHONY_LOGE("InValidData");
479         return TELEPHONY_ERR_NO_SIM_CARD;
480     }
481     std::unique_lock<ffrt::mutex> lock(mutex_);
482     if (static_cast<uint32_t>(slotId) >= localCacheInfo_.size()) {
483         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
484         return TELEPHONY_ERR_ARGUMENT_INVALID;
485     }
486     if (localCacheInfo_[slotId].isEsim) {
487         simLabel.simType = SimType::ESIM;
488     }
489     simLabel.index = localCacheInfo_[slotId].simLabelIndex;
490     return TELEPHONY_ERR_SUCCESS;
491 }
492 
InitShowNumber(int slotId)493 bool MultiSimController::InitShowNumber(int slotId)
494 {
495     std::u16string showNumber;
496     if (!IsValidData(slotId)) {
497         TELEPHONY_LOGE("slotId %{public}d is invalid", slotId);
498         return false;
499     }
500     if (simFileManager_[slotId] == nullptr) {
501         TELEPHONY_LOGE("can not get simFileManager");
502         return false;
503     }
504     showNumber = simFileManager_[slotId]->GetSimTelephoneNumber();
505     int32_t result = TELEPHONY_ERROR;
506     if (!showNumber.empty()) {
507         result = SetShowNumberToDB(slotId, showNumber);
508         TELEPHONY_LOGI("Init slotId %{public}d get phone number from sim and save result: %{public}d", slotId, result);
509     }
510     return result == TELEPHONY_ERR_SUCCESS;
511 }
512 
GetListFromDataBase()513 bool MultiSimController::GetListFromDataBase()
514 {
515     std::vector<SimRdbInfo> newCache;
516     if (simDbHelper_ == nullptr) {
517         TELEPHONY_LOGE("failed by nullptr");
518         return false;
519     }
520     int32_t result = simDbHelper_->QueryAllValidData(newCache);
521     TELEPHONY_LOGI("QueryAllValidData result is %{public}d", result);
522     std::unique_lock<ffrt::mutex> lock(mutex_);
523     if (localCacheInfo_.size() > 0) {
524         localCacheInfo_.clear();
525     }
526     localCacheInfo_ = newCache;
527     SortCache();
528     return result != INVALID_VALUE;
529 }
530 
GetAllListFromDataBase()531 bool MultiSimController::GetAllListFromDataBase()
532 {
533     std::vector<SimRdbInfo> newCache;
534     if (simDbHelper_ == nullptr) {
535         TELEPHONY_LOGE("failed by nullptr");
536         return false;
537     }
538     int32_t result = simDbHelper_->QueryAllData(newCache);
539     TELEPHONY_LOGI("QueryAllData result is %{public}d", result);
540     std::unique_lock<ffrt::mutex> lock(mutex_);
541     if (allLocalCacheInfo_.size() > 0) {
542         allLocalCacheInfo_.clear();
543     }
544     allLocalCacheInfo_ = newCache;
545     SortAllCache();
546     return result != INVALID_VALUE;
547 }
548 
SortCache()549 void MultiSimController::SortCache()
550 {
551     size_t count = localCacheInfo_.size();
552     TELEPHONY_LOGI("count = %{public}lu", static_cast<unsigned long>(count));
553     if (count == 0) {
554         TELEPHONY_LOGE("empty");
555         return;
556     }
557     std::vector<SimRdbInfo> sortCache;
558     SimRdbInfo emptyUnit;
559     emptyUnit.isActive = DEACTIVE;
560     emptyUnit.iccId = "";
561     for (int i = 0; i < maxCount_; i++) {
562         emptyUnit.slotIndex = i;
563         sortCache.emplace_back(emptyUnit);
564     }
565     for (size_t j = 0; j < count; j++) {
566         TELEPHONY_LOGI(
567             "index = %{public}d j = %{public}lu", localCacheInfo_[j].slotIndex, static_cast<unsigned long>(j));
568         sortCache[localCacheInfo_[j].slotIndex] = localCacheInfo_[j];
569     }
570     localCacheInfo_ = sortCache;
571     count = localCacheInfo_.size();
572     TELEPHONY_LOGI("localCacheInfo_.size() = %{public}lu, maxCount_ = %{public}d",
573         static_cast<unsigned long>(count), maxCount_);
574 }
575 
SortAllCache()576 void MultiSimController::SortAllCache()
577 {
578     size_t count = allLocalCacheInfo_.size();
579     TELEPHONY_LOGI("count = %{public}lu", static_cast<unsigned long>(count));
580     if (count == 0) {
581         TELEPHONY_LOGE("empty");
582         return;
583     }
584     std::vector<SimRdbInfo> sortCache;
585     SimRdbInfo emptyUnit;
586     emptyUnit.isActive = DEACTIVE;
587     for (size_t i = 0; i < count; i++) {
588         sortCache.emplace_back(emptyUnit);
589     }
590     for (size_t j = 0; j < count; j++) {
591         TELEPHONY_LOGI(
592             "index = %{public}d j = %{public}lu", allLocalCacheInfo_[j].slotIndex, static_cast<unsigned long>(j));
593         if (allLocalCacheInfo_[j].simId - 1 < static_cast<int>(sortCache.size())) {
594             sortCache[allLocalCacheInfo_[j].simId - 1] = allLocalCacheInfo_[j];
595         }
596     }
597     allLocalCacheInfo_ = sortCache;
598 }
599 
600 /*
601  * check the data is valid, if we don't have SimCard the data is not valid
602  */
IsValidData(int32_t slotId)603 bool MultiSimController::IsValidData(int32_t slotId)
604 {
605     if ((slotId < DEFAULT_SIM_SLOT_ID) || (static_cast<uint32_t>(slotId) >= simStateManager_.size())) {
606         TELEPHONY_LOGE("can not get simStateManager");
607         return false;
608     }
609     if (simStateManager_.empty() || static_cast<uint32_t>(slotId) >= simStateManager_.size() ||
610         simStateManager_[slotId] == nullptr) {
611         TELEPHONY_LOGE("can not get simStateManager");
612         return false;
613     }
614     return simStateManager_[slotId]->HasSimCard();
615 }
616 
UpdateIccAccountInfoList(std::vector<IccAccountInfo> & accountInfoList,std::vector<SimRdbInfo> & localCacheInfo,bool isGetActiveAccountInfo)617 bool MultiSimController::UpdateIccAccountInfoList(
618     std::vector<IccAccountInfo> &accountInfoList, std::vector<SimRdbInfo> &localCacheInfo, bool isGetActiveAccountInfo)
619 {
620     std::unique_lock<ffrt::mutex> lock(mutex_);
621     if (localCacheInfo.empty()) {
622         return false;
623     }
624     if (accountInfoList.size() > 0) {
625         accountInfoList.clear();
626     }
627     IccAccountInfo iccAccountInfo;
628     for (const auto& info : localCacheInfo) {
629         if (isGetActiveAccountInfo && info.isActive != ACTIVE) {
630             continue;
631         }
632         iccAccountInfo.Init(info.simId, info.slotIndex);
633         iccAccountInfo.showName = Str8ToStr16(info.showName);
634         iccAccountInfo.showNumber = Str8ToStr16(info.phoneNumber);
635         iccAccountInfo.iccId = Str8ToStr16(info.iccId);
636         iccAccountInfo.isActive = info.isActive;
637         iccAccountInfo.isEsim =info.isEsim;
638         iccAccountInfo.simLabelIndex = info.simLabelIndex;
639         iccAccountInfo.operatorName = info.operatorName;
640         accountInfoList.emplace_back(iccAccountInfo);
641     }
642     return true;
643 }
644 
GetSlotId(int32_t simId)645 int32_t MultiSimController::GetSlotId(int32_t simId)
646 {
647     std::unique_lock<ffrt::mutex> lock(mutex_);
648     if (localCacheInfo_.empty()) {
649         TELEPHONY_LOGE("failed by nullptr");
650         return INVALID_VALUE;
651     }
652     std::vector<SimRdbInfo>::iterator it = localCacheInfo_.begin();
653 
654     while (it != localCacheInfo_.end()) { // loop data list
655         if (it->isActive == ACTIVE && it->simId == simId) { // pick Active item
656             return it->slotIndex;
657         }
658         ++it;
659     }
660     return INVALID_VALUE;
661 }
662 
GetSimId(int32_t slotId)663 int32_t MultiSimController::GetSimId(int32_t slotId)
664 {
665     IccAccountInfo iccAccountInfo;
666     if (GetSimAccountInfo(slotId, true, iccAccountInfo) == TELEPHONY_ERR_SUCCESS) {
667         return iccAccountInfo.simId;
668     }
669     return INVALID_VALUE;
670 }
671 
IsSimActive(int32_t slotId)672 bool MultiSimController::IsSimActive(int32_t slotId)
673 {
674     if (!IsValidData(slotId)) {
675         TELEPHONY_LOGE("slotId %{public}d is invalid", slotId);
676         return false;
677     }
678     if (static_cast<uint32_t>(slotId) >= localCacheInfo_.size()) {
679         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
680         return false;
681     }
682     return localCacheInfo_[slotId].isActive == ACTIVE ? true : false;
683 }
684 
UpdateSubState(int32_t slotId,int32_t enable)685 void MultiSimController::UpdateSubState(int32_t slotId, int32_t enable)
686 {
687     if (TELEPHONY_EXT_WRAPPER.updateSubState_) {
688         TELEPHONY_LOGI("TELEPHONY_EXT_WRAPPER UpdateSubState slotId %{public}d enable: %{public}d", slotId, enable);
689         TELEPHONY_EXT_WRAPPER.updateSubState_(slotId, enable);
690     }
691     isSetActiveSimInProgress_[slotId] = 0;
692 }
693 
UpdateDBSetActiveResult(int32_t slotId,int32_t enable,int32_t curSimId)694 int32_t MultiSimController::UpdateDBSetActiveResult(int32_t slotId, int32_t enable, int32_t curSimId)
695 {
696     if (simDbHelper_ == nullptr) {
697         TELEPHONY_LOGE("failed by nullptr");
698         isSetActiveSimInProgress_[slotId] = 0;
699         return TELEPHONY_ERR_LOCAL_PTR_NULL;
700     }
701     DataShare::DataShareValuesBucket values;
702     DataShare::DataShareValueObject valueObj(enable);
703     values.Put(SimData::IS_ACTIVE, valueObj);
704     int32_t result = simDbHelper_->UpdateDataBySimId(curSimId, values);
705     if (result == INVALID_VALUE) {
706         TELEPHONY_LOGE("failed by database");
707         isSetActiveSimInProgress_[slotId] = 0;
708         return TELEPHONY_ERR_DATABASE_WRITE_FAIL;
709     }
710     return TELEPHONY_ERR_SUCCESS;
711 }
712 
UpdataCacheSetActiveState(int32_t slotId,int32_t enable,int32_t curSimId)713 int32_t MultiSimController::UpdataCacheSetActiveState(int32_t slotId, int32_t enable, int32_t curSimId)
714 {
715     std::unique_lock<ffrt::mutex> lock(mutex_);
716     if (static_cast<uint32_t>(slotId) >= localCacheInfo_.size()) {
717         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
718         isSetActiveSimInProgress_[slotId] = 0;
719         return TELEPHONY_ERR_ARGUMENT_INVALID;
720     }
721     localCacheInfo_[slotId].isActive = enable;
722     if (curSimId - 1 >= static_cast<int>(allLocalCacheInfo_.size()) || curSimId - 1 < 0) {
723         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
724         isSetActiveSimInProgress_[slotId] = 0;
725         return TELEPHONY_ERR_ARRAY_OUT_OF_BOUNDS;
726     }
727     allLocalCacheInfo_[curSimId - 1].isActive = enable;
728     lock.unlock();
729     UpdateSubState(slotId, enable);
730     return TELEPHONY_ERR_SUCCESS;
731 }
732 
SetActiveCommonSim(int32_t slotId,int32_t enable,bool force,int32_t curSimId)733 int32_t MultiSimController::SetActiveCommonSim(int32_t slotId, int32_t enable, bool force, int32_t curSimId)
734 {
735     isSetActiveSimInProgress_[slotId] = 1;
736     std::unique_lock<ffrt::mutex> lck(activeSimMutex_);
737     while (isSetPrimarySlotIdInProgress_) {
738         TELEPHONY_LOGI("isSetSimSlotInProgress_ is true, waiting");
739         if (activeSimConn_.wait_for(lck, std::chrono::seconds(WAIT_REMOTE_TIME_SEC)) == ffrt::cv_status::timeout) {
740             TELEPHONY_LOGI("SetPrimarySlotIdDone() wait timeout");
741             break;
742         }
743     }
744     if (!SetActiveSimToRil(slotId, ENTITY_CARD, enable)) {
745         CoreServiceHiSysEvent::WriteSetActiveSimFaultEvent(
746             slotId, SimCardErrorCode::SET_ACTIVESIM_ERROR, "SetActiveSimToRil failure");
747         isSetActiveSimInProgress_[slotId] = 0;
748         return TELEPHONY_ERR_RIL_CMD_FAIL;
749     }
750     if (force) {
751         UpdateSubState(slotId, enable);
752         return TELEPHONY_ERR_SUCCESS;
753     }
754     int32_t result = UpdataCacheSetActiveState(slotId, enable, curSimId);
755     if (result != TELEPHONY_ERR_SUCCESS) {
756         return result;
757     }
758     result = UpdateDBSetActiveResult(slotId, enable, curSimId);
759     if (result != TELEPHONY_ERR_SUCCESS) {
760         return result;
761     }
762     std::unique_lock<ffrt::mutex> lock(mutex_);
763     if (static_cast<uint32_t>(slotId) >= localCacheInfo_.size()) {
764         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
765         isSetActiveSimInProgress_[slotId] = 0;
766         return TELEPHONY_ERR_ARGUMENT_INVALID;
767     }
768     localCacheInfo_[slotId].isActive = enable;
769     if (curSimId - 1 >= static_cast<int>(allLocalCacheInfo_.size()) || curSimId - 1 < 0) {
770         return TELEPHONY_ERR_ARRAY_OUT_OF_BOUNDS;
771     }
772     allLocalCacheInfo_[curSimId - 1].isActive = enable;
773     lock.unlock();
774     UpdateSubState(slotId, enable);
775     CheckIfNeedSwitchMainSlotId(false);
776     return TELEPHONY_ERR_SUCCESS;
777 }
778 
SetActiveSim(int32_t slotId,int32_t enable,bool force)779 int32_t MultiSimController::SetActiveSim(int32_t slotId, int32_t enable, bool force)
780 {
781     TELEPHONY_LOGI("enable = %{public}d slotId = %{public}d", enable, slotId);
782     if ((!IsValidData(slotId)) && !IsEsim(slotId)) {
783         TELEPHONY_LOGE("slotId %{public}d is invalid", slotId);
784         return TELEPHONY_ERR_NO_SIM_CARD;
785     }
786     int curSimId = 0;
787     if ((GetTargetSimId(slotId, curSimId) != TELEPHONY_ERR_SUCCESS) && !IsEsim(slotId)) {
788         TELEPHONY_LOGE("failed by out of range");
789         return TELEPHONY_ERR_ARGUMENT_INVALID;
790     }
791     return SetActiveCommonSim(slotId, enable, force, curSimId);
792 }
793 
SetActiveSimSatellite(int32_t slotId,int32_t enable,bool force)794 int32_t MultiSimController::SetActiveSimSatellite(int32_t slotId, int32_t enable, bool force)
795 {
796     TELEPHONY_LOGI("SetActiveSimSatellite enable = %{public}d slotId = %{public}d", enable, slotId);
797     if (!IsValidData(slotId)) {
798         TELEPHONY_LOGE("slotId %{public}d is invalid", slotId);
799         return TELEPHONY_ERR_NO_SIM_CARD;
800     }
801     int curSimId = 0;
802     if (GetTargetSimId(slotId, curSimId) != TELEPHONY_ERR_SUCCESS) {
803         TELEPHONY_LOGE("failed by out of range");
804         return TELEPHONY_ERR_ARGUMENT_INVALID;
805     }
806     isSetActiveSimInProgress_[slotId] = ACTIVE_SIM_IN_PROGRESS;
807     if (force) {
808         TELEPHONY_LOGD("no need to update cache");
809         UpdateSubState(slotId, enable);
810         return TELEPHONY_ERR_SUCCESS;
811     }
812     if (simDbHelper_ == nullptr) {
813         TELEPHONY_LOGE("failed by nullptr");
814         isSetActiveSimInProgress_[slotId] = ACTIVE_SIM_NOT_IN_PROGRESS;
815         return TELEPHONY_ERR_LOCAL_PTR_NULL;
816     }
817     DataShare::DataShareValuesBucket values;
818     DataShare::DataShareValueObject valueObj(enable);
819     values.Put(SimData::IS_ACTIVE, valueObj);
820     int32_t result = simDbHelper_->UpdateDataBySimId(curSimId, values);
821     if (result == INVALID_VALUE) {
822         TELEPHONY_LOGE("failed by database");
823         isSetActiveSimInProgress_[slotId] = ACTIVE_SIM_NOT_IN_PROGRESS;
824         return TELEPHONY_ERR_DATABASE_WRITE_FAIL;
825     }
826     std::unique_lock<ffrt::mutex> lock(mutex_);
827     if (static_cast<uint32_t>(slotId) >= localCacheInfo_.size()) {
828         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
829         isSetActiveSimInProgress_[slotId] = ACTIVE_SIM_NOT_IN_PROGRESS;
830         return TELEPHONY_ERR_ARGUMENT_INVALID;
831     }
832     localCacheInfo_[slotId].isActive = enable;
833     if (curSimId - 1 >= static_cast<int>(allLocalCacheInfo_.size()) || curSimId - 1 < 0) {
834         return TELEPHONY_ERR_ARRAY_OUT_OF_BOUNDS;
835     }
836     allLocalCacheInfo_[curSimId - 1].isActive = enable;
837     lock.unlock();
838     UpdateSubState(slotId, enable);
839     CheckIfNeedSwitchMainSlotId(false);
840     return TELEPHONY_ERR_SUCCESS;
841 }
842 
CheckIfNeedSwitchMainSlotId(bool isInit)843 void MultiSimController::CheckIfNeedSwitchMainSlotId(bool isInit)
844 {
845     TELEPHONY_LOGD("start");
846     bool satelliteStatusOn = CoreManagerInner::GetInstance().IsSatelliteEnabled();
847     if (IsSatelliteSupported() == static_cast<int32_t>(SatelliteValue::SATELLITE_SUPPORTED) && satelliteStatusOn) {
848         TELEPHONY_LOGI("satelliteStatusOn");
849         return;
850     }
851     int32_t defaultSlotId = GetDefaultMainSlotByIccId();
852     if (IsSimActive(defaultSlotId)) {
853         if (IsAllCardsReady() && defaultSlotId != lastPrimarySlotId_) {
854             TELEPHONY_LOGI("defaultSlotId changed, need to set slot%{public}d primary", defaultSlotId);
855             if (radioProtocolController_ != nullptr &&
856                 radioProtocolController_->GetRadioProtocolModemId(defaultSlotId) == MODEM_ID_0) {
857                 isInit = false;
858             }
859             std::thread initDataTask([&, defaultSlotId = defaultSlotId, isInit = isInit]() {
860                 pthread_setname_np(pthread_self(), "SetPrimarySlotId");
861                 CoreManagerInner::GetInstance().SetPrimarySlotId(defaultSlotId, !isInit);
862             });
863             initDataTask.detach();
864         } else if (radioProtocolController_->GetRadioProtocolModemId(defaultSlotId) != MODEM_ID_0 && isInit) {
865             TELEPHONY_LOGI("main slot is different with modemid, need to set slot%{public}d primary", defaultSlotId);
866             std::thread initDataTask([&, defaultSlotId = defaultSlotId, isInit = isInit]() {
867                 pthread_setname_np(pthread_self(), "SetPrimarySlotId");
868                 CoreManagerInner::GetInstance().SetPrimarySlotId(defaultSlotId, !isInit);
869             });
870             initDataTask.detach();
871         } else {
872             TELEPHONY_LOGI("no need set main slot, defaultslot same main slot");
873             SavePrimarySlotIdInfo(defaultSlotId);
874         }
875     } else {
876         int32_t firstActivedSlotId = GetFirstActivedSlotId();
877         if (!IsValidSlotId(firstActivedSlotId)) {
878             TELEPHONY_LOGE("active slotId is invalid");
879             return;
880         }
881         TELEPHONY_LOGI("single card active, need to set slot%{public}d primary", firstActivedSlotId);
882         if (radioProtocolController_ != nullptr &&
883             radioProtocolController_->GetRadioProtocolModemId(firstActivedSlotId) == MODEM_ID_0) {
884             isInit = false;
885         }
886         std::thread initDataTask([&, firstActivedSlotId = firstActivedSlotId, isInit = isInit]() {
887             pthread_setname_np(pthread_self(), "SetPrimarySlotId");
888             CoreManagerInner::GetInstance().SetPrimarySlotId(firstActivedSlotId, !isInit);
889         });
890         initDataTask.detach();
891     }
892 }
893 
GetDefaultMainSlotByIccId()894 int32_t MultiSimController::GetDefaultMainSlotByIccId()
895 {
896     if (SIM_SLOT_COUNT == std::atoi(DEFAULT_SLOT_COUNT)) {
897         TELEPHONY_LOGI("default slotId is 0 for single card version");
898         return DEFAULT_SIM_SLOT_ID;
899     }
900     int mainSlot = lastPrimarySlotId_;
901     if (simFileManager_[SIM_SLOT_0] == nullptr || simFileManager_[SIM_SLOT_1] == nullptr) {
902         TELEPHONY_LOGE("simFileManager_ is null");
903         return mainSlot;
904     }
905     std::string iccIdSub1 = Str16ToStr8(simFileManager_[SIM_SLOT_0]->GetSimIccId());
906     std::string iccIdSub2 = Str16ToStr8(simFileManager_[SIM_SLOT_1]->GetSimIccId());
907     if (iccIdSub1.empty() || iccIdSub2.empty()) {
908         TELEPHONY_LOGD("iccid is null");
909         return mainSlot;
910     }
911     std::string encryptIccIdSub1 = EncryptIccId(iccIdSub1);
912     std::string encryptIccIdSub2 = EncryptIccId(iccIdSub2);
913     char lastMainCardIccId[SYSTEM_PARAMETER_LENGTH] = { 0 };
914     GetParameter(MAIN_CARD_ICCID_KEY.c_str(), "", lastMainCardIccId, SYSTEM_PARAMETER_LENGTH);
915     if (lastMainCardIccId == encryptIccIdSub1) {
916         mainSlot = SIM_SLOT_0;
917     } else if (lastMainCardIccId == encryptIccIdSub2) {
918         mainSlot = SIM_SLOT_1;
919     }
920     TELEPHONY_LOGI("slotId %{public}d", mainSlot);
921     return mainSlot;
922 }
923 
IsValidSlotId(int32_t slotId)924 bool MultiSimController::IsValidSlotId(int32_t slotId)
925 {
926     return ((slotId >= DEFAULT_SIM_SLOT_ID) && (slotId < SIM_SLOT_COUNT));
927 }
928 
SetActiveSimToRil(int32_t slotId,int32_t type,int32_t enable)929 bool MultiSimController::SetActiveSimToRil(int32_t slotId, int32_t type, int32_t enable)
930 {
931     if (radioProtocolController_ == nullptr) {
932         TELEPHONY_LOGE("radioProtocolController_ is nullptr");
933         return false;
934     }
935     std::unique_lock<ffrt::mutex> lck(radioProtocolController_->ctx_);
936     radioProtocolController_->RadioProtocolControllerWait();
937     if (!radioProtocolController_->SetActiveSimToRil(slotId, type, enable)) {
938         TELEPHONY_LOGE("SetActiveSimToRil failed");
939         return false;
940     }
941     while (!radioProtocolController_->RadioProtocolControllerPoll()) {
942         TELEPHONY_LOGI("SetActiveSimToRil wait");
943         radioProtocolController_->cv_.wait(lck);
944     }
945     return radioProtocolController_->GetActiveSimToRilResult() == static_cast<int32_t>(ErrType::NONE);
946 }
947 
GetSimAccountInfo(int32_t slotId,bool denied,IccAccountInfo & info)948 int32_t MultiSimController::GetSimAccountInfo(int32_t slotId, bool denied, IccAccountInfo &info)
949 {
950     if (!IsValidData(slotId)) {
951         TELEPHONY_LOGW("slotId %{public}d is invalid", slotId);
952         return TELEPHONY_ERR_NO_SIM_CARD;
953     }
954     std::unique_lock<ffrt::mutex> lock(mutex_);
955     if (static_cast<uint32_t>(slotId) >= localCacheInfo_.size()) {
956         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
957         return TELEPHONY_ERR_SLOTID_INVALID;
958     }
959     if (localCacheInfo_[slotId].iccId.empty()) {
960         TELEPHONY_LOGE("slotId %{public}d not loaded", slotId);
961         return CORE_ERR_SIM_CARD_LOAD_FAILED;
962     }
963     info.slotIndex = localCacheInfo_[slotId].slotIndex;
964     info.simId = localCacheInfo_[slotId].simId;
965     info.isActive = localCacheInfo_[slotId].isActive;
966     info.showName = Str8ToStr16(localCacheInfo_[slotId].showName);
967     info.isEsim = localCacheInfo_[slotId].isEsim;
968     if (!denied) {
969         info.showNumber = Str8ToStr16(localCacheInfo_[slotId].phoneNumber);
970         info.iccId = Str8ToStr16(localCacheInfo_[slotId].iccId);
971     }
972     return TELEPHONY_ERR_SUCCESS;
973 }
974 
GetDefaultVoiceSlotId()975 int32_t MultiSimController::GetDefaultVoiceSlotId()
976 {
977     std::unique_lock<ffrt::mutex> lock(mutex_);
978     if (localCacheInfo_.size() <= 0) {
979         TELEPHONY_LOGE("sim not initialize");
980         return INVALID_VALUE;
981     }
982     int32_t i = DEFAULT_SIM_SLOT_ID;
983     for (; i < static_cast<int32_t>(localCacheInfo_.size()); i++) {
984         if (localCacheInfo_[i].isVoiceCard == MAIN_CARD && localCacheInfo_[i].isActive == ACTIVE) {
985             return i;
986         }
987     }
988     return INVALID_VALUE;
989 }
990 
GetLocalCacheSize()991 size_t MultiSimController::GetLocalCacheSize()
992 {
993     std::unique_lock<ffrt::mutex> lock(mutex_);
994     return localCacheInfo_.size();
995 }
996 
GetTargetSimId(int32_t slotId,int & simId)997 int32_t MultiSimController::GetTargetSimId(int32_t slotId, int &simId)
998 {
999     std::unique_lock<ffrt::mutex> lock(mutex_);
1000     simId = 0;
1001     if (static_cast<uint32_t>(slotId) >= localCacheInfo_.size()) {
1002         return TELEPHONY_ERR_ARGUMENT_INVALID;
1003     }
1004     simId = localCacheInfo_[slotId].simId;
1005     return TELEPHONY_ERR_SUCCESS;
1006 }
1007 
GetFirstActivedSlotId()1008 int32_t MultiSimController::GetFirstActivedSlotId()
1009 {
1010     int32_t i = DEFAULT_SIM_SLOT_ID;
1011     for (; i < maxCount_; i++) {
1012         if (localCacheInfo_[i].isActive == ACTIVE) {
1013             return localCacheInfo_[i].slotIndex;
1014         }
1015     }
1016     return INVALID_VALUE;
1017 }
1018 
SetDefaultVoiceSlotId(int32_t slotId)1019 int32_t MultiSimController::SetDefaultVoiceSlotId(int32_t slotId)
1020 {
1021     TELEPHONY_LOGI("slotId %{public}d", slotId);
1022     int curSimId = 0;
1023     int32_t ret = GetTargetDefaultSimId(slotId, curSimId);
1024     if (ret != TELEPHONY_ERR_SUCCESS) {
1025         TELEPHONY_LOGE("ret is %{public}d", ret);
1026         return ret;
1027     }
1028     if (simDbHelper_ == nullptr) {
1029         TELEPHONY_LOGE("failed by nullptr");
1030         return TELEPHONY_ERR_LOCAL_PTR_NULL;
1031     }
1032     int32_t result = simDbHelper_->SetDefaultVoiceCard(curSimId);
1033     if (result == INVALID_VALUE) {
1034         TELEPHONY_LOGE("get Data Base failed");
1035         return TELEPHONY_ERR_DATABASE_WRITE_FAIL;
1036     }
1037     int32_t i = DEFAULT_SIM_SLOT_ID;
1038     std::unique_lock<ffrt::mutex> lock(mutex_);
1039     if (localCacheInfo_.size() <= 0) {
1040         TELEPHONY_LOGE("sim not initialize");
1041         return TELEPHONY_ERR_NO_SIM_CARD;
1042     }
1043     for (; i < static_cast<int32_t>(localCacheInfo_.size()); i++) { // save to cache
1044         if (slotId == i) {
1045             localCacheInfo_[i].isVoiceCard = MAIN_CARD;
1046             curSimId = localCacheInfo_[i].simId;
1047             continue;
1048         }
1049         localCacheInfo_[i].isVoiceCard = NOT_MAIN;
1050     }
1051     lock.unlock();
1052     if (curSimId == defaultVoiceSimId_) {
1053         TELEPHONY_LOGE("no need to AnnounceDefaultVoiceSimIdChanged");
1054         return TELEPHONY_ERR_SUCCESS;
1055     }
1056     defaultVoiceSimId_ = curSimId;
1057     if (!AnnounceDefaultVoiceSimIdChanged(defaultVoiceSimId_)) {
1058         return TELEPHONY_ERR_PUBLISH_BROADCAST_FAIL;
1059     }
1060     return TELEPHONY_ERR_SUCCESS;
1061 }
1062 
GetDefaultSmsSlotId()1063 int32_t MultiSimController::GetDefaultSmsSlotId()
1064 {
1065     std::unique_lock<ffrt::mutex> lock(mutex_);
1066     if (localCacheInfo_.size() <= 0) {
1067         TELEPHONY_LOGE("sim not initialize");
1068         return INVALID_VALUE;
1069     }
1070     int32_t i = DEFAULT_SIM_SLOT_ID;
1071     for (; i < static_cast<int32_t>(localCacheInfo_.size()); i++) {
1072         if (localCacheInfo_[i].isMessageCard == MAIN_CARD && localCacheInfo_[i].isActive == ACTIVE) {
1073             return i;
1074         }
1075     }
1076     return GetFirstActivedSlotId();
1077 }
1078 
SetDefaultSmsSlotId(int32_t slotId)1079 int32_t MultiSimController::SetDefaultSmsSlotId(int32_t slotId)
1080 {
1081     TELEPHONY_LOGD("slotId %{public}d", slotId);
1082     int curSimId = 0;
1083     int32_t ret = GetTargetDefaultSimId(slotId, curSimId);
1084     if (ret != TELEPHONY_ERR_SUCCESS) {
1085         TELEPHONY_LOGE("ret is %{public}d", ret);
1086         return ret;
1087     }
1088     if (simDbHelper_ == nullptr) {
1089         TELEPHONY_LOGE("failed by nullptr");
1090         return TELEPHONY_ERR_LOCAL_PTR_NULL;
1091     }
1092     int32_t result = simDbHelper_->SetDefaultMessageCard(curSimId);
1093     if (result == INVALID_VALUE) {
1094         TELEPHONY_LOGE("get Data Base failed");
1095         return TELEPHONY_ERR_DATABASE_WRITE_FAIL;
1096     }
1097     int32_t i = DEFAULT_SIM_SLOT_ID;
1098     std::unique_lock<ffrt::mutex> lock(mutex_);
1099     if (localCacheInfo_.size() <= 0) {
1100         TELEPHONY_LOGE("sim not initialize");
1101         return TELEPHONY_ERR_NO_SIM_CARD;
1102     }
1103     for (; i < static_cast<int32_t>(localCacheInfo_.size()); i++) { // save to cache
1104         if (slotId == i) {
1105             localCacheInfo_[i].isMessageCard = MAIN_CARD;
1106             curSimId = localCacheInfo_[slotId].simId;
1107             continue;
1108         }
1109         localCacheInfo_[i].isMessageCard = NOT_MAIN;
1110     }
1111     lock.unlock();
1112     if (curSimId == defaultSmsSimId_) {
1113         TELEPHONY_LOGE("no need to AnnounceDefaultSmsSimIdChanged");
1114         return TELEPHONY_ERR_SUCCESS;
1115     }
1116     defaultSmsSimId_ = curSimId;
1117     if (!AnnounceDefaultSmsSimIdChanged(defaultSmsSimId_)) {
1118         return TELEPHONY_ERR_PUBLISH_BROADCAST_FAIL;
1119     }
1120     return TELEPHONY_ERR_SUCCESS;
1121 }
1122 
GetTargetDefaultSimId(int32_t slotId,int & simId)1123 int32_t MultiSimController::GetTargetDefaultSimId(int32_t slotId, int &simId)
1124 {
1125     std::unique_lock<ffrt::mutex> lock(mutex_);
1126     simId = 0;
1127     if ((slotId == DEFAULT_SIM_SLOT_ID_REMOVE && localCacheInfo_.empty()) ||
1128         (slotId != DEFAULT_SIM_SLOT_ID_REMOVE && !IsValidData(slotId))) {
1129         TELEPHONY_LOGE("no sim card");
1130         return TELEPHONY_ERR_NO_SIM_CARD;
1131     }
1132     if (slotId != DEFAULT_SIM_SLOT_ID_REMOVE && !IsSimActive(slotId)) {
1133         TELEPHONY_LOGE("slotId is not active!");
1134         return CORE_SERVICE_SIM_CARD_IS_NOT_ACTIVE;
1135     }
1136     if (slotId != DEFAULT_SIM_SLOT_ID_REMOVE) {
1137         simId = localCacheInfo_[slotId].simId;
1138     }
1139     return TELEPHONY_ERR_SUCCESS;
1140 }
1141 
GetDefaultCellularDataSlotId()1142 int32_t MultiSimController::GetDefaultCellularDataSlotId()
1143 {
1144     TELEPHONY_LOGD("start lastCellularDataSlotId_ is %{public}d", lastCellularDataSlotId_);
1145     return lastCellularDataSlotId_;
1146 }
1147 
SetDefaultCellularDataSlotId(int32_t slotId)1148 int32_t MultiSimController::SetDefaultCellularDataSlotId(int32_t slotId)
1149 {
1150     SaveDefaultCellularDataSlotIdInfo(slotId);
1151     CoreServiceHiSysEvent::WriteDefaultDataSlotIdBehaviorEvent(slotId);
1152     return TELEPHONY_ERR_SUCCESS;
1153 }
1154 
GetPrimarySlotId()1155 int32_t MultiSimController::GetPrimarySlotId()
1156 {
1157     TELEPHONY_LOGD("start lastPrimarySlotId_ is %{public}d", lastPrimarySlotId_);
1158     return lastPrimarySlotId_;
1159 }
1160 
SetPrimarySlotIdDone()1161 void MultiSimController::SetPrimarySlotIdDone()
1162 {
1163     PublishSetPrimaryEvent(true);
1164     std::unique_lock<ffrt::mutex> lock(activeSimMutex_);
1165     isSetPrimarySlotIdInProgress_ = false;
1166     activeSimConn_.notify_all();
1167 }
1168 
SetPrimarySlotId(int32_t slotId,bool isUserSet)1169 int32_t MultiSimController::SetPrimarySlotId(int32_t slotId, bool isUserSet)
1170 {
1171     if (isUserSet && isRilSetPrimarySlotSupport_) {
1172         return SetPrimarySlotIdWithoutModemReboot(slotId);
1173     }
1174     TELEPHONY_LOGD("slotId = %{public}d", slotId);
1175     if (TELEPHONY_EXT_WRAPPER.isHandleVSim_ && TELEPHONY_EXT_WRAPPER.isHandleVSim_()) {
1176         TELEPHONY_LOGE("in vsim handle, not allowed switch card");
1177         return TELEPHONY_ERR_FAIL;
1178     }
1179     if (!IsValidData(slotId)) {
1180         TELEPHONY_LOGE("no sim card");
1181         return TELEPHONY_ERR_NO_SIM_CARD;
1182     }
1183     if (radioProtocolController_ != nullptr &&
1184         radioProtocolController_->GetRadioProtocolModemId(slotId) == MODEM_ID_0) {
1185         TELEPHONY_LOGI("The current slot is the main slot, no need to set primary slot");
1186         SavePrimarySlotIdInfo(slotId);
1187         setPrimarySlotRemainCount_[slotId] = SET_PRIMARY_RETRY_TIMES;
1188         RemoveEvent(MultiSimController::SET_PRIMARY_SLOT_RETRY_EVENT);
1189         return TELEPHONY_ERR_SUCCESS;
1190     }
1191     // change protocol for default cellulardata slotId
1192     isSetPrimarySlotIdInProgress_ = true;
1193     PublishSetPrimaryEvent(false);
1194     if (radioProtocolController_ == nullptr || !radioProtocolController_->SetRadioProtocol(slotId)) {
1195         TELEPHONY_LOGE("SetRadioProtocol failed");
1196         SetPrimarySlotIdDone();
1197         if (setPrimarySlotRemainCount_[slotId] > 0) {
1198             SendEvent(MultiSimController::SET_PRIMARY_SLOT_RETRY_EVENT, slotId, DELAY_TIME);
1199             TELEPHONY_LOGI("SetPrimarySlotId retry remain %{public}d, slotId = %{public}d",
1200                 setPrimarySlotRemainCount_[slotId], slotId);
1201             setPrimarySlotRemainCount_[slotId]--;
1202         }
1203         return TELEPHONY_ERR_LOCAL_PTR_NULL;
1204     }
1205     SavePrimarySlotIdInfo(slotId);
1206     SetPrimarySlotIdDone();
1207     setPrimarySlotRemainCount_[slotId] = SET_PRIMARY_RETRY_TIMES;
1208     RemoveEvent(MultiSimController::SET_PRIMARY_SLOT_RETRY_EVENT);
1209     return TELEPHONY_ERR_SUCCESS;
1210 }
1211 
ResetSetPrimarySlotRemain(int32_t slotId)1212 void MultiSimController::ResetSetPrimarySlotRemain(int32_t slotId)
1213 {
1214     if (slotId < DEFAULT_SIM_SLOT_ID || slotId >= SIM_SLOT_COUNT) {
1215         TELEPHONY_LOGE("It is invalid slotId, slotId = %{public}d", slotId);
1216         return;
1217     }
1218     TELEPHONY_LOGI("ResetSetPrimarySlotRemain, slotId = %{public}d", slotId);
1219     setPrimarySlotRemainCount_[slotId] = SET_PRIMARY_RETRY_TIMES;
1220     RemoveEvent(MultiSimController::SET_PRIMARY_SLOT_RETRY_EVENT);
1221 }
1222 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)1223 void MultiSimController::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event)
1224 {
1225     if (event == nullptr) {
1226         TELEPHONY_LOGE("Event is nullptr");
1227         return;
1228     }
1229     auto eventCode = event->GetInnerEventId();
1230     TELEPHONY_LOGI("EventCode is %{public}d", eventCode);
1231     switch (eventCode) {
1232         case MultiSimController::SET_PRIMARY_SLOT_RETRY_EVENT: {
1233             auto primarySlotId = event->GetParam();
1234             std::thread initDataTask([&, primarySlotId = primarySlotId]() {
1235                 pthread_setname_np(pthread_self(), "SetPrimarySlotId");
1236                 CoreManagerInner::GetInstance().SetPrimarySlotId(primarySlotId);
1237             });
1238             initDataTask.detach();
1239             break;
1240         }
1241         case RADIO_SIM_SET_PRIMARY_SLOT:
1242             OnRilSetPrimarySlotDone(event);
1243             break;
1244         case RIL_SET_PRIMARY_SLOT_TIMEOUT_EVENT:
1245             OnRilSetPrimarySlotTimeout(event);
1246             break;
1247         default:
1248             break;
1249     }
1250 }
1251 
PublishSetPrimaryEvent(bool setDone)1252 void MultiSimController::PublishSetPrimaryEvent(bool setDone)
1253 {
1254     AAFwk::Want want;
1255     want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SET_PRIMARY_SLOT_STATUS);
1256     want.SetParam(PARAM_SET_PRIMARY_STATUS, setDone);
1257     EventFwk::CommonEventData data;
1258     data.SetWant(want);
1259 
1260     EventFwk::CommonEventPublishInfo publishInfo;
1261     publishInfo.SetSticky(true);
1262     bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data, publishInfo, nullptr);
1263     TELEPHONY_LOGI("setDone: %{public}d, result: %{public}d", setDone, publishResult);
1264 }
1265 
SendMainCardBroadCast(int32_t slotId)1266 void MultiSimController::SendMainCardBroadCast(int32_t slotId)
1267 {
1268     std::unique_lock<ffrt::mutex> lock(mutex_);
1269     if (localCacheInfo_.empty() || static_cast<uint32_t>(slotId) >= localCacheInfo_.size()) {
1270         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
1271         return;
1272     }
1273     if (localCacheInfo_[slotId].simId == primarySimId_) {
1274         TELEPHONY_LOGE("no need to AnnouncePrimarySimIdChanged");
1275         return;
1276     }
1277     primarySimId_ = localCacheInfo_[slotId].simId;
1278     lock.unlock();
1279     TELEPHONY_LOGI("Announce main simId %{public}d", primarySimId_);
1280     AnnouncePrimarySimIdChanged(primarySimId_);
1281 }
1282 
SendDefaultCellularDataBroadCast(int32_t slotId)1283 void MultiSimController::SendDefaultCellularDataBroadCast(int32_t slotId)
1284 {
1285     if (localCacheInfo_.empty() || static_cast<uint32_t>(slotId) >= localCacheInfo_.size()) {
1286         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
1287         return;
1288     }
1289     if (localCacheInfo_[slotId].simId == defaultCellularSimId_) {
1290         TELEPHONY_LOGE("no need to AnnouncePrimarySimIdChanged");
1291         return;
1292     }
1293     defaultCellularSimId_ = localCacheInfo_[slotId].simId;
1294     TELEPHONY_LOGI("Announce default cellular data simId %{public}d", defaultCellularSimId_);
1295     AnnounceDefaultCellularDataSimIdChanged(defaultCellularSimId_);
1296 }
1297 
EncryptIccId(const std::string iccid)1298 std::string MultiSimController::EncryptIccId(const std::string iccid)
1299 {
1300     unsigned char hash[SHA256_DIGEST_LENGTH];
1301     SHA256_CTX sha256;
1302     SHA256_Init(&sha256);
1303     SHA256_Update(&sha256, iccid.c_str(), iccid.size());
1304     SHA256_Final(hash, &sha256);
1305     std::string encryptIccId = SIMUtils::BytesConvertToHexString(hash, SHA256_DIGEST_LENGTH);
1306     return encryptIccId;
1307 }
1308 
SavePrimarySlotIdInfo(int32_t slotId)1309 void MultiSimController::SavePrimarySlotIdInfo(int32_t slotId)
1310 {
1311     lastPrimarySlotId_ = slotId;
1312     SetParameter(PRIMARY_SLOTID_KEY.c_str(), std::to_string(slotId).c_str());
1313     if (simFileManager_[slotId] == nullptr) {
1314         TELEPHONY_LOGE("simFileManager_ is null slotId is %{public}d", slotId);
1315         return;
1316     }
1317     std::string iccId = Str16ToStr8(simFileManager_[slotId]->GetSimIccId());
1318     TELEPHONY_LOGI("save data is empty %{public}d", iccId.empty());
1319     if (!iccId.empty()) {
1320         std::string encryptIccId = EncryptIccId(iccId);
1321         SetParameter(MAIN_CARD_ICCID_KEY.c_str(), encryptIccId.c_str());
1322     }
1323     SendMainCardBroadCast(slotId);
1324     SetDefaultCellularDataSlotId(slotId);
1325 }
1326 
SaveDefaultCellularDataSlotIdInfo(int32_t slotId)1327 void MultiSimController::SaveDefaultCellularDataSlotIdInfo(int32_t slotId)
1328 {
1329     SetParameter(MAIN_CELLULAR_DATA_SLOTID_KEY.c_str(), std::to_string(slotId).c_str());
1330     lastCellularDataSlotId_ = slotId;
1331     SendDefaultCellularDataBroadCast(slotId);
1332 }
1333 
InitMainCardSlotId()1334 void MultiSimController::InitMainCardSlotId()
1335 {
1336     char lastPrimarySlotId[SYSTEM_PARAMETER_LENGTH] = { 0 };
1337     GetParameter(PRIMARY_SLOTID_KEY.c_str(), PRIMARY_SLOTID.c_str(), lastPrimarySlotId, SYSTEM_PARAMETER_LENGTH);
1338     lastPrimarySlotId_ = std::atoi(lastPrimarySlotId);
1339 
1340     char lastCellularDataSlotId[SYSTEM_PARAMETER_LENGTH] = { 0 };
1341     GetParameter(
1342         MAIN_CELLULAR_DATA_SLOTID_KEY.c_str(), PRIMARY_SLOTID.c_str(), lastCellularDataSlotId, SYSTEM_PARAMETER_LENGTH);
1343     lastCellularDataSlotId_ = std::atoi(lastCellularDataSlotId);
1344 }
1345 
GetShowNumber(int32_t slotId,std::u16string & showNumber)1346 int32_t MultiSimController::GetShowNumber(int32_t slotId, std::u16string &showNumber)
1347 {
1348     if (!IsValidData(slotId)) {
1349         TELEPHONY_LOGE("InValidData");
1350         return TELEPHONY_ERR_NO_SIM_CARD;
1351     }
1352     if (simFileManager_[slotId] == nullptr) {
1353         TELEPHONY_LOGE("can not get simFileManager");
1354         return TELEPHONY_ERR_LOCAL_PTR_NULL;
1355     }
1356     showNumber = simFileManager_[slotId]->GetSimTelephoneNumber();
1357     if (!showNumber.empty()) {
1358         std::unique_lock<ffrt::mutex> lock(mutex_);
1359         if ((static_cast<uint32_t>(slotId) >= localCacheInfo_.size())) {
1360             TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
1361             return TELEPHONY_ERR_NO_SIM_CARD;
1362         }
1363         if (showNumber != Str8ToStr16(localCacheInfo_[slotId].phoneNumber)) {
1364             TelFFRTUtils::Submit([=]() {
1365                 int32_t result = SetShowNumberToDB(slotId, showNumber);
1366                 TELEPHONY_LOGI("slotId: %{public}d get phone "
1367                     "number from sim and save result: %{public}d", slotId, result);
1368             });
1369         }
1370         return TELEPHONY_ERR_SUCCESS;
1371     }
1372     int curSimId;
1373     if (GetTargetSimId(slotId, curSimId) != TELEPHONY_ERR_SUCCESS) {
1374         TELEPHONY_LOGE("failed by out of range");
1375         return TELEPHONY_ERR_ARGUMENT_INVALID;
1376     }
1377     showNumber = Str8ToStr16(localCacheInfo_[slotId].phoneNumber);
1378     if (!showNumber.empty()) {
1379         return TELEPHONY_ERR_SUCCESS;
1380     }
1381     return GetSimTelephoneNumber(slotId, showNumber);
1382 }
1383 
SetShowNumber(int32_t slotId,std::u16string number,bool force)1384 int32_t MultiSimController::SetShowNumber(int32_t slotId, std::u16string number, bool force)
1385 {
1386     TELEPHONY_LOGI("slotId %{public}d", slotId);
1387     if (!force && !IsValidData(slotId)) {
1388         TELEPHONY_LOGE("slotId %{public}d is invalid", slotId);
1389         return TELEPHONY_ERR_NO_SIM_CARD;
1390     }
1391     if (simFileManager_[slotId] == nullptr) {
1392         TELEPHONY_LOGE("can not get simFileManager");
1393         return TELEPHONY_ERR_LOCAL_PTR_NULL;
1394     }
1395     std::u16string alphaTag = simFileManager_[slotId]->GetSimTeleNumberIdentifier();
1396     if (!simFileManager_[slotId]->SetSimTelephoneNumber(alphaTag, number)) {
1397         return TELEPHONY_ERR_FAIL;
1398     }
1399     return SetShowNumberToDB(slotId, number);
1400 }
1401 
SetShowNumberToDB(int32_t slotId,std::u16string number)1402 int32_t MultiSimController::SetShowNumberToDB(int32_t slotId, std::u16string number)
1403 {
1404     if (static_cast<uint32_t>(slotId) >= localCacheInfo_.size()) {
1405         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
1406         return false;
1407     }
1408     int curSimId;
1409     if (GetTargetSimId(slotId, curSimId) != TELEPHONY_ERR_SUCCESS) {
1410         TELEPHONY_LOGE("failed by out of range");
1411         return TELEPHONY_ERR_ARGUMENT_INVALID;
1412     }
1413     if (simDbHelper_ == nullptr) {
1414         TELEPHONY_LOGE("failed by nullptr");
1415         return TELEPHONY_ERR_LOCAL_PTR_NULL;
1416     }
1417     DataShare::DataShareValuesBucket values;
1418     DataShare::DataShareValueObject valueObj(Str16ToStr8(number));
1419     values.Put(SimData::PHONE_NUMBER, valueObj);
1420     int32_t result = simDbHelper_->UpdateDataBySimId(curSimId, values);
1421     if (result == INVALID_VALUE) {
1422         TELEPHONY_LOGE("set Data Base failed");
1423         return TELEPHONY_ERR_DATABASE_WRITE_FAIL;
1424     }
1425     std::unique_lock<ffrt::mutex> lock(mutex_);
1426     if ((static_cast<uint32_t>(slotId) >= localCacheInfo_.size())) {
1427         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
1428         return TELEPHONY_ERR_NO_SIM_CARD;
1429     }
1430     localCacheInfo_[slotId].phoneNumber = Str16ToStr8(number); // save to cache
1431     if (curSimId - 1 >= static_cast<int>(allLocalCacheInfo_.size()) || curSimId - 1 < 0) {
1432         return TELEPHONY_ERR_ARRAY_OUT_OF_BOUNDS;
1433     }
1434     allLocalCacheInfo_[curSimId - 1].phoneNumber = Str16ToStr8(number);
1435     return TELEPHONY_ERR_SUCCESS;
1436 }
1437 
GetShowName(int32_t slotId,std::u16string & showName)1438 int32_t MultiSimController::GetShowName(int32_t slotId, std::u16string &showName)
1439 {
1440     if (!IsValidData(slotId)) {
1441         TELEPHONY_LOGE("InValidData");
1442         return TELEPHONY_ERR_NO_SIM_CARD;
1443     }
1444     std::unique_lock<ffrt::mutex> lock(mutex_);
1445     if (static_cast<uint32_t>(slotId) >= localCacheInfo_.size()) {
1446         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
1447         return TELEPHONY_ERR_ARGUMENT_INVALID;
1448     }
1449     showName = Str8ToStr16(localCacheInfo_[slotId].showName);
1450     lock.unlock();
1451     TELEPHONY_LOGD("Get the SIM name set by the user");
1452     return TELEPHONY_ERR_SUCCESS;
1453 }
1454 
SetShowName(int32_t slotId,std::u16string name,bool force)1455 int32_t MultiSimController::SetShowName(int32_t slotId, std::u16string name, bool force)
1456 {
1457     if (!force && !IsValidData(slotId)) {
1458         TELEPHONY_LOGE("slotId %{public}d is invalid", slotId);
1459         return TELEPHONY_ERR_NO_SIM_CARD;
1460     }
1461     int curSimId;
1462     if (GetTargetSimId(slotId, curSimId) != TELEPHONY_ERR_SUCCESS) {
1463         TELEPHONY_LOGE("failed by out of range");
1464         return TELEPHONY_ERR_ARGUMENT_INVALID;
1465     }
1466     if (simDbHelper_ == nullptr) {
1467         TELEPHONY_LOGE("get Data Base failed");
1468         return TELEPHONY_ERR_LOCAL_PTR_NULL;
1469     }
1470     DataShare::DataShareValuesBucket values;
1471     DataShare::DataShareValueObject valueObj(Str16ToStr8(name));
1472     values.Put(SimData::SHOW_NAME, valueObj);
1473     int32_t result = simDbHelper_->UpdateDataBySimId(curSimId, values);
1474     if (result == INVALID_VALUE) {
1475         TELEPHONY_LOGE("set Data Base failed");
1476         return TELEPHONY_ERR_DATABASE_WRITE_FAIL;
1477     }
1478     std::unique_lock<ffrt::mutex> lock(mutex_);
1479     if ((static_cast<uint32_t>(slotId) >= localCacheInfo_.size())) {
1480         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
1481         return TELEPHONY_ERR_ARGUMENT_INVALID;
1482     }
1483     localCacheInfo_[slotId].showName = Str16ToStr8(name); // save to cache
1484     if (curSimId - 1 >= static_cast<int>(allLocalCacheInfo_.size()) || curSimId - 1 < 0) {
1485         return TELEPHONY_ERR_ARRAY_OUT_OF_BOUNDS;
1486     }
1487     allLocalCacheInfo_[curSimId - 1].showName = Str16ToStr8(name);
1488     return TELEPHONY_ERR_SUCCESS;
1489 }
1490 
GetSimTelephoneNumber(int32_t slotId,std::u16string & telephoneNumber)1491 int32_t MultiSimController::GetSimTelephoneNumber(int32_t slotId, std::u16string &telephoneNumber)
1492 {
1493     if (!IsValidData(slotId)) {
1494         TELEPHONY_LOGE("slotId %{public}d is invalid", slotId);
1495         return TELEPHONY_ERR_NO_SIM_CARD;
1496     }
1497     std::shared_ptr<ImsCoreServiceClient> imsCoreServiceClient = DelayedSingleton<ImsCoreServiceClient>::GetInstance();
1498     if (imsCoreServiceClient == nullptr) {
1499         TELEPHONY_LOGE("can not get imsCoreServiceClient");
1500         return TELEPHONY_ERR_LOCAL_PTR_NULL;
1501     }
1502     std::string result = "";
1503     imsCoreServiceClient->GetPhoneNumberFromIMPU(slotId, result);
1504     telephoneNumber = Str8ToStr16(result);
1505     TELEPHONY_LOGI("impu result is empty:%{public}s, slot%{public}d", (telephoneNumber.empty() ? "true" : "false"),
1506         slotId);
1507     std::unique_lock<ffrt::mutex> lock(mutex_);
1508     if ((static_cast<uint32_t>(slotId) >= localCacheInfo_.size())) {
1509         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
1510         return TELEPHONY_ERR_NO_SIM_CARD;
1511     }
1512     if (!telephoneNumber.empty() && telephoneNumber != Str8ToStr16(localCacheInfo_[slotId].phoneNumber)) {
1513         TelFFRTUtils::Submit([=]() {
1514             int32_t ret = SetShowNumberToDB(slotId, telephoneNumber);
1515             TELEPHONY_LOGI("slotId %{public}d save impu phone number result: %{public}d", slotId, ret);
1516         });
1517     }
1518     return TELEPHONY_ERR_SUCCESS;
1519 }
1520 
GetTargetIccId(int32_t slotId,std::string & iccId)1521 int32_t MultiSimController::GetTargetIccId(int32_t slotId, std::string &iccId)
1522 {
1523     std::unique_lock<ffrt::mutex> lock(mutex_);
1524     iccId = "";
1525     if (static_cast<uint32_t>(slotId) >= localCacheInfo_.size()) {
1526         TELEPHONY_LOGE("Out of range, slotId %{public}d", slotId);
1527         return TELEPHONY_ERROR;
1528     }
1529     iccId = localCacheInfo_[slotId].iccId;
1530     return TELEPHONY_ERR_SUCCESS;
1531 }
1532 
AnnounceDefaultVoiceSimIdChanged(int32_t simId)1533 bool MultiSimController::AnnounceDefaultVoiceSimIdChanged(int32_t simId)
1534 {
1535     AAFwk::Want want;
1536     want.SetParam(PARAM_SIMID, simId);
1537     want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SIM_CARD_DEFAULT_VOICE_SUBSCRIPTION_CHANGED);
1538     int32_t eventCode = EVENT_CODE;
1539     std::string eventData(DEFAULT_VOICE_SIMID_CHANGED);
1540     return PublishSimFileEvent(want, eventCode, eventData);
1541 }
1542 
AnnounceDefaultSmsSimIdChanged(int32_t simId)1543 bool MultiSimController::AnnounceDefaultSmsSimIdChanged(int32_t simId)
1544 {
1545     AAFwk::Want want;
1546     want.SetParam(PARAM_SIMID, simId);
1547     want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SIM_CARD_DEFAULT_SMS_SUBSCRIPTION_CHANGED);
1548     int32_t eventCode = EVENT_CODE;
1549     std::string eventData(DEFAULT_SMS_SIMID_CHANGED);
1550     return PublishSimFileEvent(want, eventCode, eventData);
1551 }
1552 
AnnounceDefaultCellularDataSimIdChanged(int32_t simId)1553 bool MultiSimController::AnnounceDefaultCellularDataSimIdChanged(int32_t simId)
1554 {
1555     AAFwk::Want want;
1556     want.SetParam(PARAM_SIMID, simId);
1557     want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SIM_CARD_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
1558     int32_t eventCode = EVENT_CODE;
1559     std::string eventData(DEFAULT_CELLULAR_DATA_SIMID_CHANGED);
1560     return PublishSimFileEvent(want, eventCode, eventData);
1561 }
1562 
AnnouncePrimarySimIdChanged(int32_t simId)1563 bool MultiSimController::AnnouncePrimarySimIdChanged(int32_t simId)
1564 {
1565     AAFwk::Want want;
1566     want.SetParam(PARAM_SIMID, simId);
1567     want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SIM_CARD_DEFAULT_MAIN_SUBSCRIPTION_CHANGED);
1568     int32_t eventCode = EVENT_CODE;
1569     std::string eventData(DEFAULT_MAIN_SIMID_CHANGED);
1570     return PublishSimFileEvent(want, eventCode, eventData);
1571 }
1572 
PublishSimFileEvent(const AAFwk::Want & want,int eventCode,const std::string & eventData)1573 bool MultiSimController::PublishSimFileEvent(const AAFwk::Want &want, int eventCode, const std::string &eventData)
1574 {
1575     EventFwk::CommonEventData data;
1576     data.SetWant(want);
1577     data.SetCode(eventCode);
1578     data.SetData(eventData);
1579     EventFwk::CommonEventPublishInfo publishInfo;
1580     publishInfo.SetOrdered(false);
1581     bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data, publishInfo, nullptr);
1582     TELEPHONY_LOGD("end###publishResult = %{public}d", publishResult);
1583     return publishResult;
1584 }
1585 
SaveImsSwitch(int32_t slotId,int32_t imsSwitchValue)1586 int32_t MultiSimController::SaveImsSwitch(int32_t slotId, int32_t imsSwitchValue)
1587 {
1588     std::string curIccid = "";
1589     if (GetTargetIccId(slotId, curIccid) != TELEPHONY_SUCCESS || simDbHelper_ == nullptr) {
1590         TELEPHONY_LOGE("failed by out of range or simDbHelper is nullptr");
1591         imsSwitchValue = IMS_SWITCH_VALUE_UNKNOWN;
1592         return TELEPHONY_ERROR;
1593     }
1594     DataShare::DataShareValuesBucket values;
1595     DataShare::DataShareValueObject valueObj(imsSwitchValue);
1596     values.Put(SimData::IMS_SWITCH, valueObj);
1597     return simDbHelper_->UpdateDataByIccId(curIccid, values);
1598 }
1599 
QueryImsSwitch(int32_t slotId,int32_t & imsSwitchValue)1600 int32_t MultiSimController::QueryImsSwitch(int32_t slotId, int32_t &imsSwitchValue)
1601 {
1602     std::string curIccid = "";
1603     if (GetTargetIccId(slotId, curIccid) != TELEPHONY_SUCCESS || simDbHelper_ == nullptr) {
1604         TELEPHONY_LOGE("failed by out of range or simDbHelper is nullptr");
1605         imsSwitchValue = IMS_SWITCH_VALUE_UNKNOWN;
1606         return TELEPHONY_ERROR;
1607     }
1608     SimRdbInfo simRdbInfo;
1609     simRdbInfo.imsSwitch = IMS_SWITCH_STATUS_UNKNOWN;
1610     simDbHelper_->QueryDataByIccId(curIccid, simRdbInfo);
1611     imsSwitchValue = simRdbInfo.imsSwitch;
1612     return TELEPHONY_SUCCESS;
1613 }
1614 
GetActiveSimAccountInfoList(bool denied,std::vector<IccAccountInfo> & iccAccountInfoList)1615 int32_t MultiSimController::GetActiveSimAccountInfoList(bool denied, std::vector<IccAccountInfo> &iccAccountInfoList)
1616 {
1617     if (!UpdateIccAccountInfoList(activeIccAccountInfoList_, localCacheInfo_, true)) {
1618         TELEPHONY_LOGW("refresh failed");
1619         return TELEPHONY_ERR_NO_SIM_CARD;
1620     }
1621     iccAccountInfoList.clear();
1622     std::unique_lock<ffrt::mutex> lock(mutex_);
1623     std::vector<IccAccountInfo>::iterator it = activeIccAccountInfoList_.begin();
1624     while (it != activeIccAccountInfoList_.end()) {
1625         if (denied) {
1626             it->iccId = u"";
1627             it->showNumber = u"";
1628         }
1629         iccAccountInfoList.emplace_back(*it);
1630         ++it;
1631     }
1632     return iccAccountInfoList.size() > 0 ? TELEPHONY_ERR_SUCCESS : TELEPHONY_ERR_NO_SIM_CARD;
1633 }
1634 
GetAllSimAccountInfoList(bool denied,std::vector<IccAccountInfo> & iccAccountInfoList)1635 int32_t MultiSimController::GetAllSimAccountInfoList(bool denied, std::vector<IccAccountInfo> &iccAccountInfoList)
1636 {
1637     if (!UpdateIccAccountInfoList(allIccAccountInfoList_, allLocalCacheInfo_, false)) {
1638         TELEPHONY_LOGE("refresh failed");
1639         return TELEPHONY_ERR_NO_SIM_CARD;
1640     }
1641     iccAccountInfoList.clear();
1642     std::unique_lock<ffrt::mutex> lock(mutex_);
1643     std::vector<IccAccountInfo>::iterator it = allIccAccountInfoList_.begin();
1644     while (it != allIccAccountInfoList_.end()) {
1645         if (denied) {
1646             it->iccId = u"";
1647             it->showNumber = u"";
1648         }
1649         iccAccountInfoList.emplace_back(*it);
1650         ++it;
1651     }
1652     return iccAccountInfoList.size() > 0 ? TELEPHONY_ERR_SUCCESS : TELEPHONY_ERR_NO_SIM_CARD;
1653 }
1654 
GetRadioProtocolTech(int32_t slotId)1655 int32_t MultiSimController::GetRadioProtocolTech(int32_t slotId)
1656 {
1657     if (radioProtocolController_ == nullptr) {
1658         TELEPHONY_LOGE("radioProtocolController_ is nullptr");
1659         return static_cast<int32_t>(RadioProtocolTech::RADIO_PROTOCOL_TECH_UNKNOWN);
1660     }
1661     return radioProtocolController_->GetRadioProtocolTech(slotId);
1662 }
1663 
GetRadioProtocol(int32_t slotId)1664 void MultiSimController::GetRadioProtocol(int32_t slotId)
1665 {
1666     if (radioProtocolController_ == nullptr) {
1667         TELEPHONY_LOGE("radioProtocolController_ is nullptr");
1668         return;
1669     }
1670     radioProtocolController_->GetRadioProtocol(slotId);
1671 }
IsSatelliteSupported()1672 int32_t MultiSimController::IsSatelliteSupported()
1673 {
1674     char satelliteSupported[SYSPARA_SIZE] = { 0 };
1675     GetParameter(TEL_SATELLITE_SUPPORTED, SATELLITE_DEFAULT_VALUE, satelliteSupported, SYSPARA_SIZE);
1676     TELEPHONY_LOGI("satelliteSupported is %{public}s", satelliteSupported);
1677     return std::atoi(satelliteSupported);
1678 }
1679 
IsSetActiveSimInProgress(int32_t slotId)1680 bool MultiSimController::IsSetActiveSimInProgress(int32_t slotId)
1681 {
1682     if (static_cast<uint32_t>(slotId) >= isSetActiveSimInProgress_.size()) {
1683         TELEPHONY_LOGE("invalid slotId %{public}d", slotId);
1684         return false;
1685     }
1686     TELEPHONY_LOGD("isSetActiveSimInProgress_ %{public}d, is %{public}d", slotId, isSetActiveSimInProgress_[slotId]);
1687     return static_cast<bool>(isSetActiveSimInProgress_[slotId]);
1688 }
1689 
SavePrimarySlotId(int32_t slotId)1690 int32_t MultiSimController::SavePrimarySlotId(int32_t slotId)
1691 {
1692     if (!IsValidSlotId(slotId)) {
1693         TELEPHONY_LOGE("SavePrimarySlotId invalid slotId %{public}d", slotId);
1694         return TELEPHONY_ERR_ARGUMENT_INVALID;
1695     }
1696 
1697     TELEPHONY_LOGI("slotId %{public}d", slotId);
1698     SavePrimarySlotIdInfo(slotId);
1699     return TELEPHONY_ERR_SUCCESS;
1700 }
1701 
SetPrimarySlotIdWithoutModemReboot(int32_t slotId)1702 int32_t MultiSimController::SetPrimarySlotIdWithoutModemReboot(int32_t slotId)
1703 {
1704     TELEPHONY_LOGD("slotId = %{public}d", slotId);
1705     if (TELEPHONY_EXT_WRAPPER.isHandleVSim_ && TELEPHONY_EXT_WRAPPER.isHandleVSim_()) {
1706         TELEPHONY_LOGE("in vsim handle, not allowed switch card");
1707         return TELEPHONY_ERR_FAIL;
1708     }
1709     if (!IsValidData(slotId)) {
1710         TELEPHONY_LOGE("no sim card");
1711         return TELEPHONY_ERR_NO_SIM_CARD;
1712     }
1713     isSetPrimarySlotIdInProgress_ = true;
1714     PublishSetPrimaryEvent(false);
1715     if (!SetPrimarySlotToRil(slotId)) {
1716         TELEPHONY_LOGE("SetPrimarySlotToRil failed");
1717         SetPrimarySlotIdDone();
1718         return TELEPHONY_ERR_LOCAL_PTR_NULL;
1719     }
1720     SavePrimarySlotIdInfo(slotId);
1721     SetPrimarySlotIdDone();
1722     RemoveEvent(RIL_SET_PRIMARY_SLOT_TIMEOUT_EVENT);
1723     TELEPHONY_LOGD("SetPrimarySlotIdWithoutModemReboot finish");
1724     return TELEPHONY_ERR_SUCCESS;
1725 }
1726 
SetPrimarySlotToRil(int32_t slotId)1727 bool MultiSimController::SetPrimarySlotToRil(int32_t slotId)
1728 {
1729     if (isSettingPrimarySlotToRil_) {
1730         TELEPHONY_LOGE("SetPrimarySlotToRil is settting, can not set now");
1731         return false;
1732     }
1733     std::unique_lock<ffrt::mutex> setPrimarySlotLock(setPrimarySlotToRilMutex_);
1734     isSettingPrimarySlotToRil_ = true;
1735     setPrimarySlotResponseResult_ = false;
1736     SendSetPrimarySlotEvent(slotId);
1737     while (isSettingPrimarySlotToRil_) {
1738         TELEPHONY_LOGI("SetPrimarySlotToRil wait for the setPrimarySlot to finish");
1739         setPrimarySlotToRilCv_.wait(setPrimarySlotLock);
1740     }
1741     TELEPHONY_LOGI("SetPrimarySlotToRil finish");
1742     return setPrimarySlotResponseResult_;
1743 }
1744 
SendSetPrimarySlotEvent(int32_t slotId)1745 void MultiSimController::SendSetPrimarySlotEvent(int32_t slotId)
1746 {
1747     auto telRilManager = telRilManager_.lock();
1748     if (telRilManager == nullptr) {
1749         TELEPHONY_LOGE("SendSetPrimarySlotEvent telRilManager is nullptr");
1750         ProcessRilSetPrimarySlotResponse(false);
1751         return;
1752     }
1753     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::Get(RADIO_SIM_SET_PRIMARY_SLOT);
1754     if (event == nullptr) {
1755         TELEPHONY_LOGE("SetPrimarySlot event is nullptr");
1756         ProcessRilSetPrimarySlotResponse(false);
1757         return;
1758     }
1759     event->SetOwner(shared_from_this());
1760     telRilManager->SetPrimarySlot(slotId, event);
1761     SendEvent(RIL_SET_PRIMARY_SLOT_TIMEOUT_EVENT, slotId, RIL_SET_PRIMARY_SLOT_TIMEOUT);
1762 }
1763 
OnRilSetPrimarySlotDone(const AppExecFwk::InnerEvent::Pointer & event)1764 void MultiSimController::OnRilSetPrimarySlotDone(const AppExecFwk::InnerEvent::Pointer &event)
1765 {
1766     if (event == nullptr) {
1767         TELEPHONY_LOGE("event is nullptr");
1768         return;
1769     }
1770     std::shared_ptr<RadioResponseInfo> responseInfo = event->GetSharedObject<RadioResponseInfo>();
1771     if (responseInfo == nullptr) {
1772         TELEPHONY_LOGE("responseInfo is nullptr");
1773         return;
1774     }
1775     ProcessRilSetPrimarySlotResponse(responseInfo->error == ErrType::NONE);
1776 }
1777 
OnRilSetPrimarySlotTimeout(const AppExecFwk::InnerEvent::Pointer & event)1778 void MultiSimController::OnRilSetPrimarySlotTimeout(const AppExecFwk::InnerEvent::Pointer &event)
1779 {
1780     if (event == nullptr) {
1781         TELEPHONY_LOGE("event is nullptr");
1782         return;
1783     }
1784     int32_t primarySlotId = event->GetParam();
1785     TELEPHONY_LOGI("setPrimarySlotToRilTimeout slotId is %{public}d", primarySlotId);
1786     ProcessRilSetPrimarySlotResponse(false);
1787 }
1788 
ProcessRilSetPrimarySlotResponse(bool result)1789 void MultiSimController::ProcessRilSetPrimarySlotResponse(bool result)
1790 {
1791     isSettingPrimarySlotToRil_ = false;
1792     setPrimarySlotResponseResult_ = result;
1793     setPrimarySlotToRilCv_.notify_all();
1794 }
1795 
IsEsim(int32_t slotId)1796 bool MultiSimController::IsEsim(int32_t slotId)
1797 {
1798 #ifdef CORE_SERVICE_SUPPORT_ESIM
1799     if ((radioProtocolController_ == nullptr) ||
1800         (slotId < DEFAULT_SIM_SLOT_ID) || (static_cast<uint32_t>(slotId) >= simStateManager_.size())) {
1801             TELEPHONY_LOGE("slotId[%{public}d] invalid or radioProtocolController_ is null", slotId);
1802             return false;
1803     }
1804     int32_t modemId = radioProtocolController_->GetRadioProtocolModemId(slotId);
1805     std::string propAtr = "";
1806     propAtr = (modemId == MODEM_ID_0) ? GSM_SIM_ATR : propAtr;
1807     propAtr = (modemId == MODEM_ID_1) ? GSM_SIM_ATR1 : propAtr;
1808     if (propAtr.empty()) {
1809         TELEPHONY_LOGE("modemId invalid, can't get atr prop.");
1810         return false;
1811     }
1812 
1813     char buf[CARD_ATR_LEN + 1] = {0};
1814     GetParameter(propAtr.c_str(), "", buf, CARD_ATR_LEN);
1815     std::string cardAtr(buf);
1816     if (cardAtr.empty()) {
1817         TELEPHONY_LOGE("card atr is empty.");
1818         return false;
1819     }
1820 
1821     ResetResponse resetResponse;
1822     resetResponse.AnalysisAtrData(cardAtr);
1823     TELEPHONY_LOGI("slot%{public}d isEsim: %{public}s", slotId, resetResponse.IsEuiccAvailable() ? "true" : "false");
1824     return resetResponse.IsEuiccAvailable();
1825 #else
1826     return false;
1827 #endif
1828 }
1829 
1830 } // namespace Telephony
1831 } // namespace OHOS
1832