1 /*
2  * Copyright (C) 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 "esim_file.h"
17 
18 #include <unistd.h>
19 
20 #include "common_event_manager.h"
21 #include "common_event_support.h"
22 #include "core_manager_inner.h"
23 #include "core_service.h"
24 #include "parameters.h"
25 #include "radio_event.h"
26 #include "sim_number_decode.h"
27 #include "str_convert.h"
28 #include "telephony_common_utils.h"
29 #include "telephony_ext_wrapper.h"
30 #include "telephony_state_registry_client.h"
31 #include "telephony_tag_def.h"
32 #include "vcard_utils.h"
33 using namespace OHOS::AppExecFwk;
34 using namespace OHOS::EventFwk;
35 
36 namespace OHOS {
37 namespace Telephony {
EsimFile(std::shared_ptr<SimStateManager> simStateManager)38 EsimFile::EsimFile(std::shared_ptr<SimStateManager> simStateManager) : IccFile("EsimFile", simStateManager)
39 {
40     currentChannelId_ = 0;
41     InitMemberFunc();
42     InitChanneMemberFunc();
43 }
44 
StartLoad()45 void EsimFile::StartLoad() {}
46 
SyncOpenChannel()47 void EsimFile::SyncOpenChannel()
48 {
49     uint32_t tryCnt = 0;
50     std::u16string aid = OHOS::Telephony::ToUtf16(ISDR_AID);
51     if (esimProfile_.aid != aid) {
52         SyncCloseChannel();
53         esimProfile_.aid = aid;
54     }
55     while (!IsLogicChannelOpen()) {
56         ProcessEsimOpenChannel(OHOS::Telephony::ToUtf16(ISDR_AID));
57         std::unique_lock<std::mutex> lck(openChannelMutex_);
58         if (openChannelCv_.wait_for(lck, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
59             [this]() { return IsLogicChannelOpen(); })) {
60             break;
61         }
62         tryCnt++;
63         if (tryCnt >= NUMBER_THREE) {
64             TELEPHONY_LOGE("failed to open the channel");
65             break;
66         }
67     }
68 }
69 
SyncOpenChannel(const std::u16string &aid)70 void EsimFile::SyncOpenChannel(const std::u16string &aid)
71 {
72     uint32_t tryCnt = 0;
73     while (!IsLogicChannelOpen()) {
74         ProcessEsimOpenChannel(aid);
75         std::unique_lock<std::mutex> lck(openChannelMutex_);
76         if (openChannelCv_.wait_for(lck, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
77             [this]() { return IsLogicChannelOpen(); })) {
78             break;
79         }
80         tryCnt++;
81         if (tryCnt >= NUMBER_THREE) {
82             TELEPHONY_LOGE("failed to open the channel");
83             break;
84         }
85     }
86 }
87 
SyncCloseChannel()88 void EsimFile::SyncCloseChannel()
89 {
90     uint32_t tryCnt = 0;
91     while (IsLogicChannelOpen()) {
92         ProcessEsimCloseChannel();
93         std::unique_lock<std::mutex> lck(closeChannelMutex_);
94         if (closeChannelCv_.wait_for(lck, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
95             [this]() { return !IsLogicChannelOpen(); })) {
96             break;
97         }
98         tryCnt++;
99         if (tryCnt >= NUMBER_THREE) {
100             currentChannelId_ = 0;
101             TELEPHONY_LOGE("failed to close the channel");
102             break;
103         }
104     }
105 }
106 
ObtainEid()107 std::string EsimFile::ObtainEid()
108 {
109     SyncOpenChannel();
110     AppExecFwk::InnerEvent::Pointer eventGetEid = BuildCallerInfo(MSG_ESIM_OBTAIN_EID_DONE);
111     if (!ProcessObtainEid(slotId_, eventGetEid)) {
112         TELEPHONY_LOGE("ProcessObtainEid encode failed");
113         return "";
114     }
115     // wait profileInfo is ready
116     isEidReady_ = false;
117     std::unique_lock<std::mutex> lock(getEidMutex_);
118     if (!getEidCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
119         [this]() { return isEidReady_; })) {
120         SyncCloseChannel();
121         return "";
122     }
123     SyncCloseChannel();
124     return eid_;
125 }
126 
GetEuiccProfileInfoList()127 GetEuiccProfileInfoListResult EsimFile::GetEuiccProfileInfoList()
128 {
129     SyncOpenChannel();
130     AppExecFwk::InnerEvent::Pointer eventRequestAllProfiles = BuildCallerInfo(MSG_ESIM_REQUEST_ALL_PROFILES);
131     if (!ProcessRequestAllProfiles(slotId_, eventRequestAllProfiles)) {
132         TELEPHONY_LOGE("ProcessRequestAllProfiles encode failed");
133         return GetEuiccProfileInfoListResult();
134     }
135     isAllProfileInfoReady_ = false;
136     std::unique_lock<std::mutex> lock(allProfileInfoMutex_);
137     if (!allProfileInfoCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
138         [this]() { return isAllProfileInfoReady_; })) {
139         SyncCloseChannel();
140         return GetEuiccProfileInfoListResult();
141     }
142     SyncCloseChannel();
143     return euiccProfileInfoList_;
144 }
145 
GetEuiccInfo()146 EuiccInfo EsimFile::GetEuiccInfo()
147 {
148     SyncOpenChannel();
149     AppExecFwk::InnerEvent::Pointer eventEUICCInfo1 = BuildCallerInfo(MSG_ESIM_OBTAIN_EUICC_INFO_1_DONE);
150     if (!ProcessObtainEuiccInfo1(slotId_, eventEUICCInfo1)) {
151         TELEPHONY_LOGE("ProcessObtainEuiccInfo1 encode failed");
152         return EuiccInfo();
153     }
154     isEuiccInfo1Ready_ = false;
155     std::unique_lock<std::mutex> lock(euiccInfo1Mutex_);
156     if (!euiccInfo1Cv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
157         [this]() { return isEuiccInfo1Ready_; })) {
158         SyncCloseChannel();
159         return EuiccInfo();
160     }
161     SyncCloseChannel();
162     return eUiccInfo_;
163 }
164 
CopyApdCmdToReqInfo(ApduSimIORequestInfo *requestInfo, ApduCommand *apduCommand)165 void EsimFile::CopyApdCmdToReqInfo(ApduSimIORequestInfo *requestInfo, ApduCommand *apduCommand)
166 {
167     if (apduCommand == nullptr || requestInfo == nullptr) {
168         TELEPHONY_LOGE("CopyApdCmdToReqInfo failed");
169         return;
170     }
171     requestInfo->serial = nextSerialId_;
172     nextSerialId_++;
173     if (nextSerialId_ >= INT32_MAX) {
174         nextSerialId_ = 0;
175     }
176     requestInfo->channelId = apduCommand->channel;
177     requestInfo->type = apduCommand->data.cla;
178     requestInfo->instruction = apduCommand->data.ins;
179     requestInfo->p1 = apduCommand->data.p1;
180     requestInfo->p2 = apduCommand->data.p2;
181     requestInfo->p3 = apduCommand->data.p3;
182     requestInfo->data = apduCommand->data.cmdHex;
183 }
184 
CommBuildOneApduReqInfo(ApduSimIORequestInfo &requestInfo, std::shared_ptr<Asn1Builder> &builder)185 void EsimFile::CommBuildOneApduReqInfo(ApduSimIORequestInfo &requestInfo, std::shared_ptr<Asn1Builder> &builder)
186 {
187     if (builder == nullptr) {
188         TELEPHONY_LOGE("builder is nullptr");
189         return;
190     }
191     std::string hexStr;
192     uint32_t hexStrLen = builder->Asn1BuilderToHexStr(hexStr);
193     if (hexStrLen == 0) {
194         TELEPHONY_LOGE("hexStrLen is zero");
195         return;
196     }
197     RequestApduBuild codec(currentChannelId_);
198     codec.BuildStoreData(hexStr);
199     std::list<std::unique_ptr<ApduCommand>> list = codec.GetCommands();
200     if (list.empty()) {
201         TELEPHONY_LOGE("node is empty");
202         return;
203     }
204     std::unique_ptr<ApduCommand> apduCommand = std::move(list.front());
205     CopyApdCmdToReqInfo(&requestInfo, apduCommand.get());
206 }
207 
ProcessObtainEid(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)208 bool EsimFile::ProcessObtainEid(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
209 {
210     if (!IsLogicChannelOpen()) {
211         return false;
212     }
213     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_GET_EID);
214     if (builder == nullptr) {
215         TELEPHONY_LOGE("builder is nullptr");
216         return false;
217     }
218     std::vector<uint8_t> eidTags;
219     eidTags.push_back(static_cast<unsigned char>(TAG_ESIM_EID));
220     builder->Asn1AddChildAsBytes(TAG_ESIM_TAG_LIST, eidTags, eidTags.size());
221     ApduSimIORequestInfo requestInfo;
222     CommBuildOneApduReqInfo(requestInfo, builder);
223     if (telRilManager_ == nullptr) {
224         return false;
225     }
226     telRilManager_->SimTransmitApduLogicalChannel(slotId, requestInfo, responseEvent);
227     return true;
228 }
229 
ProcessObtainEuiccInfo1(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)230 bool EsimFile::ProcessObtainEuiccInfo1(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
231 {
232     if (!IsLogicChannelOpen()) {
233         return false;
234     }
235     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_GET_EUICC_INFO_1);
236     ApduSimIORequestInfo requestInfo;
237     CommBuildOneApduReqInfo(requestInfo, builder);
238     if (telRilManager_ == nullptr) {
239         return false;
240     }
241     telRilManager_->SimTransmitApduLogicalChannel(slotId, requestInfo, responseEvent);
242     return true;
243 }
244 
ProcessRequestAllProfiles(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)245 bool EsimFile::ProcessRequestAllProfiles(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
246 {
247     if (!IsLogicChannelOpen()) {
248         return false;
249     }
250     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_GET_PROFILES);
251     if (builder == nullptr) {
252         TELEPHONY_LOGE("builder is nullptr");
253         return false;
254     }
255     unsigned char EUICC_PROFILE_TAGS[] = {
256         static_cast<unsigned char>(TAG_ESIM_ICCID),
257         static_cast<unsigned char>(TAG_ESIM_NICKNAME),
258         static_cast<unsigned char>(TAG_ESIM_OBTAIN_OPERATOR_NAME),
259         static_cast<unsigned char>(TAG_ESIM_PROFILE_NAME),
260         static_cast<unsigned char>(TAG_ESIM_OPERATOR_ID),
261         static_cast<unsigned char>(TAG_ESIM_PROFILE_STATE / PROFILE_DEFAULT_NUMBER),
262         static_cast<unsigned char>(TAG_ESIM_PROFILE_STATE % PROFILE_DEFAULT_NUMBER),
263         static_cast<unsigned char>(TAG_ESIM_PROFILE_CLASS),
264         static_cast<unsigned char>(TAG_ESIM_PROFILE_POLICY_RULE),
265         static_cast<unsigned char>(TAG_ESIM_CARRIER_PRIVILEGE_RULES / PROFILE_DEFAULT_NUMBER),
266         static_cast<unsigned char>(TAG_ESIM_CARRIER_PRIVILEGE_RULES % PROFILE_DEFAULT_NUMBER),
267     };
268     std::vector<uint8_t> euiccProfileTags;
269     for (const unsigned char tag : EUICC_PROFILE_TAGS) {
270         euiccProfileTags.push_back(tag);
271     }
272     builder->Asn1AddChildAsBytes(TAG_ESIM_TAG_LIST, euiccProfileTags, euiccProfileTags.size());
273     ApduSimIORequestInfo requestInfo;
274     CommBuildOneApduReqInfo(requestInfo, builder);
275     if (telRilManager_ == nullptr) {
276         return false;
277     }
278     telRilManager_->SimTransmitApduLogicalChannel(slotId, requestInfo, responseEvent);
279     return true;
280 }
281 
IsLogicChannelOpen()282 bool EsimFile::IsLogicChannelOpen()
283 {
284     if (currentChannelId_ > 0) {
285         return true;
286     }
287     return false;
288 }
289 
ProcessEsimOpenChannel(const std::u16string &aid)290 void EsimFile::ProcessEsimOpenChannel(const std::u16string &aid)
291 {
292     std::string appId = OHOS::Telephony::ToUtf8(aid);
293     AppExecFwk::InnerEvent::Pointer response = BuildCallerInfo(MSG_ESIM_OPEN_CHANNEL_DONE);
294     if (telRilManager_ == nullptr) {
295         return;
296     }
297     telRilManager_->SimOpenLogicalChannel(slotId_, appId, PARAMETER_TWO, response);
298     return;
299 }
300 
ProcessEsimOpenChannelDone(const AppExecFwk::InnerEvent::Pointer &event)301 bool EsimFile::ProcessEsimOpenChannelDone(const AppExecFwk::InnerEvent::Pointer &event)
302 {
303     if (event == nullptr) {
304         TELEPHONY_LOGE("open logical channel event is nullptr!");
305         return false;
306     }
307     auto resultPtr = event->GetSharedObject<OpenLogicalChannelResponse>();
308     if (resultPtr == nullptr) {
309         TELEPHONY_LOGE("open logical channel fd is nullptr!");
310         return false;
311     }
312     if (resultPtr->channelId > 0) {
313         currentChannelId_ = resultPtr->channelId;
314         openChannelCv_.notify_one();
315     } else {
316         return false;
317     }
318     return true;
319 }
320 
ProcessEsimCloseChannel()321 void EsimFile::ProcessEsimCloseChannel()
322 {
323     AppExecFwk::InnerEvent::Pointer response = BuildCallerInfo(MSG_ESIM_CLOSE_CHANNEL_DONE);
324     if (telRilManager_ == nullptr) {
325         return;
326     }
327     telRilManager_->SimCloseLogicalChannel(slotId_, currentChannelId_, response);
328     return;
329 }
330 
ProcessEsimCloseChannelDone(const AppExecFwk::InnerEvent::Pointer &event)331 bool EsimFile::ProcessEsimCloseChannelDone(const AppExecFwk::InnerEvent::Pointer &event)
332 {
333     {
334         std::lock_guard<std::mutex> lock(closeChannelMutex_);
335         currentChannelId_ = 0;
336         TELEPHONY_LOGI("Logical channel closed successfully. Notifying waiting thread.");
337     }
338     closeChannelCv_.notify_one();
339     return true;
340 }
341 
MakeVersionString(std::vector<uint8_t> &versionRaw)342 std::string EsimFile::MakeVersionString(std::vector<uint8_t> &versionRaw)
343 {
344     if (versionRaw.size() < NUMBER_THREE) {
345         TELEPHONY_LOGE("versionRaw.size(%{public}zu) error!", versionRaw.size());
346         return "";
347     }
348     std::ostringstream oss;
349     oss << std::hex << std::uppercase << (versionRaw[VERSION_HIGH] & MAX_UINT8) << "." <<
350         (versionRaw[VERSION_MIDDLE] & MAX_UINT8) << "." <<
351         (versionRaw[VERSION_LOW] & MAX_UINT8);
352     return oss.str();
353 }
354 
ProcessObtainEidDone(const AppExecFwk::InnerEvent::Pointer &event)355 bool EsimFile::ProcessObtainEidDone(const AppExecFwk::InnerEvent::Pointer &event)
356 {
357     std::shared_ptr<Asn1Node> root = ParseEvent(event);
358     if (root == nullptr) {
359         TELEPHONY_LOGE("Asn1ParseResponse failed");
360         return false;
361     }
362     std::shared_ptr<Asn1Node> profileRoot = root->Asn1GetChild(TAG_ESIM_EID);
363     if (profileRoot == nullptr) {
364         return false;
365     }
366     std::vector<uint8_t> outPutBytes;
367     uint32_t byteLen = profileRoot->Asn1AsBytes(outPutBytes);
368     if (byteLen == 0) {
369         TELEPHONY_LOGE("byteLen is zero!");
370         return false;
371     }
372     std::string strResult = Asn1Utils::BytesToHexStr(outPutBytes);
373     {
374         std::lock_guard<std::mutex> lock(getEidMutex_);
375         eid_ = strResult;
376         isEidReady_ = true;
377     }
378     getEidCv_.notify_one();
379     return true;
380 }
381 
Asn1ParseResponse(const std::vector<uint8_t> &response, uint32_t respLength)382 std::shared_ptr<Asn1Node> EsimFile::Asn1ParseResponse(const std::vector<uint8_t> &response, uint32_t respLength)
383 {
384     if (response.empty() || respLength == 0) {
385         TELEPHONY_LOGE("response null, respLen = %{public}d", respLength);
386         return nullptr;
387     }
388     Asn1Decoder decoder(response, 0, respLength);
389     if (!decoder.Asn1HasNextNode()) {
390         TELEPHONY_LOGE("Empty response");
391         return nullptr;
392     }
393     std::shared_ptr<Asn1Node> node = decoder.Asn1NextNode();
394     return node;
395 }
396 
ProcessObtainEuiccInfo1Done(const AppExecFwk::InnerEvent::Pointer &event)397 bool EsimFile::ProcessObtainEuiccInfo1Done(const AppExecFwk::InnerEvent::Pointer &event)
398 {
399     IccFileData rawData;
400     if (!GetRawDataFromEvent(event, rawData)) {
401         TELEPHONY_LOGE("rawData is nullptr within rcvMsg");
402         return false;
403     }
404     std::vector<uint8_t> responseByte = Asn1Utils::HexStrToBytes(rawData.resultData);
405     uint32_t byteLen = responseByte.size();
406     std::shared_ptr<Asn1Node> root = Asn1ParseResponse(responseByte, byteLen);
407     if (root == nullptr) {
408         TELEPHONY_LOGE("Asn1ParseResponse error!");
409         return false;
410     }
411     if (!ObtainEuiccInfo1ParseTagCtx2(root)) {
412         TELEPHONY_LOGE("ObtainEuiccInfo1ParseTagCtx2 error!");
413         return false;
414     }
415     std::string responseHexStr = rawData.resultData;
416     eUiccInfo_.response_ = Str8ToStr16(responseHexStr);
417     {
418         std::lock_guard<std::mutex> lock(euiccInfo1Mutex_);
419         isEuiccInfo1Ready_ = true;
420     }
421     euiccInfo1Cv_.notify_one();
422     return true;
423 }
424 
ObtainEuiccInfo1ParseTagCtx2(std::shared_ptr<Asn1Node> &root)425 bool EsimFile::ObtainEuiccInfo1ParseTagCtx2(std::shared_ptr<Asn1Node> &root)
426 {
427     std::shared_ptr<Asn1Node> svnNode = root->Asn1GetChild(TAG_ESIM_CTX_2);
428     if (svnNode == nullptr) {
429         TELEPHONY_LOGE("svnNode is nullptr");
430         return false;
431     }
432     std::vector<uint8_t> svnRaw;
433     uint32_t svnRawlen = svnNode->Asn1AsBytes(svnRaw);
434     if (svnRawlen < SVN_RAW_LENGTH_MIN) {
435         TELEPHONY_LOGE("invalid SVN data");
436         return false;
437     }
438     eUiccInfo_.osVersion_ = OHOS::Telephony::ToUtf16(MakeVersionString(svnRaw));
439     return true;
440 }
441 
ProcessRequestAllProfilesDone(const AppExecFwk::InnerEvent::Pointer &event)442 bool EsimFile::ProcessRequestAllProfilesDone(const AppExecFwk::InnerEvent::Pointer &event)
443 {
444     std::shared_ptr<Asn1Node> root = ParseEvent(event);
445     if (root == nullptr) {
446         TELEPHONY_LOGE("root is nullptr");
447         return false;
448     }
449 
450     if (!RequestAllProfilesParseProfileInfo(root)) {
451         TELEPHONY_LOGE("RequestAllProfilesParseProfileInfo error!");
452         return false;
453     }
454 
455     {
456         std::lock_guard<std::mutex> lock(allProfileInfoMutex_);
457         isAllProfileInfoReady_ = true;
458     }
459     allProfileInfoCv_.notify_one();
460     return true;
461 }
462 
RequestAllProfilesParseProfileInfo(std::shared_ptr<Asn1Node> &root)463 bool EsimFile::RequestAllProfilesParseProfileInfo(std::shared_ptr<Asn1Node> &root)
464 {
465     std::shared_ptr<Asn1Node> profileRoot = root->Asn1GetChild(TAG_ESIM_CTX_COMP_0);
466     if (profileRoot == nullptr) {
467         TELEPHONY_LOGE("profileRoot is nullptr");
468         return false;
469     }
470     std::list<std::shared_ptr<Asn1Node>> profileNodes;
471     profileRoot->Asn1GetChildren(TAG_ESIM_PROFILE_INFO, profileNodes);
472     std::shared_ptr<Asn1Node> curNode = nullptr;
473     EuiccProfileInfo euiccProfileInfo = {{0}};
474     euiccProfileInfoList_.profiles_.clear();
475     for (auto it = profileNodes.begin(); it != profileNodes.end(); ++it) {
476         curNode = *it;
477         if (!curNode->Asn1HasChild(TAG_ESIM_ICCID)) {
478             TELEPHONY_LOGE("Profile must have an ICCID.");
479             continue;
480         }
481         BuildBasicProfileInfo(&euiccProfileInfo, curNode);
482         EuiccProfile euiccProfile;
483         ConvertProfileInfoToApiStruct(euiccProfile, euiccProfileInfo);
484         euiccProfileInfoList_.profiles_.push_back(euiccProfile);
485     }
486     euiccProfileInfoList_.result_ = ResultState::RESULT_OK;
487     return true;
488 }
489 
SplitMccAndMnc(const std::string mccMnc, std::string &mcc, std::string &mnc)490 bool EsimFile::SplitMccAndMnc(const std::string mccMnc, std::string &mcc, std::string &mnc)
491 {
492     std::string mMcc(NUMBER_THREE, '\0');
493     mMcc[NUMBER_ZERO] = mccMnc[NUMBER_ONE];
494     mMcc[NUMBER_ONE] = mccMnc[NUMBER_ZERO];
495     mMcc[NUMBER_TWO] = mccMnc[NUMBER_THREE];
496 
497     std::string mMnc(NUMBER_THREE, '\0');
498     if (mccMnc[NUMBER_TWO] == 'F') {
499         mMnc[NUMBER_ZERO] = mccMnc[NUMBER_FIVE];
500         mMnc[NUMBER_ONE] = mccMnc[NUMBER_FOUR];
501     } else {
502         mMnc[NUMBER_ZERO] = mccMnc[NUMBER_FIVE];
503         mMnc[NUMBER_ONE] = mccMnc[NUMBER_FOUR];
504         mMnc[NUMBER_TWO] = mccMnc[NUMBER_TWO];
505     }
506     mcc = mMcc.c_str();
507     mnc = mMnc.c_str();
508     return true;
509 }
510 
ConvertProfileInfoToApiStruct(EuiccProfile &dst, EuiccProfileInfo &src)511 void EsimFile::ConvertProfileInfoToApiStruct(EuiccProfile &dst, EuiccProfileInfo &src)
512 {
513     dst.iccId_ = OHOS::Telephony::ToUtf16(src.iccid);
514     dst.nickName_ = OHOS::Telephony::ToUtf16(src.nickname);
515     dst.serviceProviderName_ = OHOS::Telephony::ToUtf16(src.serviceProviderName);
516     dst.profileName_ = OHOS::Telephony::ToUtf16(src.profileName);
517     dst.state_ = static_cast<ProfileState>(src.profileState);
518     dst.profileClass_ = static_cast<ProfileClass>(src.profileClass);
519     dst.policyRules_ = static_cast<PolicyRules>(src.policyRules);
520 
521     // split mccMnc to mcc and mnc
522     std::string mcc = "";
523     std::string mnc = "";
524     SplitMccAndMnc(src.operatorId.mccMnc, mcc, mnc);
525     dst.carrierId_.mcc_ = OHOS::Telephony::ToUtf16(mcc);
526     dst.carrierId_.mnc_ = OHOS::Telephony::ToUtf16(mnc);
527     dst.carrierId_.gid1_ = OHOS::Telephony::ToUtf16(src.operatorId.gid1);
528     dst.carrierId_.gid2_ = OHOS::Telephony::ToUtf16(src.operatorId.gid2);
529     dst.accessRules_.clear();
530 }
531 
BuildBasicProfileInfo(EuiccProfileInfo *eProfileInfo, std::shared_ptr<Asn1Node> &profileNode)532 void EsimFile::BuildBasicProfileInfo(EuiccProfileInfo *eProfileInfo, std::shared_ptr<Asn1Node> &profileNode)
533 {
534     if (eProfileInfo == nullptr || profileNode == nullptr) {
535         TELEPHONY_LOGE("BuildBasicProfileInfo failed");
536         return;
537     }
538     std::shared_ptr<Asn1Node> iccIdNode = profileNode->Asn1GetChild(TAG_ESIM_ICCID);
539     if (iccIdNode == nullptr) {
540         TELEPHONY_LOGE("iccIdNode is nullptr");
541         return;
542     }
543     std::vector<uint8_t> iccidBytes;
544     uint32_t iccidBytesLen = iccIdNode->Asn1AsBytes(iccidBytes);
545     Asn1Utils::BchToString(iccidBytes, eProfileInfo->iccid);
546     if (profileNode->Asn1HasChild(TAG_ESIM_NICKNAME)) {
547         std::shared_ptr<Asn1Node> nickNameNode = profileNode->Asn1GetChild(TAG_ESIM_NICKNAME);
548         if (nickNameNode == nullptr) {
549             TELEPHONY_LOGE("nickNameNode is nullptr");
550             return;
551         }
552         std::vector<uint8_t> nickNameBytes;
553         nickNameNode->Asn1AsBytes(nickNameBytes);
554         eProfileInfo->nickname = Asn1Utils::BytesToString(nickNameBytes);
555     }
556     if (profileNode->Asn1HasChild(TAG_ESIM_OBTAIN_OPERATOR_NAME)) {
557         std::shared_ptr<Asn1Node> serviceProviderNameNode = profileNode->Asn1GetChild(TAG_ESIM_OBTAIN_OPERATOR_NAME);
558         if (serviceProviderNameNode == nullptr) {
559             TELEPHONY_LOGE("serviceProviderNameNode is nullptr");
560             return;
561         }
562         std::vector<uint8_t> serviceProviderNameBytes;
563         serviceProviderNameNode->Asn1AsBytes(serviceProviderNameBytes);
564         eProfileInfo->serviceProviderName = Asn1Utils::BytesToString(serviceProviderNameBytes);
565     }
566     if (profileNode->Asn1HasChild(TAG_ESIM_PROFILE_NAME)) {
567         std::shared_ptr<Asn1Node> profileNameNode = profileNode->Asn1GetChild(TAG_ESIM_PROFILE_NAME);
568         if (profileNameNode == nullptr) {
569             TELEPHONY_LOGE("profileNameNode is nullptr");
570             return;
571         }
572         std::vector<uint8_t> profileNameBytes;
573         profileNameNode->Asn1AsBytes(profileNameBytes);
574         eProfileInfo->profileName = Asn1Utils::BytesToString(profileNameBytes);
575     }
576     if (profileNode->Asn1HasChild(TAG_ESIM_OPERATOR_ID)) {
577         std::shared_ptr<Asn1Node> pOperatorId = profileNode->Asn1GetChild(TAG_ESIM_OPERATOR_ID);
578         BuildOperatorId(eProfileInfo, pOperatorId);
579     }
580 
581     BuildAdvancedProfileInfo(eProfileInfo, profileNode);
582 }
583 
BuildAdvancedProfileInfo(EuiccProfileInfo *eProfileInfo, std::shared_ptr<Asn1Node> &profileNode)584 void EsimFile::BuildAdvancedProfileInfo(EuiccProfileInfo *eProfileInfo, std::shared_ptr<Asn1Node> &profileNode)
585 {
586     if (eProfileInfo == nullptr || profileNode == nullptr) {
587         TELEPHONY_LOGE("BuildAdvancedProfileInfo failed");
588         return;
589     }
590     if (profileNode->Asn1HasChild(TAG_ESIM_PROFILE_STATE)) {
591         std::shared_ptr<Asn1Node> profileStateNode = profileNode->Asn1GetChild(TAG_ESIM_PROFILE_STATE);
592         if (profileStateNode == nullptr) {
593             TELEPHONY_LOGE("profileStateNode is nullptr");
594             return;
595         }
596         int32_t ret = profileStateNode->Asn1AsInteger();
597         eProfileInfo->profileState = ((ret == TELEPHONY_ERR_ARGUMENT_INVALID) ? ESIM_PROFILE_STATE_DISABLED : ret);
598     } else {
599         eProfileInfo->profileState = ESIM_PROFILE_STATE_DISABLED;
600     }
601     if (profileNode->Asn1HasChild(TAG_ESIM_PROFILE_CLASS)) {
602         std::shared_ptr<Asn1Node> profileClassNode = profileNode->Asn1GetChild(TAG_ESIM_PROFILE_CLASS);
603         if (profileClassNode == nullptr) {
604             TELEPHONY_LOGE("profileClassNode is nullptr");
605             return;
606         }
607         eProfileInfo->profileClass = profileClassNode->Asn1AsInteger();
608     } else {
609         eProfileInfo->profileClass = PROFILE_CLASS_OPERATIONAL;
610     }
611     if (profileNode->Asn1HasChild(TAG_ESIM_PROFILE_POLICY_RULE)) {
612         std::shared_ptr<Asn1Node> profilePolicyRuleNode = profileNode->Asn1GetChild(TAG_ESIM_PROFILE_POLICY_RULE);
613         if (profilePolicyRuleNode == nullptr) {
614             TELEPHONY_LOGE("profilePolicyRuleNode is nullptr");
615             return;
616         }
617         eProfileInfo->policyRules = profilePolicyRuleNode->Asn1AsBits();
618     }
619     if (profileNode->Asn1HasChild(TAG_ESIM_CARRIER_PRIVILEGE_RULES)) {
620         std::list<std::shared_ptr<Asn1Node>> refArDoNodes;
621         std::shared_ptr<Asn1Node> carrierPrivilegeRulesNode =
622             profileNode->Asn1GetChild(TAG_ESIM_CARRIER_PRIVILEGE_RULES);
623         if (carrierPrivilegeRulesNode == nullptr) {
624             TELEPHONY_LOGE("carrierPrivilegeRulesNode is nullptr");
625             return;
626         }
627         carrierPrivilegeRulesNode->Asn1GetChildren(TAG_ESIM_REF_AR_DO, refArDoNodes);
628     }
629 }
630 
BuildOperatorId(EuiccProfileInfo *eProfileInfo, std::shared_ptr<Asn1Node> &operatorIdNode)631 void EsimFile::BuildOperatorId(EuiccProfileInfo *eProfileInfo, std::shared_ptr<Asn1Node> &operatorIdNode)
632 {
633     if (eProfileInfo == nullptr || operatorIdNode == nullptr) {
634         TELEPHONY_LOGE("BuildOperatorId failed");
635         return;
636     }
637     if (operatorIdNode->Asn1HasChild(TAG_ESIM_CTX_0)) {
638         std::shared_ptr<Asn1Node> nodeCtx0 = operatorIdNode->Asn1GetChild(TAG_ESIM_CTX_0);
639         if (nodeCtx0 == nullptr) {
640             TELEPHONY_LOGE("nodeCtx0 is nullptr");
641             return;
642         }
643         nodeCtx0->Asn1AsString(eProfileInfo->operatorId.mccMnc);
644     }
645     if (operatorIdNode->Asn1HasChild(TAG_ESIM_CTX_1)) {
646         std::shared_ptr<Asn1Node> nodeCtx1 = operatorIdNode->Asn1GetChild(TAG_ESIM_CTX_1);
647         if (nodeCtx1 == nullptr) {
648             TELEPHONY_LOGE("nodeCtx1 is nullptr");
649             return;
650         }
651         nodeCtx1->Asn1AsString(eProfileInfo->operatorId.gid1);
652     }
653     if (operatorIdNode->Asn1HasChild(TAG_ESIM_CTX_2)) {
654         std::shared_ptr<Asn1Node> nodeCtx2 = operatorIdNode->Asn1GetChild(TAG_ESIM_CTX_2);
655         if (nodeCtx2 == nullptr) {
656             TELEPHONY_LOGE("nodeCtx2 is nullptr");
657             return;
658         }
659         nodeCtx2->Asn1AsString(eProfileInfo->operatorId.gid2);
660     }
661     return;
662 }
663 
DisableProfile(int32_t portIndex, const std::u16string &iccId)664 ResultState EsimFile::DisableProfile(int32_t portIndex, const std::u16string &iccId)
665 {
666     esimProfile_.portIndex = portIndex;
667     esimProfile_.iccId = iccId;
668     SyncOpenChannel();
669     AppExecFwk::InnerEvent::Pointer eventDisableProfile = BuildCallerInfo(MSG_ESIM_DISABLE_PROFILE);
670     if (!ProcessDisableProfile(slotId_, eventDisableProfile)) {
671         TELEPHONY_LOGE("ProcessDisableProfile encode failed");
672         return ResultState();
673     }
674     isDisableProfileReady_ = false;
675     std::unique_lock<std::mutex> lock(disableProfileMutex_);
676     if (!disableProfileCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
677         [this]() { return isDisableProfileReady_; })) {
678         SyncCloseChannel();
679         return ResultState();
680     }
681     SyncCloseChannel();
682     return disableProfileResult_;
683 }
684 
ObtainSmdsAddress(int32_t portIndex)685 std::string EsimFile::ObtainSmdsAddress(int32_t portIndex)
686 {
687     esimProfile_.portIndex = portIndex;
688     SyncOpenChannel();
689     AppExecFwk::InnerEvent::Pointer eventObtainSmdsAddress = BuildCallerInfo(MSG_ESIM_OBTAIN_SMDS_ADDRESS);
690     if (!ProcessObtainSmdsAddress(slotId_, eventObtainSmdsAddress)) {
691         TELEPHONY_LOGE("ProcessObtainSmdsAddress encode failed");
692         return "";
693     }
694     isSmdsAddressReady_ = false;
695     std::unique_lock<std::mutex> lock(smdsAddressMutex_);
696     if (!smdsAddressCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
697         [this]() { return isSmdsAddressReady_; })) {
698         SyncCloseChannel();
699         return "";
700     }
701     SyncCloseChannel();
702     return smdsAddress_;
703 }
704 
ObtainRulesAuthTable(int32_t portIndex)705 EuiccRulesAuthTable EsimFile::ObtainRulesAuthTable(int32_t portIndex)
706 {
707     esimProfile_.portIndex = portIndex;
708     SyncOpenChannel();
709     AppExecFwk::InnerEvent::Pointer eventRequestRulesAuthTable = BuildCallerInfo(MSG_ESIM_REQUEST_RULES_AUTH_TABLE);
710     if (!ProcessRequestRulesAuthTable(slotId_, eventRequestRulesAuthTable)) {
711         TELEPHONY_LOGE("ProcessRequestRulesAuthTable encode failed");
712         return EuiccRulesAuthTable();
713     }
714     isRulesAuthTableReady_ = false;
715     std::unique_lock<std::mutex> lock(rulesAuthTableMutex_);
716     if (!rulesAuthTableCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
717         [this]() { return isRulesAuthTableReady_; })) {
718         SyncCloseChannel();
719         return EuiccRulesAuthTable();
720     }
721     SyncCloseChannel();
722     return eUiccRulesAuthTable_;
723 }
724 
ObtainEuiccChallenge(int32_t portIndex)725 ResponseEsimResult EsimFile::ObtainEuiccChallenge(int32_t portIndex)
726 {
727     esimProfile_.portIndex = portIndex;
728     SyncOpenChannel();
729     AppExecFwk::InnerEvent::Pointer eventEUICCChanllenge = BuildCallerInfo(MSG_ESIM_OBTAIN_EUICC_CHALLENGE_DONE);
730     if (!ProcessObtainEuiccChallenge(slotId_, eventEUICCChanllenge)) {
731         TELEPHONY_LOGE("ProcessObtainEuiccChallenge encode failed");
732         return ResponseEsimResult();
733     }
734     isEuiccChallengeReady_ = false;
735     std::unique_lock<std::mutex> lock(euiccChallengeMutex_);
736     if (!euiccChallengeCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
737         [this]() { return isEuiccChallengeReady_; })) {
738         SyncCloseChannel();
739         return ResponseEsimResult();
740     }
741     SyncCloseChannel();
742     return responseChallengeResult_;
743 }
744 
ProcessDisableProfile(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)745 bool EsimFile::ProcessDisableProfile(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
746 {
747     if (!IsLogicChannelOpen()) {
748         return false;
749     }
750     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_DISABLE_PROFILE);
751     std::shared_ptr<Asn1Builder> subBuilder = std::make_shared<Asn1Builder>(TAG_ESIM_CTX_COMP_0);
752     if (builder == nullptr || subBuilder == nullptr) {
753         TELEPHONY_LOGE("get builder failed");
754         return false;
755     }
756     std::vector<uint8_t> iccidBytes;
757     std::string str = OHOS::Telephony::ToUtf8(esimProfile_.iccId);
758     Asn1Utils::BcdToBytes(str, iccidBytes);
759     subBuilder->Asn1AddChildAsBytes(TAG_ESIM_ICCID, iccidBytes, iccidBytes.size());
760     std::shared_ptr<Asn1Node> subNode = subBuilder->Asn1Build();
761     if (subNode == nullptr) {
762         return false;
763     }
764     builder->Asn1AddChild(subNode);
765     builder->Asn1AddChildAsBoolean(TAG_ESIM_CTX_1, true);
766     ApduSimIORequestInfo reqInfo;
767     CommBuildOneApduReqInfo(reqInfo, builder);
768     if (telRilManager_ == nullptr) {
769         return false;
770     }
771     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
772     if (apduResult == TELEPHONY_ERR_FAIL) {
773         return false;
774     }
775     return true;
776 }
777 
ProcessObtainSmdsAddress(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)778 bool EsimFile::ProcessObtainSmdsAddress(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
779 {
780     if (!IsLogicChannelOpen()) {
781         return false;
782     }
783     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_GET_CONFIGURED_ADDRESSES);
784     if (builder == nullptr) {
785         TELEPHONY_LOGE("builder is nullptr");
786         return false;
787     }
788     ApduSimIORequestInfo reqInfo;
789     CommBuildOneApduReqInfo(reqInfo, builder);
790     if (telRilManager_ == nullptr) {
791         return false;
792     }
793     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
794     if (apduResult == TELEPHONY_ERR_FAIL) {
795         return false;
796     }
797     return true;
798 }
799 
ProcessRequestRulesAuthTable(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)800 bool EsimFile::ProcessRequestRulesAuthTable(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
801 {
802     if (!IsLogicChannelOpen()) {
803         return false;
804     }
805     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_GET_RAT);
806     ApduSimIORequestInfo reqInfo;
807     CommBuildOneApduReqInfo(reqInfo, builder);
808     if (telRilManager_ == nullptr) {
809         return false;
810     }
811     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
812     if (apduResult == TELEPHONY_ERR_FAIL) {
813         return false;
814     }
815     return true;
816 }
817 
ProcessObtainEuiccChallenge(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)818 bool EsimFile::ProcessObtainEuiccChallenge(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
819 {
820     if (!IsLogicChannelOpen()) {
821         return false;
822     }
823     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_GET_EUICC_CHALLENGE);
824     if (builder == nullptr) {
825         TELEPHONY_LOGE("builder is nullptr");
826         return false;
827     }
828     ApduSimIORequestInfo reqInfo;
829     CommBuildOneApduReqInfo(reqInfo, builder);
830     if (telRilManager_ == nullptr) {
831         return false;
832     }
833     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
834     if (apduResult == TELEPHONY_ERR_FAIL) {
835         return false;
836     }
837     return true;
838 }
839 
ProcessDisableProfileDone(const AppExecFwk::InnerEvent::Pointer &event)840 bool EsimFile::ProcessDisableProfileDone(const AppExecFwk::InnerEvent::Pointer &event)
841 {
842     std::shared_ptr<Asn1Node> root = ParseEvent(event);
843     if (root == nullptr) {
844         TELEPHONY_LOGE("Asn1ParseResponse failed");
845         return false;
846     }
847     std::shared_ptr<Asn1Node> pAsn1Node = root->Asn1GetChild(TAG_ESIM_CTX_0);
848     if (pAsn1Node == nullptr) {
849         TELEPHONY_LOGE("pAsn1Node is nullptr");
850         return false;
851     }
852     disableProfileResult_ = static_cast<ResultState>(pAsn1Node->Asn1AsInteger());
853     {
854         std::lock_guard<std::mutex> lock(disableProfileMutex_);
855         isDisableProfileReady_ = true;
856     }
857     disableProfileCv_.notify_one();
858     return true;
859 }
860 
ProcessObtainSmdsAddressDone(const AppExecFwk::InnerEvent::Pointer &event)861 bool EsimFile::ProcessObtainSmdsAddressDone(const AppExecFwk::InnerEvent::Pointer &event)
862 {
863     std::shared_ptr<Asn1Node> root = ParseEvent(event);
864     if (root == nullptr) {
865         TELEPHONY_LOGE("Asn1ParseResponse failed");
866         return false;
867     }
868     std::shared_ptr<Asn1Node> profileRoot = root->Asn1GetChild(TAG_ESIM_CTX_1);
869     if (profileRoot == nullptr) {
870         TELEPHONY_LOGE("profileRoot is nullptr!");
871         return false;
872     }
873     std::vector<uint8_t> outPutBytes;
874     profileRoot->Asn1AsBytes(outPutBytes);
875     smdsAddress_ = Asn1Utils::BytesToString(outPutBytes);
876     {
877         std::lock_guard<std::mutex> lock(smdsAddressMutex_);
878         isSmdsAddressReady_ = true;
879     }
880     smdsAddressCv_.notify_one();
881     return true;
882 }
883 
CarrierIdentifiers(const std::vector<uint8_t> &mccMncData, int mccMncLen, const std::u16string &gid1, const std::u16string &gid2)884 struct CarrierIdentifier CarrierIdentifiers(const std::vector<uint8_t> &mccMncData, int mccMncLen,
885     const std::u16string &gid1, const std::u16string &gid2)
886 {
887     std::string strResult = Asn1Utils::BytesToHexStr(mccMncData);
888     std::string mMcc(NUMBER_THREE, '\0');
889     mMcc[NUMBER_ZERO] = strResult[NUMBER_ONE];
890     mMcc[NUMBER_ONE] = strResult[NUMBER_ZERO];
891     mMcc[NUMBER_TWO] = strResult[NUMBER_THREE];
892     std::string mMnc(NUMBER_THREE, '\0');
893     mMnc[NUMBER_ZERO] = strResult[NUMBER_FIVE];
894     mMnc[NUMBER_ONE] = strResult[NUMBER_FOUR];
895     if (strResult[NUMBER_TWO] != 'F') {
896         mMnc[NUMBER_TWO] = strResult[NUMBER_TWO];
897     }
898     CarrierIdentifier carrierId;
899     carrierId.mcc_ = OHOS::Telephony::ToUtf16(std::string(mMcc.c_str()));
900     carrierId.mnc_ = OHOS::Telephony::ToUtf16(std::string(mMnc.c_str()));
901     carrierId.gid1_ = gid1;
902     carrierId.gid2_ = gid2;
903     return carrierId;
904 }
905 
buildCarrierIdentifiers(std::shared_ptr<Asn1Node> &root)906 struct CarrierIdentifier buildCarrierIdentifiers(std::shared_ptr<Asn1Node> &root)
907 {
908     std::u16string gid1;
909     std::u16string gid2;
910     std::vector<uint8_t> gid1Byte;
911     std::vector<uint8_t> gid2Byte;
912     std::string strResult;
913     CarrierIdentifier defaultCarrier = CarrierIdentifiers({}, 0, u"", u"");
914     if (root->Asn1HasChild(TAG_ESIM_CTX_1)) {
915         std::shared_ptr<Asn1Node> node = root->Asn1GetChild(TAG_ESIM_CTX_1);
916         if (node == nullptr) {
917             return defaultCarrier;
918         }
919         node->Asn1AsBytes(gid1Byte);
920         strResult = Asn1Utils::BytesToHexStr(gid1Byte);
921         gid1 = OHOS::Telephony::ToUtf16(strResult);
922     }
923     if (root->Asn1HasChild(TAG_ESIM_CTX_2)) {
924         std::shared_ptr<Asn1Node> node = root->Asn1GetChild(TAG_ESIM_CTX_2);
925         if (node == nullptr) {
926             return defaultCarrier;
927         }
928         node->Asn1AsBytes(gid2Byte);
929         strResult = Asn1Utils::BytesToHexStr(gid2Byte);
930         gid2 = OHOS::Telephony::ToUtf16(strResult);
931     }
932 
933     std::vector<uint8_t> mccMnc;
934     std::shared_ptr<Asn1Node> ctx0Node = root->Asn1GetChild(TAG_ESIM_CTX_0);
935     if (ctx0Node == nullptr) {
936         return defaultCarrier;
937     }
938     uint32_t mccMncLen = ctx0Node->Asn1AsBytes(mccMnc);
939     CarrierIdentifier myCarrier = CarrierIdentifiers(mccMnc, mccMncLen, gid1, gid2);
940     return myCarrier;
941 }
942 
RequestRulesAuthTableParseTagCtxComp0(std::shared_ptr<Asn1Node> &root)943 bool EsimFile::RequestRulesAuthTableParseTagCtxComp0(std::shared_ptr<Asn1Node> &root)
944 {
945     std::list<std::shared_ptr<Asn1Node>> Nodes;
946     std::list<std::shared_ptr<Asn1Node>> opIdNodes;
947     root->Asn1GetChildren(TAG_ESIM_CTX_COMP_0, Nodes);
948     for (auto it = Nodes.begin(); it != Nodes.end(); ++it) {
949         std::shared_ptr<Asn1Node> node = *it;
950         if (node == nullptr) {
951             return false;
952         }
953         std::shared_ptr<Asn1Node> grandson = node->Asn1GetGrandson(TAG_ESIM_SEQUENCE, TAG_ESIM_CTX_COMP_1);
954         if (grandson == nullptr) {
955             return false;
956         }
957         int32_t opIdNodesRes = grandson->Asn1GetChildren(TAG_ESIM_OPERATOR_ID, opIdNodes);
958         if (opIdNodesRes != 0) {
959             return false;
960         }
961         for (auto iter = opIdNodes.begin(); iter != opIdNodes.end(); ++iter) {
962             std::shared_ptr<Asn1Node> curNode = nullptr;
963             curNode = *iter;
964             if (curNode == nullptr) {
965                 return false;
966             }
967             eUiccRulesAuthTable_.carrierIds_.push_back(buildCarrierIdentifiers(curNode));
968         }
969         grandson = node->Asn1GetGrandson(TAG_ESIM_SEQUENCE, TAG_ESIM_CTX_0);
970         if (grandson == nullptr) {
971             return false;
972         }
973         int32_t policyRules = grandson->Asn1AsInteger();
974         grandson = node->Asn1GetGrandson(TAG_ESIM_SEQUENCE, TAG_ESIM_CTX_2);
975         if (grandson == nullptr) {
976             return false;
977         }
978         int32_t policyRuleFlags = grandson->Asn1AsInteger();
979         eUiccRulesAuthTable_.policyRules_.push_back(policyRules);
980         eUiccRulesAuthTable_.policyRuleFlags_.push_back(policyRuleFlags);
981     }
982     return true;
983 }
984 
ProcessRequestRulesAuthTableDone(const AppExecFwk::InnerEvent::Pointer &event)985 bool EsimFile::ProcessRequestRulesAuthTableDone(const AppExecFwk::InnerEvent::Pointer &event)
986 {
987     std::shared_ptr<Asn1Node> root = ParseEvent(event);
988     if (root == nullptr) {
989         TELEPHONY_LOGE("root is nullptr");
990         return false;
991     }
992     if (!RequestRulesAuthTableParseTagCtxComp0(root)) {
993         TELEPHONY_LOGE("RequestRulesAuthTableParseTagCtxComp0 error");
994         return false;
995     }
996 
997     {
998         std::lock_guard<std::mutex> lock(rulesAuthTableMutex_);
999         isRulesAuthTableReady_ = true;
1000     }
1001     rulesAuthTableCv_.notify_one();
1002     return true;
1003 }
1004 
ProcessObtainEuiccChallengeDone(const AppExecFwk::InnerEvent::Pointer &event)1005 bool EsimFile::ProcessObtainEuiccChallengeDone(const AppExecFwk::InnerEvent::Pointer &event)
1006 {
1007     std::shared_ptr<Asn1Node> root = ParseEvent(event);
1008     if (root == nullptr) {
1009         TELEPHONY_LOGE("root is nullptr");
1010         return false;
1011     }
1012     std::shared_ptr<Asn1Node> profileRoot = root->Asn1GetChild(TAG_ESIM_CTX_0);
1013     if (profileRoot == nullptr) {
1014         TELEPHONY_LOGE("Asn1GetChild failed");
1015         return false;
1016     }
1017     std::vector<uint8_t> profileResponseByte;
1018     uint32_t byteLen = profileRoot->Asn1AsBytes(profileResponseByte);
1019     if (byteLen == 0) {
1020         return false;
1021     }
1022     std::string resultStr = Asn1Utils::BytesToHexStr(profileResponseByte);
1023     responseChallengeResult_.resultCode_ = ResultState::RESULT_OK;
1024     responseChallengeResult_.response_ = OHOS::Telephony::ToUtf16(resultStr);
1025     {
1026         std::lock_guard<std::mutex> lock(euiccChallengeMutex_);
1027         isEuiccChallengeReady_ = true;
1028     }
1029     euiccChallengeCv_.notify_one();
1030     return true;
1031 }
1032 
ObtainDefaultSmdpAddress()1033 std::string EsimFile::ObtainDefaultSmdpAddress()
1034 {
1035     SyncOpenChannel();
1036     AppExecFwk::InnerEvent::Pointer eventSmdpAddress = BuildCallerInfo(MSG_ESIM_OBTAIN_DEFAULT_SMDP_ADDRESS_DONE);
1037     if (!ProcessObtainDefaultSmdpAddress(slotId_, eventSmdpAddress)) {
1038         TELEPHONY_LOGE("ProcessObtainDefaultSmdpAddress encode failed");
1039         return "";
1040     }
1041     isObtainDefaultSmdpAddressReady_ = false;
1042     std::unique_lock<std::mutex> lock(obtainDefaultSmdpAddressMutex_);
1043     if (!obtainDefaultSmdpAddressCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
1044         [this]() { return isObtainDefaultSmdpAddressReady_; })) {
1045         SyncCloseChannel();
1046         return "";
1047     }
1048     SyncCloseChannel();
1049     return defaultDpAddress_;
1050 }
1051 
CancelSession(const std::u16string &transactionId, CancelReason cancelReason)1052 ResponseEsimResult EsimFile::CancelSession(const std::u16string &transactionId, CancelReason cancelReason)
1053 {
1054     esimProfile_.transactionId = transactionId;
1055     esimProfile_.cancelReason = cancelReason;
1056     SyncOpenChannel();
1057     AppExecFwk::InnerEvent::Pointer eventCancelSession = BuildCallerInfo(MSG_ESIM_CANCEL_SESSION);
1058     if (!ProcessCancelSession(slotId_, eventCancelSession)) {
1059         TELEPHONY_LOGE("ProcessCancelSession encode failed");
1060         return ResponseEsimResult();
1061     }
1062     isCancelSessionReady_ = false;
1063     std::unique_lock<std::mutex> lock(cancelSessionMutex_);
1064     if (!cancelSessionCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
1065         [this]() { return isCancelSessionReady_; })) {
1066         SyncCloseChannel();
1067         return ResponseEsimResult();
1068     }
1069     SyncCloseChannel();
1070     return cancelSessionResult_;
1071 }
1072 
ObtainProfile(int32_t portIndex, const std::u16string &iccId)1073 EuiccProfile EsimFile::ObtainProfile(int32_t portIndex, const std::u16string &iccId)
1074 {
1075     esimProfile_.portIndex = portIndex;
1076     esimProfile_.iccId = iccId;
1077     SyncOpenChannel();
1078     AppExecFwk::InnerEvent::Pointer eventGetProfile = BuildCallerInfo(MSG_ESIM_GET_PROFILE);
1079     if (!ProcessGetProfile(slotId_, eventGetProfile)) {
1080         TELEPHONY_LOGE("ProcessGetProfile encode failed");
1081         return EuiccProfile();
1082     }
1083     isObtainProfileReady_ = false;
1084     std::unique_lock<std::mutex> lock(obtainProfileMutex_);
1085     if (!obtainProfileCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
1086         [this]() { return isObtainProfileReady_; })) {
1087         SyncCloseChannel();
1088         return EuiccProfile();
1089     }
1090     SyncCloseChannel();
1091     return eUiccProfile_;
1092 }
1093 
ProcessObtainDefaultSmdpAddress(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)1094 bool EsimFile::ProcessObtainDefaultSmdpAddress(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
1095 {
1096     if (!IsLogicChannelOpen()) {
1097         return false;
1098     }
1099     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_GET_CONFIGURED_ADDRESSES);
1100     if (builder == nullptr) {
1101         TELEPHONY_LOGE("get builder failed");
1102         return false;
1103     }
1104     ApduSimIORequestInfo reqInfo;
1105     CommBuildOneApduReqInfo(reqInfo, builder);
1106     if (telRilManager_ == nullptr) {
1107         return false;
1108     }
1109     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
1110     if (apduResult == TELEPHONY_ERR_FAIL) {
1111         return false;
1112     }
1113     return true;
1114 }
1115 
ProcessGetProfile(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)1116 bool EsimFile::ProcessGetProfile(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
1117 {
1118     if (!IsLogicChannelOpen()) {
1119         return false;
1120     }
1121     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_GET_PROFILES);
1122     std::shared_ptr<Asn1Builder> subBuilder = std::make_shared<Asn1Builder>(TAG_ESIM_CTX_COMP_0);
1123     if (builder == nullptr || subBuilder == nullptr) {
1124         TELEPHONY_LOGE("get builder failed");
1125         return false;
1126     }
1127     std::vector<uint8_t> iccidBytes;
1128     std::string iccid = OHOS::Telephony::ToUtf8(esimProfile_.iccId);
1129     Asn1Utils::BcdToBytes(iccid, iccidBytes);
1130     subBuilder->Asn1AddChildAsBytes(TAG_ESIM_ICCID, iccidBytes, iccidBytes.size());
1131     std::shared_ptr<Asn1Node> subNode = subBuilder->Asn1Build();
1132     builder->Asn1AddChild(subNode);
1133     std::vector<uint8_t> getProfileTags = GetProfileTagList();
1134     builder->Asn1AddChildAsBytes(TAG_ESIM_TAG_LIST, getProfileTags, getProfileTags.size());
1135     ApduSimIORequestInfo reqInfo;
1136     CommBuildOneApduReqInfo(reqInfo, builder);
1137     if (telRilManager_ == nullptr) {
1138         return false;
1139     }
1140     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
1141     if (apduResult == TELEPHONY_ERR_FAIL) {
1142         return false;
1143     }
1144     return true;
1145 }
1146 
GetProfileTagList()1147 std::vector<uint8_t> EsimFile::GetProfileTagList()
1148 {
1149     unsigned char EUICC_PROFILE_TAGS[] = {
1150         static_cast<unsigned char>(TAG_ESIM_ICCID),
1151         static_cast<unsigned char>(TAG_ESIM_NICKNAME),
1152         static_cast<unsigned char>(TAG_ESIM_OBTAIN_OPERATOR_NAME),
1153         static_cast<unsigned char>(TAG_ESIM_PROFILE_NAME),
1154         static_cast<unsigned char>(TAG_ESIM_OPERATOR_ID),
1155         static_cast<unsigned char>(TAG_ESIM_PROFILE_STATE / PROFILE_DEFAULT_NUMBER),
1156         static_cast<unsigned char>(TAG_ESIM_PROFILE_STATE % PROFILE_DEFAULT_NUMBER),
1157         static_cast<unsigned char>(TAG_ESIM_PROFILE_CLASS),
1158         static_cast<unsigned char>(TAG_ESIM_PROFILE_POLICY_RULE),
1159         static_cast<unsigned char>(TAG_ESIM_CARRIER_PRIVILEGE_RULES / PROFILE_DEFAULT_NUMBER),
1160         static_cast<unsigned char>(TAG_ESIM_CARRIER_PRIVILEGE_RULES % PROFILE_DEFAULT_NUMBER),
1161     };
1162     std::vector<uint8_t> getProfileTags;
1163     for (const unsigned char tag : EUICC_PROFILE_TAGS) {
1164         getProfileTags.push_back(tag);
1165     }
1166     return getProfileTags;
1167 }
1168 
ProcessCancelSession(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)1169 bool EsimFile::ProcessCancelSession(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
1170 {
1171     if (!IsLogicChannelOpen()) {
1172         return false;
1173     }
1174     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_CANCEL_SESSION);
1175     if (builder == nullptr) {
1176         TELEPHONY_LOGE("builder is nullptr");
1177         return false;
1178     }
1179     std::string transactionIdStr = Str16ToStr8(esimProfile_.transactionId);
1180     std::vector<uint8_t> transactionIdByte = Asn1Utils::HexStrToBytes(transactionIdStr);
1181     builder->Asn1AddChildAsBytes(TAG_ESIM_CTX_0, transactionIdByte, transactionIdByte.size());
1182     builder->Asn1AddChildAsInteger(TAG_ESIM_CTX_1, static_cast<uint32_t>(esimProfile_.cancelReason));
1183     ApduSimIORequestInfo reqInfo;
1184     CommBuildOneApduReqInfo(reqInfo, builder);
1185     if (telRilManager_ == nullptr) {
1186         return false;
1187     }
1188     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
1189     if (apduResult == TELEPHONY_ERR_FAIL) {
1190         return false;
1191     }
1192     return true;
1193 }
1194 
ProcessObtainDefaultSmdpAddressDone(const AppExecFwk::InnerEvent::Pointer &event)1195 bool EsimFile::ProcessObtainDefaultSmdpAddressDone(const AppExecFwk::InnerEvent::Pointer &event)
1196 {
1197     if (event == nullptr) {
1198         TELEPHONY_LOGE("event is nullptr");
1199         return false;
1200     }
1201     std::shared_ptr<Asn1Node> root = ParseEvent(event);
1202     if (root == nullptr) {
1203         TELEPHONY_LOGE("Asn1ParseResponse failed");
1204         return false;
1205     }
1206     std::shared_ptr<Asn1Node> profileRoot = root->Asn1GetChild(TAG_ESIM_CTX_0);
1207     if (profileRoot == nullptr) {
1208         return false;
1209     }
1210     std::vector<uint8_t> outPutBytes;
1211     uint32_t byteLen = profileRoot->Asn1AsBytes(outPutBytes);
1212     if (byteLen == 0) {
1213         TELEPHONY_LOGE("byteLen is zero");
1214         return false;
1215     }
1216     defaultDpAddress_ = Asn1Utils::BytesToHexStr(outPutBytes);
1217     return true;
1218 }
1219 
ProcessCancelSessionDone(const AppExecFwk::InnerEvent::Pointer &event)1220 bool EsimFile::ProcessCancelSessionDone(const AppExecFwk::InnerEvent::Pointer &event)
1221 {
1222     if (event == nullptr) {
1223         TELEPHONY_LOGE("event is nullptr!");
1224         return false;
1225     }
1226     std::shared_ptr<Asn1Node> root = ParseEvent(event);
1227     if (root == nullptr) {
1228         TELEPHONY_LOGE("root is nullptr");
1229         return false;
1230     }
1231     std::string responseResult;
1232     uint32_t byteLen = root->Asn1AsString(responseResult);
1233     if (byteLen == 0) {
1234         return false;
1235     }
1236     cancelSessionResult_.resultCode_ = ResultState::RESULT_OK;
1237     cancelSessionResult_.response_ = OHOS::Telephony::ToUtf16(responseResult);
1238     {
1239         std::lock_guard<std::mutex> lock(cancelSessionMutex_);
1240         isCancelSessionReady_ = true;
1241     }
1242     cancelSessionCv_.notify_one();
1243     return true;
1244 }
1245 
GetProfileDoneParseProfileInfo(std::shared_ptr<Asn1Node> &root)1246 bool EsimFile::GetProfileDoneParseProfileInfo(std::shared_ptr<Asn1Node> &root)
1247 {
1248     std::shared_ptr<Asn1Node> profileInfo = root->Asn1GetGrandson(TAG_ESIM_CTX_COMP_0, TAG_ESIM_PROFILE_INFO);
1249     if (profileInfo == nullptr) {
1250         TELEPHONY_LOGE("get profile list failed");
1251         return false;
1252     }
1253     std::shared_ptr<Asn1Node> iccNode = profileInfo->Asn1GetChild(TAG_ESIM_ICCID);
1254     if (iccNode == nullptr) {
1255         TELEPHONY_LOGE("nodeIcc is nullptr");
1256         return false;
1257     }
1258     EuiccProfileInfo euiccProfileInfo = {{0}};
1259     BuildBasicProfileInfo(&euiccProfileInfo, profileInfo);
1260     ConvertProfileInfoToApiStruct(eUiccProfile_, euiccProfileInfo);
1261     return true;
1262 }
1263 
ProcessGetProfileDone(const AppExecFwk::InnerEvent::Pointer &event)1264 bool EsimFile::ProcessGetProfileDone(const AppExecFwk::InnerEvent::Pointer &event)
1265 {
1266     if (event == nullptr) {
1267         TELEPHONY_LOGE("event is nullptr!");
1268         return false;
1269     }
1270     std::shared_ptr<Asn1Node> root = ParseEvent(event);
1271     if (root == nullptr) {
1272         TELEPHONY_LOGE("Asn1ParseResponse failed");
1273         return false;
1274     }
1275     if (!GetProfileDoneParseProfileInfo(root)) {
1276         TELEPHONY_LOGE("GetProfileDoneParseProfileInfo error!");
1277         return false;
1278     }
1279 
1280     {
1281         std::lock_guard<std::mutex> lock(obtainProfileMutex_);
1282         isObtainProfileReady_ = true;
1283     }
1284     obtainProfileCv_.notify_one();
1285     return true;
1286 }
1287 
ResetMemory(ResetOption resetOption)1288 ResultState EsimFile::ResetMemory(ResetOption resetOption)
1289 {
1290     esimProfile_.option = resetOption;
1291     SyncOpenChannel();
1292     AppExecFwk::InnerEvent::Pointer eventResetMemory = BuildCallerInfo(MSG_ESIM_RESET_MEMORY);
1293     if (!ProcessResetMemory(slotId_, eventResetMemory)) {
1294         TELEPHONY_LOGE("ProcessResetMemory encode failed");
1295         return ResultState();
1296     }
1297     isResetMemoryReady_ = false;
1298     std::unique_lock<std::mutex> lock(resetMemoryMutex_);
1299     if (!resetMemoryCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
1300         [this]() { return isResetMemoryReady_; })) {
1301         SyncCloseChannel();
1302         return ResultState();
1303     }
1304     SyncCloseChannel();
1305     return resetResult_;
1306 }
1307 
SetDefaultSmdpAddress(const std::u16string &defaultSmdpAddress)1308 ResultState EsimFile::SetDefaultSmdpAddress(const std::u16string &defaultSmdpAddress)
1309 {
1310     esimProfile_.defaultSmdpAddress = defaultSmdpAddress;
1311     SyncOpenChannel();
1312     AppExecFwk::InnerEvent::Pointer eventSetSmdpAddress = BuildCallerInfo(MSG_ESIM_ESTABLISH_DEFAULT_SMDP_ADDRESS_DONE);
1313     if (!ProcessEstablishDefaultSmdpAddress(slotId_, eventSetSmdpAddress)) {
1314         TELEPHONY_LOGE("ProcessEstablishDefaultSmdpAddress encode failed!!");
1315         return ResultState();
1316     }
1317     isSetDefaultSmdpAddressReady_ = false;
1318     std::unique_lock<std::mutex> lock(setDefaultSmdpAddressMutex_);
1319     if (!setDefaultSmdpAddressCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
1320         [this]() { return isSetDefaultSmdpAddressReady_; })) {
1321         SyncCloseChannel();
1322         return ResultState();
1323     }
1324     SyncCloseChannel();
1325     return setDpAddressResult_;
1326 }
1327 
ProcessEstablishDefaultSmdpAddress(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)1328 bool EsimFile::ProcessEstablishDefaultSmdpAddress(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
1329 {
1330     if (!IsLogicChannelOpen()) {
1331         return false;
1332     }
1333 
1334     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_SET_DEFAULT_SMDP_ADDRESS);
1335     if (builder == nullptr) {
1336         TELEPHONY_LOGE("builder is nullptr");
1337         return false;
1338     }
1339     std::string address = OHOS::Telephony::ToUtf8(esimProfile_.defaultSmdpAddress);
1340     builder->Asn1AddChildAsString(TAG_ESIM_TARGET_ADDR, address);
1341     ApduSimIORequestInfo reqInfo;
1342     CommBuildOneApduReqInfo(reqInfo, builder);
1343     if (telRilManager_ == nullptr) {
1344         return false;
1345     }
1346     telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
1347     return true;
1348 }
1349 
ProcessEstablishDefaultSmdpAddressDone(const AppExecFwk::InnerEvent::Pointer &event)1350 bool EsimFile::ProcessEstablishDefaultSmdpAddressDone(const AppExecFwk::InnerEvent::Pointer &event)
1351 {
1352     std::shared_ptr<Asn1Node> root = ParseEvent(event);
1353     if (root == nullptr) {
1354         TELEPHONY_LOGE("Asn1ParseResponse failed");
1355         return false;
1356     }
1357     std::shared_ptr<Asn1Node> pAsn1Node = root->Asn1GetChild(TAG_ESIM_CTX_0);
1358     if (pAsn1Node == nullptr) {
1359         TELEPHONY_LOGE("pAsn1Node is nullptr");
1360         return false;
1361     }
1362     setDpAddressResult_ = static_cast<ResultState>(pAsn1Node->Asn1AsInteger());
1363     {
1364         std::lock_guard<std::mutex> lock(setDefaultSmdpAddressMutex_);
1365         isSetDefaultSmdpAddressReady_ = true;
1366     }
1367     setDefaultSmdpAddressCv_.notify_one();
1368     return true;
1369 }
1370 
IsEsimSupported()1371 bool EsimFile::IsEsimSupported()
1372 {
1373     char buf[ATR_LENGTH + 1] = {0};
1374     GetParameter(TEL_ESIM_SUPPORT, "", buf, ATR_LENGTH);
1375     ResetResponse resetResponse;
1376     std::string atr(buf);
1377     resetResponse.AnalysisAtrData(atr);
1378     isSupported_ = resetResponse.IsEuiccAvailable();
1379     return isSupported_;
1380 }
1381 
SendApduData(const std::u16string &aid, const EsimApduData &apduData)1382 ResponseEsimResult EsimFile::SendApduData(const std::u16string &aid, const EsimApduData &apduData)
1383 {
1384     if (aid.empty()) {
1385         return ResponseEsimResult();
1386     }
1387     if (esimProfile_.aid != aid) {
1388         SyncCloseChannel();
1389         esimProfile_.aid = aid;
1390     }
1391     esimProfile_.apduData = apduData;
1392     if (esimProfile_.apduData.closeChannelFlag_) {
1393         SyncCloseChannel();
1394         esimProfile_.apduData.instructionType_ = 0;
1395         esimProfile_.apduData.instruction_ = 0;
1396         esimProfile_.apduData.p1_ = 0;
1397         esimProfile_.apduData.p2_ = 0;
1398         esimProfile_.apduData.p3_ = 0;
1399         esimProfile_.apduData.unusedDefaultReqHeadFlag_ = false;
1400         return ResponseEsimResult();
1401     }
1402 
1403     SyncOpenChannel(aid);
1404     AppExecFwk::InnerEvent::Pointer eventSendApduData = BuildCallerInfo(MSG_ESIM_SEND_APUD_DATA);
1405     if (!ProcessSendApduData(slotId_, eventSendApduData)) {
1406         TELEPHONY_LOGE("ProcessSendApduData encode failed");
1407         return ResponseEsimResult();
1408     }
1409     isSendApduDataReady_ = false;
1410     std::unique_lock<std::mutex> lock(sendApduDataMutex_);
1411     if (!sendApduDataCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
1412         [this]() { return isSendApduDataReady_; })) {
1413         SyncCloseChannel();
1414         return ResponseEsimResult();
1415     }
1416     return transApduDataResponse_;
1417 }
1418 
ProcessResetMemory(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)1419 bool EsimFile::ProcessResetMemory(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
1420 {
1421     if (!IsLogicChannelOpen()) {
1422         return false;
1423     }
1424     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_EUICC_MEMORY_RESET);
1425     if (builder == nullptr) {
1426         TELEPHONY_LOGE("get builder failed");
1427         return false;
1428     }
1429     std::vector<uint8_t> resetMemoryTags;
1430     resetMemoryTags.push_back(static_cast<uint8_t>(EUICC_MEMORY_RESET_BIT_STR_FILL_LEN));
1431     resetMemoryTags.push_back(static_cast<uint8_t>(EUICC_MEMORY_RESET_BIT_STR_VALUE));
1432     builder->Asn1AddChildAsBytes(TAG_ESIM_CTX_2, resetMemoryTags, resetMemoryTags.size());
1433     ApduSimIORequestInfo reqInfo;
1434     CommBuildOneApduReqInfo(reqInfo, builder);
1435     if (telRilManager_ == nullptr) {
1436         return false;
1437     }
1438     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
1439     if (apduResult == TELEPHONY_ERR_FAIL) {
1440         return false;
1441     }
1442     return true;
1443 }
1444 
ProcessResetMemoryDone(const AppExecFwk::InnerEvent::Pointer &event)1445 bool EsimFile::ProcessResetMemoryDone(const AppExecFwk::InnerEvent::Pointer &event)
1446 {
1447     std::shared_ptr<Asn1Node> root = ParseEvent(event);
1448     if (root == nullptr) {
1449         TELEPHONY_LOGE("Asn1ParseResponse failed");
1450         return false;
1451     }
1452     std::shared_ptr<Asn1Node> asn1NodeData = root->Asn1GetChild(TAG_ESIM_CTX_0);
1453     if (asn1NodeData == nullptr) {
1454         TELEPHONY_LOGE("asn1NodeData is nullptr");
1455         return false;
1456     }
1457     resetResult_ = static_cast<ResultState>(asn1NodeData->Asn1AsInteger());
1458     {
1459         std::lock_guard<std::mutex> lock(resetMemoryMutex_);
1460         isResetMemoryReady_ = true;
1461     }
1462     resetMemoryCv_.notify_one();
1463     return true;
1464 }
1465 
ProcessSendApduData(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)1466 bool EsimFile::ProcessSendApduData(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
1467 {
1468     if (!IsLogicChannelOpen()) {
1469         return false;
1470     }
1471     std::string hexStr = OHOS::Telephony::ToUtf8(esimProfile_.apduData.data_);
1472     RequestApduBuild codec(currentChannelId_);
1473     codec.BuildStoreData(hexStr);
1474     std::list<std::unique_ptr<ApduCommand>> list = codec.GetCommands();
1475     if (list.empty()) {
1476         TELEPHONY_LOGE("node is empty");
1477         return false;
1478     }
1479     std::unique_ptr<ApduCommand> apdCmd = std::move(list.front());
1480     if (apdCmd == nullptr) {
1481         return false;
1482     }
1483     ApduSimIORequestInfo reqInfo;
1484     CopyApdCmdToReqInfo(&reqInfo, apdCmd.get());
1485     if (esimProfile_.apduData.unusedDefaultReqHeadFlag_) {
1486         reqInfo.type = esimProfile_.apduData.instructionType_;
1487         reqInfo.instruction = esimProfile_.apduData.instruction_;
1488         reqInfo.p1 = esimProfile_.apduData.p1_;
1489         reqInfo.p2 = esimProfile_.apduData.p2_;
1490         reqInfo.p3 = esimProfile_.apduData.p3_;
1491     }
1492     if (telRilManager_ == nullptr) {
1493         return false;
1494     }
1495     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
1496     if (apduResult == TELEPHONY_ERR_FAIL) {
1497         return false;
1498     }
1499     return true;
1500 }
1501 
ProcessSendApduDataDone(const AppExecFwk::InnerEvent::Pointer &event)1502 bool EsimFile::ProcessSendApduDataDone(const AppExecFwk::InnerEvent::Pointer &event)
1503 {
1504     if (event == nullptr) {
1505         TELEPHONY_LOGE("event is nullptr");
1506         return false;
1507     }
1508     std::unique_ptr<IccFromRilMsg> rcvMsg = event->GetUniqueObject<IccFromRilMsg>();
1509     if (rcvMsg == nullptr) {
1510         TELEPHONY_LOGE("rcvMsg is nullptr");
1511         return false;
1512     }
1513     IccFileData *result = &(rcvMsg->fileData);
1514     if (result == nullptr) {
1515         return false;
1516     }
1517     transApduDataResponse_.resultCode_ = ResultState::RESULT_OK;
1518     transApduDataResponse_.response_ = OHOS::Telephony::ToUtf16(result->resultData);
1519     transApduDataResponse_.sw1_ = result->sw1;
1520     transApduDataResponse_.sw2_ = result->sw2;
1521 
1522     {
1523         std::lock_guard<std::mutex> lock(sendApduDataMutex_);
1524         isSendApduDataReady_ = true;
1525     }
1526     sendApduDataCv_.notify_one();
1527     return true;
1528 }
1529 
ObtainPrepareDownload(const DownLoadConfigInfo &downLoadConfigInfo)1530 ResponseEsimResult EsimFile::ObtainPrepareDownload(const DownLoadConfigInfo &downLoadConfigInfo)
1531 {
1532     esimProfile_.portIndex = downLoadConfigInfo.portIndex_;
1533     esimProfile_.hashCc = downLoadConfigInfo.hashCc_;
1534     esimProfile_.smdpSigned2 = downLoadConfigInfo.smdpSigned2_;
1535     esimProfile_.smdpSignature2 = downLoadConfigInfo.smdpSignature2_;
1536     esimProfile_.smdpCertificate = downLoadConfigInfo.smdpCertificate_;
1537     SyncOpenChannel();
1538     recvCombineStr_ = "";
1539     if (!ProcessPrepareDownload(slotId_)) {
1540         TELEPHONY_LOGE("ProcessPrepareDownload encode failed");
1541         return ResponseEsimResult();
1542     }
1543     isPrepareDownloadReady_ = false;
1544     std::unique_lock<std::mutex> lock(prepareDownloadMutex_);
1545     if (!prepareDownloadCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
1546         [this]() { return isPrepareDownloadReady_; })) {
1547         SyncCloseChannel();
1548         return ResponseEsimResult();
1549     }
1550     SyncCloseChannel();
1551     return preDownloadResult_;
1552 }
1553 
ObtainLoadBoundProfilePackage(int32_t portIndex, const std::u16string boundProfilePackage)1554 ResponseEsimBppResult EsimFile::ObtainLoadBoundProfilePackage(int32_t portIndex,
1555     const std::u16string boundProfilePackage)
1556 {
1557     esimProfile_.portIndex = portIndex;
1558     esimProfile_.boundProfilePackage = boundProfilePackage;
1559     SyncOpenChannel();
1560     recvCombineStr_ = "";
1561     if (!ProcessLoadBoundProfilePackage(slotId_)) {
1562         TELEPHONY_LOGE("ProcessLoadBoundProfilePackage encode failed");
1563         return ResponseEsimBppResult();
1564     }
1565     isLoadBppReady_ = false;
1566     std::unique_lock<std::mutex> lock(loadBppMutex_);
1567     if (!loadBppCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
1568         [this]() { return isLoadBppReady_; })) {
1569         SyncCloseChannel();
1570         return ResponseEsimBppResult();
1571     }
1572     SyncCloseChannel();
1573     return loadBPPResult_;
1574 }
1575 
ListNotifications(int32_t portIndex, Event events)1576 EuiccNotificationList EsimFile::ListNotifications(int32_t portIndex, Event events)
1577 {
1578     esimProfile_.portIndex = portIndex;
1579     esimProfile_.events = events;
1580     AppExecFwk::InnerEvent::Pointer eventListNotif = BuildCallerInfo(MSG_ESIM_LIST_NOTIFICATION);
1581     SyncOpenChannel();
1582     recvCombineStr_ = "";
1583     if (!ProcessListNotifications(slotId_, events, eventListNotif)) {
1584         TELEPHONY_LOGE("ProcessListNotifications encode failed");
1585         return EuiccNotificationList();
1586     }
1587     isListNotificationsReady_ = false;
1588     std::unique_lock<std::mutex> lock(listNotificationsMutex_);
1589     if (!listNotificationsCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
1590         [this]() { return isListNotificationsReady_; })) {
1591         SyncCloseChannel();
1592         return EuiccNotificationList();
1593     }
1594     SyncCloseChannel();
1595     return eUiccNotificationList_;
1596 }
1597 
ConvertPreDownloadParaFromApiStru(PrepareDownloadResp& dst, EsimProfile& src)1598 void EsimFile::ConvertPreDownloadParaFromApiStru(PrepareDownloadResp& dst, EsimProfile& src)
1599 {
1600     dst.smdpSigned2 = OHOS::Telephony::ToUtf8(src.smdpSigned2);
1601     dst.smdpSignature2 = OHOS::Telephony::ToUtf8(src.smdpSignature2);
1602     dst.smdpCertificate = OHOS::Telephony::ToUtf8(src.smdpCertificate);
1603     dst.hashCc = OHOS::Telephony::ToUtf8(src.hashCc);
1604 }
1605 
Asn1AddChildAsBase64(std::shared_ptr<Asn1Builder> &builder, std::string &base64Src)1606 void EsimFile::Asn1AddChildAsBase64(std::shared_ptr<Asn1Builder> &builder, std::string &base64Src)
1607 {
1608     std::string destString = VCardUtils::DecodeBase64(base64Src);
1609     std::vector<uint8_t> dest = Asn1Utils::StringToBytes(destString);
1610     std::shared_ptr<Asn1Decoder> decoder = std::make_shared<Asn1Decoder>(dest, 0, dest.size());
1611     if (decoder == nullptr) {
1612         TELEPHONY_LOGE("create decoder failed");
1613         return;
1614     }
1615     std::shared_ptr<Asn1Node> node = decoder->Asn1NextNode();
1616     if (builder == nullptr) {
1617         TELEPHONY_LOGE("build is nullptr");
1618         return;
1619     }
1620     builder->Asn1AddChild(node);
1621 }
1622 
ProcessPrepareDownload(int32_t slotId)1623 bool EsimFile::ProcessPrepareDownload(int32_t slotId)
1624 {
1625     if (!IsLogicChannelOpen()) {
1626         return false;
1627     }
1628     PrepareDownloadResp dst;
1629     ConvertPreDownloadParaFromApiStru(dst, esimProfile_);
1630     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_PREPARE_DOWNLOAD);
1631     if (builder == nullptr) {
1632         return false;
1633     }
1634     Asn1AddChildAsBase64(builder, dst.smdpSigned2);
1635     Asn1AddChildAsBase64(builder, dst.smdpSignature2);
1636     if (dst.hashCc.size() != 0) {
1637         std::vector<uint8_t> bytes = Asn1Utils::StringToBytes(VCardUtils::DecodeBase64(dst.hashCc));
1638         builder->Asn1AddChildAsBytes(TAG_ESIM_OCTET_STRING_TYPE, bytes, bytes.size());
1639     }
1640     Asn1AddChildAsBase64(builder, dst.smdpCertificate);
1641     std::string hexStr;
1642     uint32_t hexStrLen = builder->Asn1BuilderToHexStr(hexStr);
1643     if (hexStrLen == 0) {
1644         return false;
1645     }
1646     SplitSendLongData(slotId, hexStr, MSG_ESIM_PREPARE_DOWNLOAD_DONE);
1647     return true;
1648 }
1649 
SplitSendLongData(int32_t slotId, std::string hexStr, int32_t esimMessageId)1650 void EsimFile::SplitSendLongData(int32_t slotId, std::string hexStr, int32_t esimMessageId)
1651 {
1652     RequestApduBuild codec(currentChannelId_);
1653     codec.BuildStoreData(hexStr);
1654     std::list<std::unique_ptr<ApduCommand>> apduCommandList = codec.GetCommands();
1655     for (const auto &cmd : apduCommandList) {
1656         ApduSimIORequestInfo reqInfo;
1657         CopyApdCmdToReqInfo(&reqInfo, cmd.get());
1658         AppExecFwk::InnerEvent::Pointer tmpResponseEvent = BuildCallerInfo(esimMessageId);
1659         if (telRilManager_ == nullptr) {
1660             return;
1661         }
1662         telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, tmpResponseEvent);
1663     }
1664 }
1665 
CombineResponseDataFinish(IccFileData &fileData)1666 bool EsimFile::CombineResponseDataFinish(IccFileData &fileData)
1667 {
1668     if (fileData.resultData.length() == 0) {
1669         return false;
1670     }
1671     recvCombineStr_ = recvCombineStr_ + fileData.resultData;
1672     return (fileData.sw1 == SW1_VALUE_90 && fileData.sw2 == SW2_VALUE_00);
1673 }
1674 
ProcessIfNeedMoreResponse(IccFileData &fileData, int32_t eventId)1675 void EsimFile::ProcessIfNeedMoreResponse(IccFileData &fileData, int32_t eventId)
1676 {
1677     if (fileData.sw1 == SW1_MORE_RESPONSE) {
1678         ApduSimIORequestInfo reqInfo;
1679         RequestApduBuild codec(currentChannelId_);
1680         codec.BuildStoreData("");
1681         std::list<std::unique_ptr<ApduCommand>> list = codec.GetCommands();
1682         if (list.empty()) {
1683             TELEPHONY_LOGE("node is empty");
1684             return;
1685         }
1686         std::unique_ptr<ApduCommand> apdCmd = std::move(list.front());
1687         if (apdCmd == nullptr) {
1688             return;
1689         }
1690         apdCmd->data.cla = 0;
1691         apdCmd->data.ins = INS_GET_MORE_RESPONSE;
1692         apdCmd->data.p1 = 0;
1693         apdCmd->data.p2 = 0;
1694         apdCmd->data.p3 = static_cast<uint32_t>(fileData.sw2);
1695         CopyApdCmdToReqInfo(&reqInfo, apdCmd.get());
1696         AppExecFwk::InnerEvent::Pointer responseEvent = BuildCallerInfo(eventId);
1697         if (telRilManager_ == nullptr) {
1698             return;
1699         }
1700         telRilManager_->SimTransmitApduLogicalChannel(slotId_, reqInfo, responseEvent);
1701     }
1702 }
1703 
MergeRecvLongDataComplete(IccFileData &fileData, int32_t eventId)1704 bool EsimFile::MergeRecvLongDataComplete(IccFileData &fileData, int32_t eventId)
1705 {
1706     if (!CombineResponseDataFinish(fileData)) {
1707         ProcessIfNeedMoreResponse(fileData, eventId);
1708         return false;
1709     }
1710     return true;
1711 }
1712 
ProcessPrepareDownloadDone(const AppExecFwk::InnerEvent::Pointer &event)1713 bool EsimFile::ProcessPrepareDownloadDone(const AppExecFwk::InnerEvent::Pointer &event)
1714 {
1715     if (event == nullptr) {
1716         TELEPHONY_LOGE("event is nullptr");
1717         return false;
1718     }
1719     std::unique_ptr<IccFromRilMsg> rcvMsg = event->GetUniqueObject<IccFromRilMsg>();
1720     if (rcvMsg == nullptr) {
1721         TELEPHONY_LOGE("rcvMsg is nullptr");
1722         return false;
1723     }
1724     IccFileData &iccFileData = rcvMsg->fileData;
1725     if (!MergeRecvLongDataComplete(iccFileData, MSG_ESIM_PREPARE_DOWNLOAD_DONE)) {
1726         return true;
1727     }
1728     std::vector<uint8_t> responseByte = Asn1Utils::HexStrToBytes(recvCombineStr_);
1729     uint32_t byteLen = responseByte.size();
1730     std::shared_ptr<Asn1Node> root = Asn1ParseResponse(responseByte, byteLen);
1731     if (root == nullptr) {
1732         TELEPHONY_LOGE("root is nullptr");
1733         return false;
1734     }
1735     std::shared_ptr<Asn1Node> childNode = root->Asn1GetChild(TAG_ESIM_CTX_COMP_1);
1736     if (childNode != nullptr) {
1737         std::shared_ptr<Asn1Node> errCodeNode = childNode->Asn1GetChild(TAG_ESIM_CTX_COMP_1);
1738         if (errCodeNode != nullptr) {
1739             int32_t protocolErr = errCodeNode->Asn1AsInteger();
1740             if (protocolErr != TELEPHONY_ERR_ARGUMENT_INVALID) {
1741                 TELEPHONY_LOGE("Prepare download error, es10x errcode: %{public}d", protocolErr);
1742                 return false;
1743             }
1744         }
1745     }
1746     preDownloadResult_.resultCode_ = ResultState::RESULT_OK;
1747     std::string responseByteStr = Asn1Utils::BytesToString(responseByte);
1748     std::string destString = VCardUtils::EncodeBase64(responseByteStr);
1749     preDownloadResult_.response_ = OHOS::Telephony::ToUtf16(destString);
1750     {
1751         std::lock_guard<std::mutex> lock(prepareDownloadMutex_);
1752         isPrepareDownloadReady_ = true;
1753     }
1754     prepareDownloadCv_.notify_one();
1755     return true;
1756 }
1757 
DecodeBoundProfilePackage(const std::string &boundProfilePackageStr, std::shared_ptr<Asn1Node> &bppNode)1758 bool EsimFile::DecodeBoundProfilePackage(const std::string &boundProfilePackageStr, std::shared_ptr<Asn1Node> &bppNode)
1759 {
1760     std::string destString = VCardUtils::DecodeBase64(boundProfilePackageStr);
1761     std::vector<uint8_t> dest = Asn1Utils::StringToBytes(destString);
1762     std::shared_ptr<Asn1Decoder> decoder = std::make_shared<Asn1Decoder>(dest, 0, dest.size());
1763     if (decoder == nullptr) {
1764         TELEPHONY_LOGE("decoder is nullptr");
1765         return false;
1766     }
1767     bppNode = decoder->Asn1NextNode();
1768     if (bppNode == nullptr) {
1769         TELEPHONY_LOGE("bppNode is nullptr");
1770         return false;
1771     }
1772     return true;
1773 }
1774 
BuildApduForInitSecureChannel( RequestApduBuild& codec, std::shared_ptr<Asn1Node> &bppNode, std::shared_ptr<Asn1Node> &initSecureChannelReq)1775 void EsimFile::BuildApduForInitSecureChannel(
1776     RequestApduBuild& codec, std::shared_ptr<Asn1Node> &bppNode, std::shared_ptr<Asn1Node> &initSecureChannelReq)
1777 {
1778     std::string hexStr;
1779     std::string destStr;
1780     uint32_t cursorLen = bppNode->Asn1GetHeadAsHexStr(hexStr);
1781     cursorLen += initSecureChannelReq->Asn1NodeToHexStr(destStr);
1782     hexStr += destStr;
1783     codec.BuildStoreData(hexStr);
1784 }
1785 
BuildApduForFirstSequenceOf87(RequestApduBuild &codec, std::shared_ptr<Asn1Node> &firstSequenceOf87)1786 void EsimFile::BuildApduForFirstSequenceOf87(RequestApduBuild &codec, std::shared_ptr<Asn1Node> &firstSequenceOf87)
1787 {
1788     std::string hexStr;
1789     uint32_t cursorLen = firstSequenceOf87->Asn1NodeToHexStr(hexStr);
1790     codec.BuildStoreData(hexStr);
1791 }
1792 
BuildApduForSequenceOf88(RequestApduBuild &codec, std::shared_ptr<Asn1Node> &sequenceOf88)1793 void EsimFile::BuildApduForSequenceOf88(RequestApduBuild &codec, std::shared_ptr<Asn1Node> &sequenceOf88)
1794 {
1795     std::list<std::shared_ptr<Asn1Node>> metaDataSeqs;
1796     int32_t metaDataRes = sequenceOf88->Asn1GetChildren(TAG_ESIM_CTX_8, metaDataSeqs);
1797     if (metaDataRes != 0) {
1798         return;
1799     }
1800     std::string hexStr;
1801     uint32_t cursorLen = sequenceOf88->Asn1GetHeadAsHexStr(hexStr);
1802     codec.BuildStoreData(hexStr);
1803     std::shared_ptr<Asn1Node> curNode = nullptr;
1804     for (auto it = metaDataSeqs.begin(); it != metaDataSeqs.end(); ++it) {
1805         curNode = *it;
1806         if (curNode == nullptr) {
1807             break;
1808         }
1809         curNode->Asn1NodeToHexStr(hexStr);
1810         codec.BuildStoreData(hexStr);
1811     }
1812 }
1813 
BuildApduForSequenceOf86(RequestApduBuild &codec, std::shared_ptr<Asn1Node> &bppNode, std::shared_ptr<Asn1Node> &sequenceOf86)1814 void EsimFile::BuildApduForSequenceOf86(RequestApduBuild &codec, std::shared_ptr<Asn1Node> &bppNode,
1815     std::shared_ptr<Asn1Node> &sequenceOf86)
1816 {
1817     std::string hexStr;
1818     std::list<std::shared_ptr<Asn1Node>> elementSeqs;
1819     int32_t elementRes = sequenceOf86->Asn1GetChildren(TAG_ESIM_CTX_6, elementSeqs);
1820     if (elementRes != 0) {
1821         TELEPHONY_LOGE("sequenceOf86 encode error");
1822         return;
1823     }
1824     if (bppNode->Asn1HasChild(TAG_ESIM_CTX_COMP_2)) {
1825         std::shared_ptr<Asn1Node> pGetChild = bppNode->Asn1GetChild(TAG_ESIM_CTX_COMP_2);
1826         if (pGetChild == nullptr) {
1827             TELEPHONY_LOGE("pGetChild is nullptr");
1828             return;
1829         }
1830         pGetChild->Asn1NodeToHexStr(hexStr);
1831         codec.BuildStoreData(hexStr);
1832     }
1833     uint32_t cursorLen = sequenceOf86->Asn1GetHeadAsHexStr(hexStr);
1834     codec.BuildStoreData(hexStr);
1835     std::shared_ptr<Asn1Node> curNode = nullptr;
1836     for (auto it = elementSeqs.begin(); it != elementSeqs.end(); ++it) {
1837         curNode = *it;
1838         if (curNode == nullptr) {
1839             break;
1840         }
1841         curNode->Asn1NodeToHexStr(hexStr);
1842         codec.BuildStoreData(hexStr);
1843     }
1844 }
1845 
ProcessLoadBoundProfilePackage(int32_t slotId)1846 bool EsimFile::ProcessLoadBoundProfilePackage(int32_t slotId)
1847 {
1848     if (!IsLogicChannelOpen()) {
1849         TELEPHONY_LOGE("open channel is failed");
1850         return false;
1851     }
1852     std::string boundProfilePackage = OHOS::Telephony::ToUtf8(esimProfile_.boundProfilePackage);
1853     std::shared_ptr<Asn1Node> bppNode = nullptr;
1854     if (!DecodeBoundProfilePackage(boundProfilePackage, bppNode)) {
1855         TELEPHONY_LOGE("DecodeBoundProfilePackage failed");
1856         return false;
1857     }
1858     RequestApduBuild codec(currentChannelId_);
1859     std::shared_ptr<Asn1Node> initSecureChannelReq = bppNode->Asn1GetChild(TAG_ESIM_INITIALISE_SECURE_CHANNEL);
1860     if (initSecureChannelReq != nullptr) {
1861         BuildApduForInitSecureChannel(codec, bppNode, initSecureChannelReq);
1862     }
1863     std::shared_ptr<Asn1Node> firstSequenceOf87 = bppNode->Asn1GetChild(TAG_ESIM_CTX_COMP_0);
1864     if (firstSequenceOf87 != nullptr) {
1865         BuildApduForFirstSequenceOf87(codec, firstSequenceOf87);
1866     }
1867     std::shared_ptr<Asn1Node> sequenceOf88 = bppNode->Asn1GetChild(TAG_ESIM_CTX_COMP_1);
1868     if (sequenceOf88 != nullptr) {
1869         BuildApduForSequenceOf88(codec, sequenceOf88);
1870     }
1871     std::shared_ptr<Asn1Node> sequenceOf86 = bppNode->Asn1GetChild(TAG_ESIM_CTX_COMP_3);
1872     if (sequenceOf86 != nullptr) {
1873         BuildApduForSequenceOf86(codec, bppNode, sequenceOf86);
1874     }
1875     std::list<std::unique_ptr<ApduCommand>> apduCommandList = codec.GetCommands();
1876     for (const auto &cmd : apduCommandList) {
1877         ApduSimIORequestInfo reqInfo;
1878         CopyApdCmdToReqInfo(&reqInfo, cmd.get());
1879         AppExecFwk::InnerEvent::Pointer responseEvent = BuildCallerInfo(MSG_ESIM_LOAD_BOUND_PROFILE_PACKAGE);
1880         if (telRilManager_ == nullptr) {
1881             return false;
1882         }
1883         int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
1884         if (apduResult == TELEPHONY_ERR_FAIL) {
1885             return false;
1886         }
1887     }
1888     return true;
1889 }
1890 
ProcessLoadBoundProfilePackageDone(const AppExecFwk::InnerEvent::Pointer &event)1891 bool EsimFile::ProcessLoadBoundProfilePackageDone(const AppExecFwk::InnerEvent::Pointer &event)
1892 {
1893     if (event == nullptr) {
1894         TELEPHONY_LOGE("event is nullptr");
1895         return false;
1896     }
1897     std::unique_ptr<IccFromRilMsg> rcvMsg = event->GetUniqueObject<IccFromRilMsg>();
1898     if (rcvMsg == nullptr) {
1899         TELEPHONY_LOGE("rcvMsg is nullptr");
1900         return false;
1901     }
1902     IccFileData &iccFileData = rcvMsg->fileData;
1903     if (!MergeRecvLongDataComplete(iccFileData, MSG_ESIM_LOAD_BOUND_PROFILE_PACKAGE)) {
1904         return true;
1905     }
1906     return RealProcessLoadBoundProfilePackageDone(recvCombineStr_);
1907 }
1908 
RealProcessLoadBoundProfilePackageDone(std::string combineHexStr)1909 bool EsimFile::RealProcessLoadBoundProfilePackageDone(std::string combineHexStr)
1910 {
1911     std::vector<uint8_t> responseByte = Asn1Utils::HexStrToBytes(combineHexStr);
1912     uint32_t byteLen = responseByte.size();
1913     loadBPPResult_.response_ = OHOS::Telephony::ToUtf16(combineHexStr);
1914     std::shared_ptr<Asn1Node> root = Asn1ParseResponse(responseByte, byteLen);
1915     if (root == nullptr) {
1916         TELEPHONY_LOGE("root is nullptr");
1917         return false;
1918     }
1919     std::shared_ptr<Asn1Node> nodeNotificationMetadata = LoadBoundProfilePackageParseProfileInstallResult(root);
1920     if (nodeNotificationMetadata == nullptr) {
1921         {
1922             std::lock_guard<std::mutex> lock(loadBppMutex_);
1923             isLoadBppReady_ = true;
1924         }
1925         loadBppCv_.notify_one();
1926         return false;
1927     }
1928     if (!LoadBoundProfilePackageParseNotificationMetadata(nodeNotificationMetadata)) {
1929         {
1930             std::lock_guard<std::mutex> lock(loadBppMutex_);
1931             isLoadBppReady_ = true;
1932         }
1933         loadBppCv_.notify_one();
1934         return false;
1935     }
1936     loadBPPResult_.resultCode_ = 0;
1937     {
1938         std::lock_guard<std::mutex> lock(loadBppMutex_);
1939         isLoadBppReady_ = true;
1940     }
1941     loadBppCv_.notify_one();
1942     return true;
1943 }
1944 
LoadBoundProfilePackageParseNotificationMetadata(std::shared_ptr<Asn1Node> &notificationMetadata)1945 bool EsimFile::LoadBoundProfilePackageParseNotificationMetadata(std::shared_ptr<Asn1Node> &notificationMetadata)
1946 {
1947     if (notificationMetadata == nullptr) {
1948         TELEPHONY_LOGE("notification metadata is empty");
1949         return false;
1950     }
1951     std::shared_ptr<Asn1Node> sequenceNumberAsn = notificationMetadata->Asn1GetChild(TAG_ESIM_CTX_0);
1952     if (sequenceNumberAsn != nullptr) {
1953         loadBPPResult_.seqNumber_ = sequenceNumberAsn->Asn1AsInteger();
1954     } else {
1955         TELEPHONY_LOGE("sequenceNumber tag missing");
1956         return false;
1957     }
1958     std::shared_ptr<Asn1Node> profileManagementOpAsn = notificationMetadata->Asn1GetChild(TAG_ESIM_CTX_1);
1959     if (profileManagementOpAsn != nullptr) {
1960         loadBPPResult_.profileManagementOperation_ = EVENT_INSTALL;
1961     } else {
1962         TELEPHONY_LOGE("profileManagementOperation tag missing");
1963         return false;
1964     }
1965     std::shared_ptr<Asn1Node> addressAsn = notificationMetadata->Asn1GetChild(TAG_ESIM_TARGET_ADDR);
1966     if (addressAsn != nullptr) {
1967         std::string hexString;
1968         addressAsn->Asn1AsString(hexString);
1969         std::string address = Asn1Utils::HexStrToString(hexString);
1970         loadBPPResult_.notificationAddress_ = OHOS::Telephony::ToUtf16(address);
1971     } else {
1972         TELEPHONY_LOGE("notificationAddress tag missing");
1973         return false;
1974     }
1975     std::shared_ptr<Asn1Node> iccidAsn = notificationMetadata->Asn1GetChild(TAG_ESIM_EID);
1976     if (iccidAsn == nullptr) {
1977         TELEPHONY_LOGE("iccidAsn is nullptr");
1978         return false;
1979     }
1980     std::vector<uint8_t> iccid;
1981     std::string iccString;
1982     uint32_t iccidLen = iccidAsn->Asn1AsBytes(iccid);
1983     Asn1Utils::BchToString(iccid, iccString);
1984     loadBPPResult_.iccId_ = OHOS::Telephony::ToUtf16(iccString);
1985     return true;
1986 }
1987 
LoadBoundProfilePackageParseProfileInstallResult(std::shared_ptr<Asn1Node> &root)1988 std::shared_ptr<Asn1Node> EsimFile::LoadBoundProfilePackageParseProfileInstallResult(std::shared_ptr<Asn1Node> &root)
1989 {
1990     if (root == nullptr) {
1991         TELEPHONY_LOGE("failed to parse load BPP file response");
1992         return nullptr;
1993     }
1994     std::shared_ptr<Asn1Node> resultData = root->Asn1GetChild(TAG_ESIM_PROFILE_INSTALLATION_RESULT_DATA);
1995     if (resultData == nullptr) {
1996         TELEPHONY_LOGE("failed to find ProfileInstallationResult tag");
1997         return nullptr;
1998     }
1999     std::shared_ptr<Asn1Node> errNode = resultData->Asn1GetGreatGrandson(TAG_ESIM_CTX_COMP_2,
2000         TAG_ESIM_CTX_COMP_1, TAG_ESIM_CTX_1);
2001     if (errNode != nullptr) {
2002         loadBPPResult_.resultCode_ = errNode->Asn1AsInteger();
2003         return nullptr;
2004     }
2005     std::shared_ptr<Asn1Node> notificationMetadataAsn = resultData->Asn1GetChild(TAG_ESIM_NOTIFICATION_METADATA);
2006     if (notificationMetadataAsn == nullptr) {
2007         TELEPHONY_LOGE("extProfileInstallRsp: failed to find finalResult tag");
2008         return nullptr;
2009     }
2010     return notificationMetadataAsn;
2011 }
2012 
ProcessListNotifications( int32_t slotId, Event events, const AppExecFwk::InnerEvent::Pointer &responseEvent)2013 bool EsimFile::ProcessListNotifications(
2014     int32_t slotId, Event events, const AppExecFwk::InnerEvent::Pointer &responseEvent)
2015 {
2016     if (!IsLogicChannelOpen()) {
2017         return false;
2018     }
2019     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_LIST_NOTIFICATION);
2020     if (builder == nullptr) {
2021         TELEPHONY_LOGE("builder is nullptr");
2022         return false;
2023     }
2024     builder->Asn1AddChildAsBits(TAG_ESIM_CTX_1, static_cast<int32_t>(events));
2025     ApduSimIORequestInfo reqInfo;
2026     CommBuildOneApduReqInfo(reqInfo, builder);
2027     if (telRilManager_ == nullptr) {
2028         return false;
2029     }
2030     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
2031     if (apduResult == TELEPHONY_ERR_FAIL) {
2032         return false;
2033     }
2034     return true;
2035 }
2036 
createNotification(std::shared_ptr<Asn1Node> &node, EuiccNotification &euicc)2037 void EsimFile::createNotification(std::shared_ptr<Asn1Node> &node, EuiccNotification &euicc)
2038 {
2039     if (node == nullptr) {
2040         TELEPHONY_LOGE("createNotification node is nullptr");
2041         return;
2042     }
2043     std::shared_ptr<Asn1Node> metadataNode;
2044     if (node->GetNodeTag() == TAG_ESIM_NOTIFICATION_METADATA) {
2045         metadataNode = node;
2046     } else if (node->GetNodeTag() == TAG_ESIM_PROFILE_INSTALLATION_RESULT) {
2047         std::shared_ptr<Asn1Node> findNode =
2048             node->Asn1GetGrandson(TAG_ESIM_PROFILE_INSTALLATION_RESULT_DATA,
2049             TAG_ESIM_NOTIFICATION_METADATA);
2050         metadataNode = findNode;
2051     } else {
2052         // Other signed notification
2053         std::shared_ptr<Asn1Node> findNode = node->Asn1GetChild(TAG_ESIM_NOTIFICATION_METADATA);
2054         metadataNode = findNode;
2055     }
2056     if (metadataNode == nullptr) {
2057         TELEPHONY_LOGE("metadataNode is nullptr");
2058         return;
2059     }
2060     std::shared_ptr<Asn1Node> nodeSeq = metadataNode->Asn1GetChild(TAG_ESIM_SEQ);
2061     if (nodeSeq == nullptr) {
2062         TELEPHONY_LOGE("nodeSeq is nullptr");
2063         return;
2064     }
2065     euicc.seq_ = nodeSeq->Asn1AsInteger();
2066 
2067     std::shared_ptr<Asn1Node> nodeTargetAddr = metadataNode->Asn1GetChild(TAG_ESIM_TARGET_ADDR);
2068     if (nodeTargetAddr == nullptr) {
2069         TELEPHONY_LOGE("nodeTargetAddr is nullptr");
2070         return;
2071     }
2072     std::vector<uint8_t> resultStr;
2073     nodeTargetAddr->Asn1AsBytes(resultStr);
2074     euicc.targetAddr_ = OHOS::Telephony::ToUtf16(Asn1Utils::BytesToString(resultStr));
2075 
2076     std::shared_ptr<Asn1Node> nodeEvent = metadataNode->Asn1GetChild(TAG_ESIM_EVENT);
2077     if (nodeEvent == nullptr) {
2078         TELEPHONY_LOGE("nodeEvent is nullptr");
2079         return;
2080     }
2081     euicc.event_ = nodeEvent->Asn1AsBits();
2082 
2083     std::string strmData;
2084     node->Asn1NodeToHexStr(strmData);
2085     euicc.data_ = Str8ToStr16(strmData);
2086 }
2087 
ProcessListNotificationsAsn1Response(std::shared_ptr<Asn1Node> &root)2088 bool EsimFile::ProcessListNotificationsAsn1Response(std::shared_ptr<Asn1Node> &root)
2089 {
2090     if (root->Asn1HasChild(TAG_ESIM_CTX_1)) {
2091         TELEPHONY_LOGE("child is nullptr");
2092         return false;
2093     }
2094     std::list<std::shared_ptr<Asn1Node>> ls;
2095     std::shared_ptr<Asn1Node> compTag = root->Asn1GetChild(TAG_ESIM_CTX_COMP_0);
2096     if (compTag == nullptr) {
2097         TELEPHONY_LOGE("compTag is nullptr");
2098         return false;
2099     }
2100     int32_t metaDataRes = compTag->Asn1GetChildren(TAG_ESIM_NOTIFICATION_METADATA, ls);
2101     if (metaDataRes != 0) {
2102         TELEPHONY_LOGE("metaDataTag is zero");
2103         return false;
2104     }
2105     std::shared_ptr<Asn1Node> curNode = nullptr;
2106     EuiccNotificationList euiccList;
2107     for (auto it = ls.begin(); it != ls.end(); ++it) {
2108         curNode = *it;
2109         EuiccNotification euicc;
2110         createNotification(curNode, euicc);
2111         euiccList.euiccNotification_.push_back(euicc);
2112     }
2113     eUiccNotificationList_ = euiccList;
2114     {
2115         std::lock_guard<std::mutex> lock(listNotificationsMutex_);
2116         isListNotificationsReady_ = true;
2117     }
2118     listNotificationsCv_.notify_one();
2119     return true;
2120 }
2121 
ProcessListNotificationsDone(const AppExecFwk::InnerEvent::Pointer &event)2122 bool EsimFile::ProcessListNotificationsDone(const AppExecFwk::InnerEvent::Pointer &event)
2123 {
2124     if (event == nullptr) {
2125         TELEPHONY_LOGE("event is nullptr!");
2126         return false;
2127     }
2128     std::unique_ptr<IccFromRilMsg> rcvMsg = event->GetUniqueObject<IccFromRilMsg>();
2129     if (rcvMsg == nullptr) {
2130         TELEPHONY_LOGE("rcvMsg is nullptr");
2131         return false;
2132     }
2133     if (!MergeRecvLongDataComplete(rcvMsg->fileData, MSG_ESIM_LIST_NOTIFICATION)) {
2134         return true;
2135     }
2136     std::vector<uint8_t> responseByte = Asn1Utils::HexStrToBytes(recvCombineStr_);
2137     uint32_t byteLen = responseByte.size();
2138     std::shared_ptr<Asn1Node> root = Asn1ParseResponse(responseByte, byteLen);
2139     if (root == nullptr) {
2140         TELEPHONY_LOGE("root is nullptr");
2141         return false;
2142     }
2143     if (!ProcessListNotificationsAsn1Response(root)) {
2144         return false;
2145     }
2146     return true;
2147 }
2148 
RetrieveNotificationList(int32_t portIndex, Event events)2149 EuiccNotificationList EsimFile::RetrieveNotificationList(int32_t portIndex, Event events)
2150 {
2151     esimProfile_.portIndex = portIndex;
2152     esimProfile_.events = events;
2153     SyncOpenChannel();
2154     recvCombineStr_ = "";
2155     AppExecFwk::InnerEvent::Pointer eventRetrieveListNotif = BuildCallerInfo(MSG_ESIM_RETRIEVE_NOTIFICATION_LIST);
2156     if (!ProcessRetrieveNotificationList(slotId_, events, eventRetrieveListNotif)) {
2157         TELEPHONY_LOGE("ProcessRetrieveNotificationList encode failed");
2158         return EuiccNotificationList();
2159     }
2160     isRetrieveNotificationListReady_ = false;
2161     std::unique_lock<std::mutex> lock(retrieveNotificationListMutex_);
2162     if (!retrieveNotificationListCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
2163         [this]() { return isRetrieveNotificationListReady_; })) {
2164         SyncCloseChannel();
2165         return EuiccNotificationList();
2166     }
2167     SyncCloseChannel();
2168     return retrieveNotificationList_;
2169 }
2170 
ObtainRetrieveNotification(int32_t portIndex, int32_t seqNumber)2171 EuiccNotification EsimFile::ObtainRetrieveNotification(int32_t portIndex, int32_t seqNumber)
2172 {
2173     esimProfile_.portIndex = portIndex;
2174     esimProfile_.seqNumber = seqNumber;
2175     SyncOpenChannel();
2176     recvCombineStr_ = "";
2177     AppExecFwk::InnerEvent::Pointer eventRetrieveNotification = BuildCallerInfo(MSG_ESIM_RETRIEVE_NOTIFICATION_DONE);
2178     if (!ProcessRetrieveNotification(slotId_, eventRetrieveNotification)) {
2179         TELEPHONY_LOGE("ProcessRetrieveNotification encode failed");
2180         return EuiccNotification();
2181     }
2182     isRetrieveNotificationReady_ = false;
2183     std::unique_lock<std::mutex> lock(retrieveNotificationMutex_);
2184     if (!retrieveNotificationCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
2185         [this]() { return isRetrieveNotificationReady_; })) {
2186         SyncCloseChannel();
2187         return EuiccNotification();
2188     }
2189     SyncCloseChannel();
2190     return notification_;
2191 }
2192 
RemoveNotificationFromList(int32_t portIndex, int32_t seqNumber)2193 ResultState EsimFile::RemoveNotificationFromList(int32_t portIndex, int32_t seqNumber)
2194 {
2195     esimProfile_.portIndex = portIndex;
2196     esimProfile_.seqNumber = seqNumber;
2197     SyncOpenChannel();
2198     AppExecFwk::InnerEvent::Pointer eventRemoveNotif = BuildCallerInfo(MSG_ESIM_REMOVE_NOTIFICATION);
2199     if (!ProcessRemoveNotification(slotId_, eventRemoveNotif)) {
2200         TELEPHONY_LOGE("ProcessRemoveNotification encode failed");
2201         return ResultState();
2202     }
2203     isRemoveNotificationReady_ = false;
2204     std::unique_lock<std::mutex> lock(removeNotificationMutex_);
2205     if (!removeNotificationCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
2206         [this]() { return isRemoveNotificationReady_; })) {
2207         SyncCloseChannel();
2208         return ResultState();
2209     }
2210     SyncCloseChannel();
2211     return removeNotifResult_;
2212 }
2213 
ProcessRetrieveNotificationList( int32_t slotId, Event events, const AppExecFwk::InnerEvent::Pointer &responseEvent)2214 bool EsimFile::ProcessRetrieveNotificationList(
2215     int32_t slotId, Event events, const AppExecFwk::InnerEvent::Pointer &responseEvent)
2216 {
2217     if (!IsLogicChannelOpen()) {
2218         return false;
2219     }
2220     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_RETRIEVE_NOTIFICATIONS_LIST);
2221     if (builder == nullptr) {
2222         TELEPHONY_LOGE("builder is nullptr!");
2223         return false;
2224     }
2225     std::shared_ptr<Asn1Builder> compBuilder = std::make_shared<Asn1Builder>(TAG_ESIM_CTX_COMP_0);
2226     if (compBuilder == nullptr) {
2227         TELEPHONY_LOGE("compBuilder is nullptr!");
2228         return false;
2229     }
2230     compBuilder->Asn1AddChildAsBits(TAG_ESIM_CTX_1, static_cast<int32_t>(events));
2231     std::shared_ptr<Asn1Node> compNode = compBuilder->Asn1Build();
2232     builder->Asn1AddChild(compNode);
2233     ApduSimIORequestInfo reqInfo;
2234     CommBuildOneApduReqInfo(reqInfo, builder);
2235     if (telRilManager_ == nullptr) {
2236         TELEPHONY_LOGE("telRilManager_ is nullptr");
2237         return false;
2238     }
2239     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
2240     if (apduResult == TELEPHONY_ERR_FAIL) {
2241         return false;
2242     }
2243     return true;
2244 }
2245 
ProcessRetrieveNotificationListDone(const AppExecFwk::InnerEvent::Pointer &event)2246 bool EsimFile::ProcessRetrieveNotificationListDone(const AppExecFwk::InnerEvent::Pointer &event)
2247 {
2248     if (event == nullptr) {
2249         TELEPHONY_LOGE("event is nullptr");
2250         return false;
2251     }
2252     std::shared_ptr<Asn1Node> root = ParseEvent(event);
2253     if (root == nullptr) {
2254         TELEPHONY_LOGE("root is nullptr");
2255         return false;
2256     }
2257     if (!RetrieveNotificationParseCompTag(root)) {
2258         TELEPHONY_LOGE("RetrieveNotificationParseCompTag error");
2259         return false;
2260     }
2261 
2262     {
2263         std::lock_guard<std::mutex> lock(retrieveNotificationListMutex_);
2264         isRetrieveNotificationListReady_ = true;
2265     }
2266     retrieveNotificationListCv_.notify_one();
2267     return true;
2268 }
2269 
RetrieveNotificationParseCompTag(std::shared_ptr<Asn1Node> &root)2270 bool EsimFile::RetrieveNotificationParseCompTag(std::shared_ptr<Asn1Node> &root)
2271 {
2272     std::list<std::shared_ptr<Asn1Node>> ls;
2273     std::shared_ptr<Asn1Node> compTag = root->Asn1GetChild(TAG_ESIM_CTX_COMP_0);
2274     if (compTag == nullptr) {
2275         TELEPHONY_LOGE("compTag is nullptr");
2276         return false;
2277     }
2278     int32_t metaDataRes = compTag->Asn1GetChildren(TAG_ESIM_SEQUENCE, ls);
2279     if (metaDataRes != 0) {
2280         TELEPHONY_LOGE("metaDataTag is zero");
2281         return false;
2282     }
2283     std::shared_ptr<Asn1Node> curNode = nullptr;
2284     EuiccNotificationList euiccList;
2285     for (auto it = ls.begin(); it != ls.end(); ++it) {
2286         curNode = *it;
2287         EuiccNotification euicc;
2288         createNotification(curNode, euicc);
2289         euiccList.euiccNotification_.push_back(euicc);
2290     }
2291     eUiccNotificationList_ = euiccList;
2292     return true;
2293 }
2294 
ProcessRetrieveNotification(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)2295 bool EsimFile::ProcessRetrieveNotification(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
2296 {
2297     if (!IsLogicChannelOpen()) {
2298         return false;
2299     }
2300     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_RETRIEVE_NOTIFICATIONS_LIST);
2301     std::shared_ptr<Asn1Builder> subBuilder = std::make_shared<Asn1Builder>(TAG_ESIM_CTX_COMP_0);
2302     if (builder == nullptr || subBuilder == nullptr) {
2303         TELEPHONY_LOGE("get builder failed");
2304         return false;
2305     }
2306     subBuilder->Asn1AddChildAsSignedInteger(TAG_ESIM_CTX_0, esimProfile_.seqNumber);
2307     std::shared_ptr<Asn1Node> subNode = subBuilder->Asn1Build();
2308     builder->Asn1AddChild(subNode);
2309     ApduSimIORequestInfo reqInfo;
2310     CommBuildOneApduReqInfo(reqInfo, builder);
2311     if (telRilManager_ == nullptr) {
2312         TELEPHONY_LOGE("telRilManager_ is nullptr");
2313         return false;
2314     }
2315     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
2316     if (apduResult == TELEPHONY_ERR_FAIL) {
2317         return false;
2318     }
2319     return true;
2320 }
2321 
ProcessRetrieveNotificationDone(const AppExecFwk::InnerEvent::Pointer &event)2322 bool EsimFile::ProcessRetrieveNotificationDone(const AppExecFwk::InnerEvent::Pointer &event)
2323 {
2324     ResetEuiccNotification();
2325     if (event == nullptr) {
2326         TELEPHONY_LOGE("event is nullptr");
2327         return false;
2328     }
2329     std::unique_ptr<IccFromRilMsg> rcvMsg = event->GetUniqueObject<IccFromRilMsg>();
2330     if (rcvMsg == nullptr) {
2331         TELEPHONY_LOGE("rcvMsg is nullptr");
2332         return false;
2333     }
2334     if (!MergeRecvLongDataComplete(rcvMsg->fileData, MSG_ESIM_RETRIEVE_NOTIFICATION_DONE)) {
2335         return true;
2336     }
2337     std::vector<uint8_t> responseByte = Asn1Utils::HexStrToBytes(recvCombineStr_);
2338     uint32_t byteLen = responseByte.size();
2339     std::shared_ptr<Asn1Node> root = Asn1ParseResponse(responseByte, byteLen);
2340     if (root == nullptr) {
2341         TELEPHONY_LOGE("root is nullptr");
2342         return false;
2343     }
2344     if (!RetrieveNotificatioParseTagCtxComp0(root)) {
2345         TELEPHONY_LOGE("RetrieveNotificatioParseTagCtxComp0 error");
2346         return false;
2347     }
2348 
2349     {
2350         std::lock_guard<std::mutex> lock(retrieveNotificationMutex_);
2351         isRetrieveNotificationReady_ = true;
2352     }
2353     retrieveNotificationCv_.notify_one();
2354     return true;
2355 }
2356 
RetrieveNotificatioParseTagCtxComp0(std::shared_ptr<Asn1Node> &root)2357 bool EsimFile::RetrieveNotificatioParseTagCtxComp0(std::shared_ptr<Asn1Node> &root)
2358 {
2359     std::list<std::shared_ptr<Asn1Node>> nodes;
2360     std::shared_ptr<Asn1Node> compNode = root->Asn1GetChild(TAG_ESIM_CTX_COMP_0);
2361     if (compNode == nullptr) {
2362         TELEPHONY_LOGE("compNode is nullptr");
2363         return false;
2364     }
2365 
2366     if (compNode->Asn1GetChildren(TAG_ESIM_SEQUENCE, nodes) != 0) {
2367         return false;
2368     }
2369     if (nodes.empty()) {
2370         TELEPHONY_LOGE("node is empty");
2371         return false;
2372     }
2373     EuiccNotification notification;
2374     std::shared_ptr<Asn1Node> firstNode = nodes.front();
2375     createNotification(firstNode, notification);
2376     notification_.seq_ = notification.seq_;
2377     notification_.targetAddr_ = notification.targetAddr_;
2378     notification_.event_ = notification.event_;
2379     notification_.data_ = notification.data_;
2380     return true;
2381 }
2382 
ProcessRemoveNotification(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)2383 bool EsimFile::ProcessRemoveNotification(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
2384 {
2385     if (!IsLogicChannelOpen()) {
2386         return false;
2387     }
2388     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_REMOVE_NOTIFICATION_FROM_LIST);
2389     if (builder == nullptr) {
2390         TELEPHONY_LOGE("builder is nullptr");
2391         return false;
2392     }
2393     builder->Asn1AddChildAsSignedInteger(TAG_ESIM_CTX_0, esimProfile_.seqNumber);
2394     ApduSimIORequestInfo reqInfo;
2395     CommBuildOneApduReqInfo(reqInfo, builder);
2396     if (telRilManager_ == nullptr) {
2397         TELEPHONY_LOGE("telRilManager is nullptr");
2398         return false;
2399     }
2400     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
2401     if (apduResult == TELEPHONY_ERR_FAIL) {
2402         return false;
2403     }
2404     return true;
2405 }
2406 
ProcessRemoveNotificationDone(const AppExecFwk::InnerEvent::Pointer &event)2407 bool EsimFile::ProcessRemoveNotificationDone(const AppExecFwk::InnerEvent::Pointer &event)
2408 {
2409     if (event == nullptr) {
2410         TELEPHONY_LOGE("event is nullptr!");
2411         return false;
2412     }
2413     std::shared_ptr<Asn1Node> root = ParseEvent(event);
2414     if (root == nullptr) {
2415         TELEPHONY_LOGE("Asn1ParseResponse failed");
2416         return false;
2417     }
2418     std::shared_ptr<Asn1Node> node = root->Asn1GetChild(TAG_ESIM_CTX_0);
2419     if (node == nullptr) {
2420         TELEPHONY_LOGE("node is nullptr");
2421         return false;
2422     }
2423     removeNotifResult_ = static_cast<ResultState>(node->Asn1AsInteger());
2424     {
2425         std::lock_guard<std::mutex> lock(removeNotificationMutex_);
2426         isRemoveNotificationReady_ = true;
2427     }
2428     removeNotificationCv_.notify_one();
2429     return true;
2430 }
2431 
DeleteProfile(const std::u16string &iccId)2432 ResultState EsimFile::DeleteProfile(const std::u16string &iccId)
2433 {
2434     esimProfile_.iccId = iccId;
2435     SyncOpenChannel();
2436     AppExecFwk::InnerEvent::Pointer eventDeleteProfile = BuildCallerInfo(MSG_ESIM_DELETE_PROFILE);
2437     if (!ProcessDeleteProfile(slotId_, eventDeleteProfile)) {
2438         TELEPHONY_LOGE("ProcessDeleteProfile encode failed");
2439         return ResultState();
2440     }
2441     isDeleteProfileReady_ = false;
2442     std::unique_lock<std::mutex> lock(deleteProfileMutex_);
2443     if (!deleteProfileCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
2444         [this]() { return isDeleteProfileReady_; })) {
2445         SyncCloseChannel();
2446         return ResultState();
2447     }
2448     SyncCloseChannel();
2449     return delProfile_;
2450 }
2451 
SwitchToProfile(int32_t portIndex, const std::u16string &iccId, bool forceDisableProfile)2452 ResultState EsimFile::SwitchToProfile(int32_t portIndex, const std::u16string &iccId, bool forceDisableProfile)
2453 {
2454     esimProfile_.portIndex = portIndex;
2455     esimProfile_.iccId = iccId;
2456     esimProfile_.forceDisableProfile = forceDisableProfile;
2457     SyncOpenChannel();
2458     AppExecFwk::InnerEvent::Pointer eventSwitchToProfile = BuildCallerInfo(MSG_ESIM_SWITCH_PROFILE);
2459     if (!ProcessSwitchToProfile(slotId_, eventSwitchToProfile)) {
2460         TELEPHONY_LOGE("ProcessSwitchToProfile encode failed");
2461         return ResultState();
2462     }
2463     isSwitchToProfileReady_ = false;
2464     std::unique_lock<std::mutex> lock(switchToProfileMutex_);
2465     if (!switchToProfileCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
2466         [this]() { return isSwitchToProfileReady_; })) {
2467         SyncCloseChannel();
2468         return ResultState();
2469     }
2470     SyncCloseChannel();
2471     return switchResult_;
2472 }
2473 
SetProfileNickname(const std::u16string &iccId, const std::u16string &nickname)2474 ResultState EsimFile::SetProfileNickname(const std::u16string &iccId, const std::u16string &nickname)
2475 {
2476     esimProfile_.iccId = iccId;
2477     esimProfile_.nickname = nickname;
2478     SyncOpenChannel();
2479     AppExecFwk::InnerEvent::Pointer eventSetNickName = BuildCallerInfo(MSG_ESIM_SET_NICK_NAME);
2480     if (!ProcessSetNickname(slotId_, eventSetNickName)) {
2481         TELEPHONY_LOGE("ProcessSetNickname encode failed");
2482         return ResultState();
2483     }
2484     isSetNicknameReady_ = false;
2485     std::unique_lock<std::mutex> lock(setNicknameMutex_);
2486     if (!setNicknameCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
2487         [this]() { return isSetNicknameReady_; })) {
2488         SyncCloseChannel();
2489         return ResultState();
2490     }
2491     SyncCloseChannel();
2492     return setNicknameResult_;
2493 }
2494 
ProcessDeleteProfile(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)2495 bool EsimFile::ProcessDeleteProfile(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
2496 {
2497     if (!IsLogicChannelOpen()) {
2498         return false;
2499     }
2500     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_DELETE_PROFILE);
2501     if (builder == nullptr) {
2502         TELEPHONY_LOGE("builder is nullptr");
2503         return false;
2504     }
2505     std::vector<uint8_t> iccidBytes;
2506     std::string strIccId = OHOS::Telephony::ToUtf8(esimProfile_.iccId);
2507     Asn1Utils::BcdToBytes(strIccId, iccidBytes);
2508     builder->Asn1AddChildAsBytes(TAG_ESIM_ICCID, iccidBytes, iccidBytes.size());
2509     ApduSimIORequestInfo reqInfo;
2510     CommBuildOneApduReqInfo(reqInfo, builder);
2511     if (telRilManager_ == nullptr) {
2512         return false;
2513     }
2514     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
2515     if (apduResult == TELEPHONY_ERR_FAIL) {
2516         return false;
2517     }
2518     return true;
2519 }
2520 
ProcessSetNickname(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)2521 bool EsimFile::ProcessSetNickname(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
2522 {
2523     if (!IsLogicChannelOpen()) {
2524         return false;
2525     }
2526     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_SET_NICKNAME);
2527     if (builder == nullptr) {
2528         TELEPHONY_LOGE("builder is nullptr");
2529         return false;
2530     }
2531     std::vector<uint8_t> iccidBytes;
2532     std::string strIccId = OHOS::Telephony::ToUtf8(esimProfile_.iccId);
2533     std::string childStr = OHOS::Telephony::ToUtf8(esimProfile_.nickname);
2534     Asn1Utils::BcdToBytes(strIccId, iccidBytes);
2535 
2536     builder->Asn1AddChildAsBytes(TAG_ESIM_ICCID, iccidBytes, iccidBytes.size());
2537     builder->Asn1AddChildAsString(TAG_ESIM_NICKNAME, childStr);
2538     ApduSimIORequestInfo reqInfo;
2539     CommBuildOneApduReqInfo(reqInfo, builder);
2540     if (telRilManager_ == nullptr) {
2541         return false;
2542     }
2543     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
2544     if (apduResult == TELEPHONY_ERR_FAIL) {
2545         return false;
2546     }
2547     return true;
2548 }
2549 
ProcessDeleteProfileDone(const AppExecFwk::InnerEvent::Pointer &event)2550 bool EsimFile::ProcessDeleteProfileDone(const AppExecFwk::InnerEvent::Pointer &event)
2551 {
2552     std::shared_ptr<Asn1Node> root = ParseEvent(event);
2553     if (root == nullptr) {
2554         TELEPHONY_LOGE("Asn1ParseResponse failed");
2555         return false;
2556     }
2557     std::shared_ptr<Asn1Node> Asn1NodeData = root->Asn1GetChild(TAG_ESIM_CTX_0);
2558     if (Asn1NodeData == nullptr) {
2559         TELEPHONY_LOGE("pAsn1Node is nullptr");
2560         return false;
2561     }
2562     delProfile_ = static_cast<ResultState>(Asn1NodeData->Asn1AsInteger());
2563     {
2564         std::lock_guard<std::mutex> lock(deleteProfileMutex_);
2565         isDeleteProfileReady_ = true;
2566     }
2567     deleteProfileCv_.notify_one();
2568     return true;
2569 }
2570 
ProcessSwitchToProfile(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)2571 bool EsimFile::ProcessSwitchToProfile(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
2572 {
2573     if (!IsLogicChannelOpen()) {
2574         return false;
2575     }
2576     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_ENABLE_PROFILE);
2577     std::shared_ptr<Asn1Builder> subBuilder = std::make_shared<Asn1Builder>(TAG_ESIM_CTX_COMP_0);
2578     if (builder == nullptr || subBuilder == nullptr) {
2579         TELEPHONY_LOGE("get builder failed");
2580         return false;
2581     }
2582     std::vector<uint8_t> iccidBytes;
2583     std::string strIccId = OHOS::Telephony::ToUtf8(esimProfile_.iccId);
2584     Asn1Utils::BcdToBytes(strIccId, iccidBytes);
2585     subBuilder->Asn1AddChildAsBytes(TAG_ESIM_ICCID, iccidBytes, iccidBytes.size());
2586     std::shared_ptr<Asn1Node> subNode = subBuilder->Asn1Build();
2587     if (subNode == nullptr) {
2588         TELEPHONY_LOGE("subNode is nullptr");
2589         return false;
2590     }
2591     builder->Asn1AddChild(subNode);
2592     builder->Asn1AddChildAsBoolean(TAG_ESIM_CTX_1, true);
2593     ApduSimIORequestInfo reqInfo;
2594     CommBuildOneApduReqInfo(reqInfo, builder);
2595     if (telRilManager_ == nullptr) {
2596         return false;
2597     }
2598     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
2599     if (apduResult == TELEPHONY_ERR_FAIL) {
2600         return false;
2601     }
2602     return true;
2603 }
2604 
ProcessSwitchToProfileDone(const AppExecFwk::InnerEvent::Pointer &event)2605 bool EsimFile::ProcessSwitchToProfileDone(const AppExecFwk::InnerEvent::Pointer &event)
2606 {
2607     std::shared_ptr<Asn1Node> root = ParseEvent(event);
2608     if (root == nullptr) {
2609         TELEPHONY_LOGE("Asn1ParseResponse failed");
2610         return false;
2611     }
2612     std::shared_ptr<Asn1Node> asn1NodeData = root->Asn1GetChild(TAG_ESIM_CTX_0);
2613     if (asn1NodeData == nullptr) {
2614         TELEPHONY_LOGE("asn1NodeData is nullptr");
2615         return false;
2616     }
2617     switchResult_ = static_cast<ResultState>(asn1NodeData->Asn1AsInteger());
2618 
2619     {
2620         std::lock_guard<std::mutex> lock(switchToProfileMutex_);
2621         isSwitchToProfileReady_ = true;
2622     }
2623     switchToProfileCv_.notify_one();
2624     return true;
2625 }
2626 
ProcessSetNicknameDone(const AppExecFwk::InnerEvent::Pointer &event)2627 bool EsimFile::ProcessSetNicknameDone(const AppExecFwk::InnerEvent::Pointer &event)
2628 {
2629     std::shared_ptr<Asn1Node> root = ParseEvent(event);
2630     if (root == nullptr) {
2631         TELEPHONY_LOGE("Asn1ParseResponse failed");
2632         return false;
2633     }
2634     std::shared_ptr<Asn1Node> asn1NodeData = root->Asn1GetChild(TAG_ESIM_CTX_0);
2635     if (asn1NodeData == nullptr) {
2636         TELEPHONY_LOGE("asn1NodeData is nullptr");
2637         return false;
2638     }
2639     setNicknameResult_ = static_cast<ResultState>(asn1NodeData->Asn1AsInteger());
2640     {
2641         std::lock_guard<std::mutex> lock(setNicknameMutex_);
2642         isSetNicknameReady_ = true;
2643     }
2644     setNicknameCv_.notify_one();
2645     return true;
2646 }
2647 
ObtainEuiccInfo2(int32_t portIndex)2648 EuiccInfo2 EsimFile::ObtainEuiccInfo2(int32_t portIndex)
2649 {
2650     esimProfile_.portIndex = portIndex;
2651     SyncOpenChannel();
2652     AppExecFwk::InnerEvent::Pointer eventEUICCInfo2 = BuildCallerInfo(MSG_ESIM_OBTAIN_EUICC_INFO2_DONE);
2653     if (!ProcessObtainEuiccInfo2(slotId_, eventEUICCInfo2)) {
2654         TELEPHONY_LOGE("ProcessObtainEuiccInfo2 encode failed");
2655         return EuiccInfo2();
2656     }
2657     isEuiccInfo2Ready_ = false;
2658     std::unique_lock<std::mutex> lock(euiccInfo2Mutex_);
2659     if (!euiccInfo2Cv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
2660         [this]() { return isEuiccInfo2Ready_; })) {
2661         SyncCloseChannel();
2662         return EuiccInfo2();
2663     }
2664     SyncCloseChannel();
2665     return euiccInfo2Result_;
2666 }
2667 
AuthenticateServer(const AuthenticateConfigInfo &authenticateConfigInfo)2668 ResponseEsimResult EsimFile::AuthenticateServer(const AuthenticateConfigInfo &authenticateConfigInfo)
2669 {
2670     esimProfile_.portIndex = authenticateConfigInfo.portIndex_;
2671     esimProfile_.matchingId = authenticateConfigInfo.matchingId_;
2672     esimProfile_.serverSigned1 = authenticateConfigInfo.serverSigned1_;
2673     esimProfile_.serverSignature1 = authenticateConfigInfo.serverSignature1_;
2674     esimProfile_.euiccCiPkIdToBeUsed = authenticateConfigInfo.euiccCiPkIdToBeUsed_;
2675     esimProfile_.serverCertificate = authenticateConfigInfo.serverCertificate_;
2676 
2677     std::u16string imei = u"";
2678     CoreManagerInner::GetInstance().GetImei(slotId_, imei);
2679     esimProfile_.imei = imei;
2680     SyncOpenChannel();
2681     recvCombineStr_ = "";
2682     if (!ProcessAuthenticateServer(slotId_)) {
2683         TELEPHONY_LOGE("ProcessAuthenticateServer encode failed");
2684         return ResponseEsimResult();
2685     }
2686     isAuthenticateServerReady_ = false;
2687     std::unique_lock<std::mutex> lock(authenticateServerMutex_);
2688     if (!authenticateServerCv_.wait_for(lock, std::chrono::seconds(WAIT_TIME_LONG_SECOND_FOR_ESIM),
2689         [this]() { return isAuthenticateServerReady_; })) {
2690         SyncCloseChannel();
2691         return ResponseEsimResult();
2692     }
2693     SyncCloseChannel();
2694     return responseAuthenticateResult_;
2695 }
2696 
ProcessObtainEuiccInfo2(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)2697 bool EsimFile::ProcessObtainEuiccInfo2(int32_t slotId, const AppExecFwk::InnerEvent::Pointer &responseEvent)
2698 {
2699     if (!IsLogicChannelOpen()) {
2700         return false;
2701     }
2702     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_GET_EUICC_INFO_2);
2703     if (builder == nullptr) {
2704         TELEPHONY_LOGE("builder is nullptr");
2705         return false;
2706     }
2707     std::string hexStr;
2708     uint32_t strLen = builder->Asn1BuilderToHexStr(hexStr);
2709     ApduSimIORequestInfo reqInfo;
2710     CommBuildOneApduReqInfo(reqInfo, builder);
2711     if (telRilManager_ == nullptr) {
2712         return false;
2713     }
2714     int32_t apduResult = telRilManager_->SimTransmitApduLogicalChannel(slotId, reqInfo, responseEvent);
2715     if (apduResult == TELEPHONY_ERR_FAIL) {
2716         return false;
2717     }
2718     return true;
2719 }
2720 
ResetEuiccNotification()2721 void EsimFile::ResetEuiccNotification()
2722 {
2723     notification_.seq_ = 0;
2724     notification_.targetAddr_ = u"";
2725     notification_.event_ = 0;
2726     notification_.data_ = u"";
2727 }
2728 
ConvertAuthInputParaFromApiStru(Es9PlusInitAuthResp &dst, EsimProfile &src)2729 void EsimFile::ConvertAuthInputParaFromApiStru(Es9PlusInitAuthResp &dst, EsimProfile &src)
2730 {
2731     dst.serverSigned1 = OHOS::Telephony::ToUtf8(src.serverSigned1);
2732     dst.serverSignature1 = OHOS::Telephony::ToUtf8(src.serverSignature1);
2733     dst.euiccCiPKIdToBeUsed = OHOS::Telephony::ToUtf8(src.euiccCiPkIdToBeUsed);
2734     dst.serverCertificate = OHOS::Telephony::ToUtf8(src.serverCertificate);
2735     dst.matchingId = OHOS::Telephony::ToUtf8(src.matchingId);
2736     dst.imei = OHOS::Telephony::ToUtf8(src.imei);
2737 }
2738 
ProcessAuthenticateServer(int32_t slotId)2739 bool EsimFile::ProcessAuthenticateServer(int32_t slotId)
2740 {
2741     if (!IsLogicChannelOpen()) {
2742         return false;
2743     }
2744     Es9PlusInitAuthResp bytes;
2745     ConvertAuthInputParaFromApiStru(bytes, esimProfile_);
2746     std::shared_ptr<Asn1Builder> builder = std::make_shared<Asn1Builder>(TAG_ESIM_AUTHENTICATE_SERVER);
2747     if (builder == nullptr) {
2748         TELEPHONY_LOGE("builder create failed");
2749         return false;
2750     }
2751     Asn1AddChildAsBase64(builder, bytes.serverSigned1);
2752     Asn1AddChildAsBase64(builder, bytes.serverSignature1);
2753     Asn1AddChildAsBase64(builder, bytes.euiccCiPKIdToBeUsed);
2754     Asn1AddChildAsBase64(builder, bytes.serverCertificate);
2755     std::shared_ptr<Asn1Builder> ctxParams1Builder = std::make_shared<Asn1Builder>(TAG_ESIM_CTX_COMP_0);
2756     AddCtxParams1(ctxParams1Builder, bytes);
2757     if (ctxParams1Builder == nullptr) {
2758         TELEPHONY_LOGE("AddCtxParams1 failed");
2759         return false;
2760     }
2761     std::shared_ptr<Asn1Node> ctxNode = ctxParams1Builder->Asn1Build();
2762     if (ctxNode == nullptr) {
2763         TELEPHONY_LOGE("ctxNode is nullptr");
2764         return false;
2765     }
2766     builder->Asn1AddChild(ctxNode);
2767     std::string hexStr;
2768     uint32_t hexStrLen = builder->Asn1BuilderToHexStr(hexStr);
2769     SplitSendLongData(slotId, hexStr, MSG_ESIM_AUTHENTICATE_SERVER);
2770     return true;
2771 }
2772 
AddDeviceCapability(std::shared_ptr<Asn1Builder> &devCapsBuilder)2773 void EsimFile::AddDeviceCapability(std::shared_ptr<Asn1Builder> &devCapsBuilder)
2774 {
2775     std::vector<uint8_t> versionBytes;
2776     Asn1Utils::UintToBytes(VERSION_NUMBER, versionBytes);
2777     devCapsBuilder->Asn1AddChildAsBytes(TAG_ESIM_CTX_0, versionBytes, versionBytes.size());
2778     devCapsBuilder->Asn1AddChildAsBytes(TAG_ESIM_CTX_1, versionBytes, versionBytes.size());
2779     devCapsBuilder->Asn1AddChildAsBytes(TAG_ESIM_CTX_5, versionBytes, versionBytes.size());
2780 }
2781 
GetImeiBytes(std::vector<uint8_t> &imeiBytes, const std::string &imei)2782 void EsimFile::GetImeiBytes(std::vector<uint8_t> &imeiBytes, const std::string &imei)
2783 {
2784     size_t imeiLen = imei.length();
2785     if (imeiLen < AUTH_SERVER_IMEI_LEN * BYTE_TO_HEX_LEN - 1) {
2786         return;
2787     }
2788     if (imeiLen != AUTH_SERVER_IMEI_LEN * BYTE_TO_HEX_LEN) {
2789         std::string newImei = imei;
2790         newImei += 'F';
2791         Asn1Utils::BcdToBytes(newImei, imeiBytes);
2792         unsigned char last = imeiBytes[LAST_BYTE_OF_IMEI];
2793         imeiBytes[LAST_BYTE_OF_IMEI] = static_cast<unsigned char>((last & 0xFF) <<
2794             OFFSET_FOUR_BIT | ((last & 0xFF) >> OFFSET_FOUR_BIT));
2795     } else {
2796         Asn1Utils::BcdToBytes(imei, imeiBytes);
2797     }
2798 }
2799 
AddCtxParams1(std::shared_ptr<Asn1Builder> &ctxParams1Builder, Es9PlusInitAuthResp &pbytes)2800 void EsimFile::AddCtxParams1(std::shared_ptr<Asn1Builder> &ctxParams1Builder, Es9PlusInitAuthResp &pbytes)
2801 {
2802     if (ctxParams1Builder == nullptr) {
2803         return;
2804     }
2805     ctxParams1Builder->Asn1AddChildAsString(TAG_ESIM_CTX_0, pbytes.matchingId);
2806     std::shared_ptr<Asn1Node> subNode = nullptr;
2807     std::vector<uint8_t> tacBytes;
2808     std::vector<uint8_t> imeiBytes;
2809     Asn1Utils::BcdToBytes(pbytes.imei, tacBytes);
2810     GetImeiBytes(imeiBytes, pbytes.imei);
2811     std::shared_ptr<Asn1Builder> subBuilder = std::make_shared<Asn1Builder>(TAG_ESIM_CTX_COMP_1);
2812     if (subBuilder == nullptr) {
2813         TELEPHONY_LOGE("AddCtxParams1 subBuilder is nullptr");
2814         return;
2815     }
2816     subBuilder->Asn1AddChildAsBytes(TAG_ESIM_CTX_0, tacBytes, tacBytes.size());
2817     // add devCap
2818     std::shared_ptr<Asn1Builder> devCapsBuilder = std::make_shared<Asn1Builder>(TAG_ESIM_CTX_COMP_1);
2819     if (devCapsBuilder == nullptr) {
2820         TELEPHONY_LOGE("AddCtxParams1 devCapsBuilder is nullptr");
2821         return;
2822     }
2823     AddDeviceCapability(devCapsBuilder);
2824     std::shared_ptr<Asn1Node> devCapNode = devCapsBuilder->Asn1Build();
2825     if (devCapNode == nullptr) {
2826         TELEPHONY_LOGE("devCapNode is nullptr");
2827         return;
2828     }
2829     subBuilder->Asn1AddChild(devCapNode);
2830     subBuilder->Asn1AddChildAsBytes(TAG_ESIM_CTX_2, imeiBytes, imeiBytes.size());
2831     subNode = subBuilder->Asn1Build();
2832     ctxParams1Builder->Asn1AddChild(subNode);
2833 }
2834 
ProcessObtainEuiccInfo2Done(const AppExecFwk::InnerEvent::Pointer &event)2835 bool EsimFile::ProcessObtainEuiccInfo2Done(const AppExecFwk::InnerEvent::Pointer &event)
2836 {
2837     if (event == nullptr) {
2838         TELEPHONY_LOGE("event is nullptr!");
2839         return false;
2840     }
2841     std::unique_ptr<IccFromRilMsg> rcvMsg = event->GetUniqueObject<IccFromRilMsg>();
2842     if (rcvMsg == nullptr) {
2843         TELEPHONY_LOGE("rcvMsg is nullptr");
2844         return false;
2845     }
2846     IccFileData *result = &(rcvMsg->fileData);
2847     if (result == nullptr) {
2848         return false;
2849     }
2850     std::vector<uint8_t> responseByte = Asn1Utils::HexStrToBytes(result->resultData);
2851     uint32_t byteLen = responseByte.size();
2852     std::shared_ptr<Asn1Node> root = Asn1ParseResponse(responseByte, byteLen);
2853     if (root == nullptr) {
2854         TELEPHONY_LOGE("Asn1ParseResponse failed");
2855         return false;
2856     }
2857     this->EuiccInfo2ParseProfileVersion(euiccInfo2Result_, root);
2858     this->EuiccInfo2ParseSvn(euiccInfo2Result_, root);
2859     this->EuiccInfo2ParseEuiccFirmwareVer(euiccInfo2Result_, root);
2860     this->EuiccInfo2ParseExtCardResource(euiccInfo2Result_, root);
2861     this->EuiccInfo2ParseUiccCapability(euiccInfo2Result_, root);
2862     this->EuiccInfo2ParseTs102241Version(euiccInfo2Result_, root);
2863     this->EuiccInfo2ParseGlobalPlatformVersion(euiccInfo2Result_, root);
2864     this->EuiccInfo2ParseRspCapability(euiccInfo2Result_, root);
2865     this->EuiccInfo2ParseEuiccCiPKIdListForVerification(euiccInfo2Result_, root);
2866     this->EuiccInfo2ParseEuiccCiPKIdListForSigning(euiccInfo2Result_, root);
2867     this->EuiccInfo2ParseEuiccCategory(euiccInfo2Result_, root);
2868     this->EuiccInfo2ParsePpVersion(euiccInfo2Result_, root);
2869     euiccInfo2Result_.resultCode_ = ResultState::RESULT_OK;
2870     euiccInfo2Result_.response_ = result->resultData;
2871     {
2872         std::lock_guard<std::mutex> lock(euiccInfo2Mutex_);
2873         isEuiccInfo2Ready_ = true;
2874     }
2875     euiccInfo2Cv_.notify_one();
2876     return true;
2877 }
2878 
EuiccInfo2ParseProfileVersion(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)2879 void EsimFile::EuiccInfo2ParseProfileVersion(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)
2880 {
2881     std::shared_ptr<Asn1Node> profileVerNode = root->Asn1GetChild(TAG_ESIM_CTX_1);
2882     if (profileVerNode == nullptr) {
2883         TELEPHONY_LOGE("profileVerNode is nullptr");
2884         return;
2885     }
2886     std::vector<uint8_t> profileVersionRaw = {};
2887     uint32_t profileVersionRawLen = profileVerNode->Asn1AsBytes(profileVersionRaw);
2888     if (profileVersionRawLen < EUICC_INFO_VERSION_MIN_LENGTH) {
2889         TELEPHONY_LOGE("invalid profileVersion data");
2890         return;
2891     }
2892     euiccInfo2.profileVersion_ = MakeVersionString(profileVersionRaw);
2893 }
2894 
EuiccInfo2ParseSvn(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)2895 void EsimFile::EuiccInfo2ParseSvn(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)
2896 {
2897     std::shared_ptr<Asn1Node> svnNode = root->Asn1GetChild(TAG_ESIM_CTX_2);
2898     if (svnNode == nullptr) {
2899         TELEPHONY_LOGE("svnNode is nullptr");
2900         return;
2901     }
2902     std::vector<uint8_t> svnRaw = {};
2903     uint32_t svnRawLen = svnNode->Asn1AsBytes(svnRaw);
2904     if (svnRawLen < EUICC_INFO_VERSION_MIN_LENGTH) {
2905         TELEPHONY_LOGE("invalid SVN data");
2906         return;
2907     }
2908     euiccInfo2.svn_ = MakeVersionString(svnRaw);
2909 }
2910 
EuiccInfo2ParseEuiccFirmwareVer(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)2911 void EsimFile::EuiccInfo2ParseEuiccFirmwareVer(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)
2912 {
2913     std::shared_ptr<Asn1Node> euiccFirmwareVerNode = root->Asn1GetChild(TAG_ESIM_CTX_3);
2914     if (euiccFirmwareVerNode == nullptr) {
2915         TELEPHONY_LOGE("euiccFirmwareVerNode is nullptr");
2916         return;
2917     }
2918     std::vector<uint8_t> euiccFirmwareVerRaw = {};
2919     uint32_t versionLen = euiccFirmwareVerNode->Asn1AsBytes(euiccFirmwareVerRaw);
2920     if (versionLen < EUICC_INFO_VERSION_MIN_LENGTH) {
2921         TELEPHONY_LOGE("invalid firmwareVer data");
2922         return;
2923     }
2924     euiccInfo2.firmwareVer_ = MakeVersionString(euiccFirmwareVerRaw);
2925 }
2926 
EuiccInfo2ParseExtCardResource(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)2927 void EsimFile::EuiccInfo2ParseExtCardResource(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)
2928 {
2929     std::shared_ptr<Asn1Node> extCardResourceNode = root->Asn1GetChild(TAG_ESIM_CTX_4);
2930     if (extCardResourceNode == nullptr) {
2931         TELEPHONY_LOGE("extCardResourceNode is nullptr");
2932         return;
2933     }
2934     extCardResourceNode->Asn1AsString(euiccInfo2.extCardResource_);
2935 }
2936 
EuiccInfo2ParseUiccCapability(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)2937 void EsimFile::EuiccInfo2ParseUiccCapability(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)
2938 {
2939     std::shared_ptr<Asn1Node> uiccCapabilityNode = root->Asn1GetChild(TAG_ESIM_CTX_5);
2940     if (uiccCapabilityNode == nullptr) {
2941         TELEPHONY_LOGE("uiccCapabilityNode is nullptr");
2942         return;
2943     }
2944     uiccCapabilityNode->Asn1AsString(euiccInfo2.uiccCapability_);
2945 }
2946 
EuiccInfo2ParseTs102241Version(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)2947 void EsimFile::EuiccInfo2ParseTs102241Version(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)
2948 {
2949     std::shared_ptr<Asn1Node> ts102241VersionNode = root->Asn1GetChild(TAG_ESIM_CTX_6);
2950     if (ts102241VersionNode == nullptr) {
2951         TELEPHONY_LOGE("ts102241VersionNode is nullptr");
2952         return;
2953     }
2954     std::vector<uint8_t> ts102241VersionRaw = {};
2955     uint32_t versionLen = ts102241VersionNode->Asn1AsBytes(ts102241VersionRaw);
2956     if (versionLen < EUICC_INFO_VERSION_MIN_LENGTH) {
2957         TELEPHONY_LOGE("invalid ts102241VersionNode data");
2958         return;
2959     }
2960     euiccInfo2.ts102241Version_ = MakeVersionString(ts102241VersionRaw);
2961 }
2962 
EuiccInfo2ParseGlobalPlatformVersion(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)2963 void EsimFile::EuiccInfo2ParseGlobalPlatformVersion(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)
2964 {
2965     std::shared_ptr<Asn1Node> globalPlatformVersionNode = root->Asn1GetChild(TAG_ESIM_CTX_7);
2966     if (globalPlatformVersionNode == nullptr) {
2967         TELEPHONY_LOGE("globalPlatformVersionNode is nullptr");
2968         return;
2969     }
2970     std::vector<uint8_t> globalPlatformVersionRaw = {};
2971     uint32_t versionLen = globalPlatformVersionNode->Asn1AsBytes(globalPlatformVersionRaw);
2972     if (versionLen < EUICC_INFO_VERSION_MIN_LENGTH) {
2973         TELEPHONY_LOGE("invalid globalplatformVersionRaw data");
2974         return;
2975     }
2976     euiccInfo2.globalPlatformVersion_ = MakeVersionString(globalPlatformVersionRaw);
2977 }
2978 
EuiccInfo2ParseRspCapability(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)2979 void EsimFile::EuiccInfo2ParseRspCapability(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)
2980 {
2981     std::shared_ptr<Asn1Node> rspCapabilityNode = root->Asn1GetChild(TAG_ESIM_CTX_8);
2982     if (rspCapabilityNode == nullptr) {
2983         TELEPHONY_LOGE("rspCapabilityNode is nullptr");
2984         return;
2985     }
2986     rspCapabilityNode->Asn1AsString(euiccInfo2.rspCapability_);
2987 }
2988 
EuiccInfo2ParseEuiccCiPKIdListForVerification(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)2989 void EsimFile::EuiccInfo2ParseEuiccCiPKIdListForVerification(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)
2990 {
2991     std::shared_ptr<Asn1Node> ciPKIdListForVerificationNode = root->Asn1GetChild(TAG_ESIM_CTX_COMP_9);
2992     if (ciPKIdListForVerificationNode == nullptr) {
2993         TELEPHONY_LOGE("ciPKIdListForVerificationNode is nullptr");
2994         return;
2995     }
2996     ciPKIdListForVerificationNode->Asn1NodeToHexStr(euiccInfo2.euiccCiPKIdListForVerification_);
2997 }
2998 
EuiccInfo2ParseEuiccCiPKIdListForSigning(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)2999 void EsimFile::EuiccInfo2ParseEuiccCiPKIdListForSigning(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)
3000 {
3001     std::shared_ptr<Asn1Node> euiccCiPKIdListForSigningNode = root->Asn1GetChild(TAG_ESIM_CTX_COMP_A);
3002     if (euiccCiPKIdListForSigningNode == nullptr) {
3003         TELEPHONY_LOGE("euiccCiPKIdListForSigningNode is nullptr");
3004         return;
3005     }
3006     euiccCiPKIdListForSigningNode->Asn1NodeToHexStr(euiccInfo2.euiccCiPKIdListForSigning_);
3007 }
3008 
EuiccInfo2ParseEuiccCategory(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)3009 void EsimFile::EuiccInfo2ParseEuiccCategory(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)
3010 {
3011     std::shared_ptr<Asn1Node> euiccCategoryNode = root->Asn1GetChild(TAG_ESIM_CTX_B);
3012     if (euiccCategoryNode == nullptr) {
3013         TELEPHONY_LOGE("euiccCategoryNode is nullptr");
3014         return;
3015     }
3016     euiccInfo2.euiccCategory_ = euiccCategoryNode->Asn1AsInteger();
3017 }
3018 
EuiccInfo2ParsePpVersion(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)3019 void EsimFile::EuiccInfo2ParsePpVersion(EuiccInfo2 &euiccInfo2, std::shared_ptr<Asn1Node> &root)
3020 {
3021     std::shared_ptr<Asn1Node> ppVersionNode = root->Asn1GetChild(TAG_ESIM_OCTET_STRING_TYPE);
3022     if (ppVersionNode == nullptr) {
3023         TELEPHONY_LOGE("ppVersionNode is nullptr");
3024         return;
3025     }
3026     std::vector<uint8_t> ppVersionNodeRaw = {};
3027     uint32_t versionLen = ppVersionNode->Asn1AsBytes(ppVersionNodeRaw);
3028     if (versionLen < EUICC_INFO_VERSION_MIN_LENGTH) {
3029         TELEPHONY_LOGE("invalid ppVersion data");
3030         return;
3031     }
3032     euiccInfo2.ppVersion_ = MakeVersionString(ppVersionNodeRaw);
3033 }
3034 
RealProcsessAuthenticateServerDone(std::string combineHexStr)3035 bool EsimFile::RealProcsessAuthenticateServerDone(std::string combineHexStr)
3036 {
3037     std::vector<uint8_t> responseByte = Asn1Utils::HexStrToBytes(combineHexStr);
3038     std::shared_ptr<Asn1Node> responseNode = Asn1ParseResponse(responseByte, responseByte.size());
3039     if (responseNode == nullptr) {
3040         TELEPHONY_LOGE("Asn1ParseResponse failed");
3041         return false;
3042     }
3043     AuthServerResponse authServerResp = { 0 };
3044     if (responseNode->Asn1HasChild(TAG_ESIM_CTX_COMP_1)) {
3045         std::shared_ptr<Asn1Node> authServerRespNode = responseNode->Asn1GetChild(TAG_ESIM_CTX_COMP_1);
3046         if (authServerRespNode == nullptr) {
3047             TELEPHONY_LOGE("authServerRespNode is nullptr");
3048             return false;
3049         }
3050         if (authServerRespNode->Asn1HasChild(TAG_ESIM_CTX_0) &&
3051             authServerRespNode->Asn1HasChild(TAG_ESIM_INTEGER_TYPE)) {
3052             std::shared_ptr<Asn1Node> transactionIdNode = authServerRespNode->Asn1GetChild(TAG_ESIM_CTX_0);
3053             std::shared_ptr<Asn1Node> errCodeNode = authServerRespNode->Asn1GetChild(TAG_ESIM_INTEGER_TYPE);
3054             if (transactionIdNode == nullptr || errCodeNode == nullptr) {
3055                 TELEPHONY_LOGE("authServerRespNode failed");
3056                 return false;
3057             }
3058             uint32_t tidByteLen = transactionIdNode->Asn1AsString(authServerResp.transactionId);
3059             if (tidByteLen == 0) {
3060                 TELEPHONY_LOGE("tidByteLen is zero.");
3061                 return false;
3062             }
3063             authServerResp.errCode = errCodeNode->Asn1AsInteger();
3064         } else {
3065             TELEPHONY_LOGE("the auth server response has no right child");
3066             return false;
3067         }
3068     } else {
3069         authServerResp.respStr = responseByte;
3070         authServerResp.respLength = responseByte.size();
3071     }
3072     CovertAuthToApiStruct(responseAuthenticateResult_, authServerResp);
3073 
3074     {
3075         std::lock_guard<std::mutex> lock(authenticateServerMutex_);
3076         isAuthenticateServerReady_ = true;
3077     }
3078     authenticateServerCv_.notify_one();
3079     return true;
3080 }
3081 
ProcessAuthenticateServerDone(const AppExecFwk::InnerEvent::Pointer &event)3082 bool EsimFile::ProcessAuthenticateServerDone(const AppExecFwk::InnerEvent::Pointer &event)
3083 {
3084     if (event == nullptr) {
3085         TELEPHONY_LOGE("event is nullptr!");
3086         return false;
3087     }
3088     std::unique_ptr<IccFromRilMsg> rcvMsg = event->GetUniqueObject<IccFromRilMsg>();
3089     if (rcvMsg == nullptr) {
3090         TELEPHONY_LOGE("rcvMsg is nullptr");
3091         return false;
3092     }
3093     if (!MergeRecvLongDataComplete(rcvMsg->fileData, MSG_ESIM_AUTHENTICATE_SERVER)) {
3094         return true;
3095     }
3096     return RealProcsessAuthenticateServerDone(recvCombineStr_);
3097 }
3098 
CovertAuthToApiStruct(ResponseEsimResult &dst, AuthServerResponse &src)3099 void EsimFile::CovertAuthToApiStruct(ResponseEsimResult &dst, AuthServerResponse &src)
3100 {
3101     dst.resultCode_ = static_cast<ResultState>(src.errCode);
3102     std::string hexStr = Asn1Utils::BytesToHexStr(src.respStr);
3103     dst.response_ = OHOS::Telephony::ToUtf16(hexStr);
3104 }
3105 
InitChanneMemberFunc()3106 void EsimFile::InitChanneMemberFunc()
3107 {
3108     memberFuncMap_[MSG_ESIM_OPEN_CHANNEL_DONE] =
3109         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessEsimOpenChannelDone(event); };
3110     memberFuncMap_[MSG_ESIM_CLOSE_CHANNEL_DONE] =
3111         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessEsimCloseChannelDone(event); };
3112     memberFuncMap_[MSG_ESIM_SEND_APUD_DATA] =
3113         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessSendApduDataDone(event); };
3114 }
3115 
InitMemberFunc()3116 void EsimFile::InitMemberFunc()
3117 {
3118     memberFuncMap_[MSG_ESIM_OBTAIN_EID_DONE] =
3119         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessObtainEidDone(event); };
3120     memberFuncMap_[MSG_ESIM_OBTAIN_EUICC_INFO_1_DONE] =
3121         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessObtainEuiccInfo1Done(event); };
3122     memberFuncMap_[MSG_ESIM_REQUEST_ALL_PROFILES] =
3123         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessRequestAllProfilesDone(event); };
3124     memberFuncMap_[MSG_ESIM_OBTAIN_EUICC_CHALLENGE_DONE] =
3125         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessObtainEuiccChallengeDone(event); };
3126     memberFuncMap_[MSG_ESIM_REQUEST_RULES_AUTH_TABLE] =
3127         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessRequestRulesAuthTableDone(event); };
3128     memberFuncMap_[MSG_ESIM_OBTAIN_SMDS_ADDRESS] =
3129         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessObtainSmdsAddressDone(event); };
3130     memberFuncMap_[MSG_ESIM_DISABLE_PROFILE] =
3131         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessDisableProfileDone(event); };
3132     memberFuncMap_[MSG_ESIM_OBTAIN_DEFAULT_SMDP_ADDRESS_DONE] =
3133         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessObtainDefaultSmdpAddressDone(event); };
3134     memberFuncMap_[MSG_ESIM_CANCEL_SESSION] =
3135         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessCancelSessionDone(event); };
3136     memberFuncMap_[MSG_ESIM_GET_PROFILE] =
3137         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessGetProfileDone(event); };
3138     memberFuncMap_[MSG_ESIM_ESTABLISH_DEFAULT_SMDP_ADDRESS_DONE] =
3139         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessEstablishDefaultSmdpAddressDone(event); };
3140     memberFuncMap_[MSG_ESIM_RESET_MEMORY] =
3141         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessResetMemoryDone(event); };
3142     memberFuncMap_[MSG_ESIM_LIST_NOTIFICATION] =
3143         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessListNotificationsDone(event); };
3144     memberFuncMap_[MSG_ESIM_LOAD_BOUND_PROFILE_PACKAGE] =
3145         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessLoadBoundProfilePackageDone(event); };
3146     memberFuncMap_[MSG_ESIM_PREPARE_DOWNLOAD_DONE] =
3147         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessPrepareDownloadDone(event); };
3148     memberFuncMap_[MSG_ESIM_REMOVE_NOTIFICATION] =
3149         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessRemoveNotificationDone(event); };
3150     memberFuncMap_[MSG_ESIM_RETRIEVE_NOTIFICATION_DONE] =
3151         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessRetrieveNotificationDone(event); };
3152     memberFuncMap_[MSG_ESIM_RETRIEVE_NOTIFICATION_LIST] =
3153         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessRetrieveNotificationListDone(event); };
3154     memberFuncMap_[MSG_ESIM_DELETE_PROFILE] =
3155         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessDeleteProfileDone(event); };
3156     memberFuncMap_[MSG_ESIM_SWITCH_PROFILE] =
3157         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessSwitchToProfileDone(event); };
3158     memberFuncMap_[MSG_ESIM_SET_NICK_NAME] =
3159         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessSetNicknameDone(event); };
3160     memberFuncMap_[MSG_ESIM_OBTAIN_EUICC_INFO2_DONE] =
3161         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessObtainEuiccInfo2Done(event); };
3162     memberFuncMap_[MSG_ESIM_AUTHENTICATE_SERVER] =
3163         [this](const AppExecFwk::InnerEvent::Pointer &event) { return ProcessAuthenticateServerDone(event); };
3164 }
3165 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event)3166 void EsimFile::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event)
3167 {
3168     if (event == nullptr) {
3169         TELEPHONY_LOGE("event is nullptr");
3170         return;
3171     }
3172     auto id = event->GetInnerEventId();
3173     auto itFunc = memberFuncMap_.find(id);
3174     if (itFunc != memberFuncMap_.end()) {
3175         auto memberFunc = itFunc->second;
3176         if (memberFunc != nullptr) {
3177             bool isFileProcessResponse = memberFunc(event);
3178             return;
3179         }
3180     } else {
3181         IccFile::ProcessEvent(event);
3182     }
3183 }
3184 
GetRawDataFromEvent(const AppExecFwk::InnerEvent::Pointer &event, IccFileData &outRawData)3185 bool EsimFile::GetRawDataFromEvent(const AppExecFwk::InnerEvent::Pointer &event, IccFileData &outRawData)
3186 {
3187     if (event == nullptr) {
3188         TELEPHONY_LOGE("event is nullptr!");
3189         return false;
3190     }
3191     std::unique_ptr<IccFromRilMsg> rcvMsg = event->GetUniqueObject<IccFromRilMsg>();
3192     if (rcvMsg == nullptr) {
3193         TELEPHONY_LOGE("rcvMsg is nullptr");
3194         return false;
3195     }
3196     outRawData = rcvMsg->fileData;
3197     return true;
3198 }
3199 
ParseEvent(const AppExecFwk::InnerEvent::Pointer &event)3200 std::shared_ptr<Asn1Node> EsimFile::ParseEvent(const AppExecFwk::InnerEvent::Pointer &event)
3201 {
3202     IccFileData rawData;
3203     if (!GetRawDataFromEvent(event, rawData)) {
3204         TELEPHONY_LOGE("rawData is nullptr within rcvMsg");
3205         return nullptr;
3206     }
3207     std::vector<uint8_t> responseByte = Asn1Utils::HexStrToBytes(rawData.resultData);
3208     uint32_t byteLen = responseByte.size();
3209     return Asn1ParseResponse(responseByte, byteLen);
3210 }
3211 
ObtainSpnCondition(bool roaming, const std::string &operatorNum)3212 int32_t EsimFile::ObtainSpnCondition(bool roaming, const std::string &operatorNum)
3213 {
3214     return 0;
3215 }
3216 
ProcessIccReady(const AppExecFwk::InnerEvent::Pointer &event)3217 bool EsimFile::ProcessIccReady(const AppExecFwk::InnerEvent::Pointer &event)
3218 {
3219     return false;
3220 }
3221 
UpdateVoiceMail(const std::string &mailName, const std::string &mailNumber)3222 bool EsimFile::UpdateVoiceMail(const std::string &mailName, const std::string &mailNumber)
3223 {
3224     return false;
3225 }
3226 
SetVoiceMailCount(int32_t voiceMailCount)3227 bool EsimFile::SetVoiceMailCount(int32_t voiceMailCount)
3228 {
3229     return false;
3230 }
3231 
SetVoiceCallForwarding(bool enable, const std::string &number)3232 bool EsimFile::SetVoiceCallForwarding(bool enable, const std::string &number)
3233 {
3234     return false;
3235 }
3236 
GetVoiceMailNumber()3237 std::string EsimFile::GetVoiceMailNumber()
3238 {
3239     return "";
3240 }
3241 
SetVoiceMailNumber(const std::string mailNumber)3242 void EsimFile::SetVoiceMailNumber(const std::string mailNumber)
3243 {
3244     return;
3245 }
3246 
ProcessIccRefresh(int msgId)3247 void EsimFile::ProcessIccRefresh(int msgId)
3248 {
3249     return;
3250 }
3251 
ProcessFileLoaded(bool response)3252 void EsimFile::ProcessFileLoaded(bool response)
3253 {
3254     return;
3255 }
3256 
OnAllFilesFetched()3257 void EsimFile::OnAllFilesFetched()
3258 {
3259     return;
3260 }
3261 } // namespace Telephony
3262 } // namespace OHOS
3263