• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023-2023 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 #include "ce_service.h"
16 #include "nfc_event_publisher.h"
17 #include "nfc_event_handler.h"
18 #include "external_deps_proxy.h"
19 #include "loghelper.h"
20 #include "nfc_sdk_common.h"
21 #include "setting_data_share_impl.h"
22 #include "accesstoken_kit.h"
23 #include "hap_token_info.h"
24 
25 namespace OHOS {
26 namespace NFC {
27 const int FIELD_COMMON_EVENT_INTERVAL = 1000;
28 const int DEACTIVATE_TIMEOUT = 6000;
29 static const int DEFAULT_HOST_ROUTE_DEST = 0x00;
30 static const int PWR_STA_SWTCH_ON_SCRN_UNLCK = 0x01;
31 static const int DEFAULT_PWR_STA_HOST = PWR_STA_SWTCH_ON_SCRN_UNLCK;
32 const std::string APP_REMOVED = "app_removed";
33 const std::string APP_ADDED = "app_added";
34 std::mutex g_defaultPaymentAppInitMutex = {};
35 
CeService(std::weak_ptr<NfcService> nfcService,std::weak_ptr<NCI::INciCeInterface> nciCeProxy)36 CeService::CeService(std::weak_ptr<NfcService> nfcService, std::weak_ptr<NCI::INciCeInterface> nciCeProxy)
37     : nfcService_(nfcService), nciCeProxy_(nciCeProxy)
38 
39 {
40     Uri nfcDefaultPaymentApp(KITS::NFC_DATA_URI_PAYMENT_DEFAULT_APP);
41     DelayedSingleton<SettingDataShareImpl>::GetInstance()->GetElementName(
42         nfcDefaultPaymentApp, KITS::DATA_SHARE_KEY_NFC_PAYMENT_DEFAULT_APP, defaultPaymentElement_);
43 
44     appStateObserver_ = std::make_shared<AppStateObserver>(this);
45     DebugLog("CeService constructor end");
46 }
47 
~CeService()48 CeService::~CeService()
49 {
50     hostCardEmulationManager_ = nullptr;
51     aidToAidEntry_.clear();
52     foregroundElement_.SetBundleName("");
53     foregroundElement_.SetAbilityName("");
54     foregroundElement_.SetDeviceID("");
55     foregroundElement_.SetModuleName("");
56     defaultPaymentElement_.SetBundleName("");
57     defaultPaymentElement_.SetAbilityName("");
58     defaultPaymentElement_.SetDeviceID("");
59     defaultPaymentElement_.SetModuleName("");
60     initDefaultPaymentAppDone_ = false;
61     dynamicAids_.clear();
62     DebugLog("CeService deconstructor end");
63 }
64 
PublishFieldOnOrOffCommonEvent(bool isFieldOn)65 void CeService::PublishFieldOnOrOffCommonEvent(bool isFieldOn)
66 {
67     ExternalDepsProxy::GetInstance().PublishNfcFieldStateChanged(isFieldOn);
68 }
69 
RegHceCmdCallback(const sptr<KITS::IHceCmdCallback> & callback,const std::string & type,Security::AccessToken::AccessTokenID callerToken)70 bool CeService::RegHceCmdCallback(const sptr<KITS::IHceCmdCallback> &callback, const std::string &type,
71                                   Security::AccessToken::AccessTokenID callerToken)
72 {
73     if (hostCardEmulationManager_ == nullptr) {
74         ErrorLog("hce is null");
75         return false;
76     }
77     return hostCardEmulationManager_->RegHceCmdCallback(callback, type, callerToken);
78 }
79 
UnRegHceCmdCallback(const std::string & type,Security::AccessToken::AccessTokenID callerToken)80 bool CeService::UnRegHceCmdCallback(const std::string &type, Security::AccessToken::AccessTokenID callerToken)
81 {
82     if (hostCardEmulationManager_ == nullptr) {
83         ErrorLog("hce is null");
84         return false;
85     }
86     return hostCardEmulationManager_->UnRegHceCmdCallback(type, callerToken);
87 }
88 
UnRegAllCallback(Security::AccessToken::AccessTokenID callerToken)89 bool CeService::UnRegAllCallback(Security::AccessToken::AccessTokenID callerToken)
90 {
91     if (hostCardEmulationManager_ == nullptr) {
92         ErrorLog("hce is null");
93         return false;
94     }
95     return hostCardEmulationManager_->UnRegAllCallback(callerToken);
96 }
97 
IsDefaultService(ElementName & element,const std::string & type)98 bool CeService::IsDefaultService(ElementName &element, const std::string &type)
99 {
100     return type == KITS::TYPE_PAYMENT && element.GetBundleName() == defaultPaymentElement_.GetBundleName() &&
101            element.GetAbilityName() == defaultPaymentElement_.GetAbilityName();
102 }
103 
SendHostApduData(const std::string & hexCmdData,bool raw,std::string & hexRespData,Security::AccessToken::AccessTokenID callerToken)104 bool CeService::SendHostApduData(const std::string &hexCmdData, bool raw, std::string &hexRespData,
105                                  Security::AccessToken::AccessTokenID callerToken)
106 {
107     if (hostCardEmulationManager_ == nullptr) {
108         ErrorLog("hce is null");
109         return false;
110     }
111     return hostCardEmulationManager_->SendHostApduData(hexCmdData, raw, hexRespData, callerToken);
112 }
113 
InitConfigAidRouting(bool forceUpdate)114 bool CeService::InitConfigAidRouting(bool forceUpdate)
115 {
116     DebugLog("AddAidRoutingHceAids: start, forceUpdate is %{public}d", forceUpdate);
117     std::lock_guard<std::mutex> lock(configRoutingMutex_);
118     std::map<std::string, AidEntry> aidEntries;
119     BuildAidEntries(aidEntries);
120     InfoLog("AddAidRoutingHceAids, aid entries cache size %{public}zu,aid entries newly builded size %{public}zu",
121             aidToAidEntry_.size(), aidEntries.size());
122     if (aidEntries == aidToAidEntry_ && !forceUpdate) {
123         InfoLog("aid entries do not change.");
124         return false;
125     }
126 
127     if (nciCeProxy_.expired()) {
128         ErrorLog("InitConfigAidRouting: nciCeProxy_ is nullptr.");
129         return false;
130     }
131     nciCeProxy_.lock()->ClearAidTable();
132     aidToAidEntry_.clear();
133     bool addAllResult = true;
134     for (const auto &pair : aidEntries) {
135         AidEntry entry = pair.second;
136         std::string aid = entry.aid;
137         int aidInfo = entry.aidInfo;
138         int power = entry.power;
139         int route = entry.route;
140         InfoLog("AddAidRoutingHceAids: aid= %{public}s, aidInfo= "
141                 "0x%{public}x, route=0x%{public}x, power=0x%{public}x",
142                 aid.c_str(), aidInfo, route, power);
143         bool addResult = nciCeProxy_.lock()->AddAidRouting(aid, route, aidInfo, power);
144         if (!addResult) {
145             ErrorLog("AddAidRoutingHceAids: add aid failed aid= %{public}s", aid.c_str());
146             addAllResult = false;
147         }
148     }
149     if (addAllResult) {
150         InfoLog("AddAidRoutingHceAids: add aids success, update the aid entries cache");
151         aidToAidEntry_ = std::move(aidEntries);
152     }
153     DebugLog("AddAidRoutingHceAids: end");
154     return true;
155 }
156 
HandleAppStateChanged(const std::string & bundleName,const std::string & abilityName,int abilityState)157 void CeService::HandleAppStateChanged(const std::string &bundleName, const std::string &abilityName,
158                                       int abilityState)
159 {
160     if (bundleName.empty()) {
161         ErrorLog("OnForegroundApplicationChanged bundle name is empty.");
162         return;
163     }
164 
165     if (bundleName != foregroundElement_.GetBundleName()) {
166         DebugLog("OnForegroundApplicationChanged not equal to the foreground element, no need to handle.");
167         return;
168     }
169     if (abilityState == static_cast<int32_t>(AppExecFwk::ApplicationState::APP_STATE_FOREGROUND)) {
170         DebugLog("OnForegroundApplicationChanged foreground state, no need to handle.");
171         return;
172     }
173 
174     ClearHceInfo();
175     InfoLog("foreground app state change: refresh route table");
176     ConfigRoutingAndCommit();
177 }
178 
BuildAidEntries(std::map<std::string,AidEntry> & aidEntries)179 void CeService::BuildAidEntries(std::map<std::string, AidEntry> &aidEntries)
180 {
181     std::vector<AppDataParser::HceAppAidInfo> hceApps;
182     ExternalDepsProxy::GetInstance().GetHceApps(hceApps);
183     InfoLog("AddAidRoutingHceOtherAids: hce apps size %{public}zu", hceApps.size());
184     for (const AppDataParser::HceAppAidInfo &appAidInfo : hceApps) {
185         bool isForeground = appAidInfo.element.GetBundleName() == foregroundElement_.GetBundleName() &&
186                            appAidInfo.element.GetAbilityName() == foregroundElement_.GetAbilityName();
187         bool isDefaultPayment = appAidInfo.element.GetBundleName() == defaultPaymentElement_.GetBundleName() &&
188                                 appAidInfo.element.GetAbilityName() == defaultPaymentElement_.GetAbilityName();
189         for (const AppDataParser::AidInfo &aidInfo : appAidInfo.customDataAid) {
190             // add payment aid of default payment app and foreground app
191             // add other aid of all apps
192             bool shouldAdd = KITS::KEY_OHTER_AID == aidInfo.name || isForeground || isDefaultPayment;
193             if (shouldAdd) {
194                 AidEntry aidEntry;
195                 aidEntry.aid = aidInfo.value;
196                 aidEntry.aidInfo = 0;
197                 aidEntry.power = DEFAULT_PWR_STA_HOST;
198                 aidEntry.route = DEFAULT_HOST_ROUTE_DEST;
199                 aidEntries[aidInfo.value] = aidEntry;
200             }
201         }
202     }
203     for (const std::string &aid : dynamicAids_) {
204         AidEntry aidEntry;
205         aidEntry.aid = aid;
206         aidEntry.aidInfo = 0;
207         aidEntry.power = DEFAULT_PWR_STA_HOST;
208         aidEntry.route = DEFAULT_HOST_ROUTE_DEST;
209         aidEntries[aid] = aidEntry;
210     }
211 }
212 
ClearAidEntriesCache()213 void CeService::ClearAidEntriesCache()
214 {
215     std::lock_guard<std::mutex> lock(configRoutingMutex_);
216     aidToAidEntry_.clear();
217     DebugLog("ClearAidEntriesCache end");
218 }
219 
IsDynamicAid(const std::string & targetAid)220 bool CeService::IsDynamicAid(const std::string &targetAid)
221 {
222     for (const std::string &aid : dynamicAids_) {
223         if (aid == targetAid) {
224             return true;
225         }
226     }
227     return false;
228 }
229 
OnDefaultPaymentServiceChange()230 void CeService::OnDefaultPaymentServiceChange()
231 {
232     ElementName newElement;
233     Uri nfcDefaultPaymentApp(KITS::NFC_DATA_URI_PAYMENT_DEFAULT_APP);
234     DelayedSingleton<SettingDataShareImpl>::GetInstance()->GetElementName(
235         nfcDefaultPaymentApp, KITS::DATA_SHARE_KEY_NFC_PAYMENT_DEFAULT_APP, newElement);
236     if (newElement.GetURI() == defaultPaymentElement_.GetURI()) {
237         InfoLog("OnDefaultPaymentServiceChange: payment service not change");
238         return;
239     }
240 
241     if (nfcService_.expired()) {
242         ErrorLog("nfcService_ is nullptr.");
243         return;
244     }
245     if (!nfcService_.lock()->IsNfcEnabled()) {
246         ErrorLog("NFC not enabled, should not happen.The default payment app is be set when nfc is enabled.");
247         return;
248     }
249     nfcService_.lock()->NotifyMessageToVendor(KITS::DEF_PAYMENT_APP_CHANGE_KEY, newElement.GetBundleName());
250     ExternalDepsProxy::GetInstance().WriteDefaultPaymentAppChangeHiSysEvent(defaultPaymentElement_.GetBundleName(),
251                                                                             newElement.GetBundleName());
252     UpdateDefaultPaymentElement(newElement);
253     InfoLog("OnDefaultPaymentServiceChange: refresh route table");
254     ConfigRoutingAndCommit();
255 }
OnAppAddOrChangeOrRemove(std::shared_ptr<EventFwk::CommonEventData> data)256 void CeService::OnAppAddOrChangeOrRemove(std::shared_ptr<EventFwk::CommonEventData> data)
257 {
258     DebugLog("OnAppAddOrChangeOrRemove start");
259 
260     if (!AppEventCheckValid(data)) {
261         return;
262     }
263 
264     std::string action = data->GetWant().GetAction();
265     ElementName element = data->GetWant().GetElement();
266     std::string bundleName = element.GetBundleName();
267 
268     InfoLog("OnAppAddOrChangeOrRemove: change bundleName %{public}s, default payment bundle name %{public}s, "
269             "installed status %{public}d",
270             bundleName.c_str(), defaultPaymentElement_.GetBundleName().c_str(),
271             defaultPaymentBundleInstalled_);
272 
273     if (nfcService_.expired()) {
274         ErrorLog("nfcService_ is nullptr.");
275         return;
276     }
277     if (bundleName == defaultPaymentElement_.GetBundleName() &&
278         action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) {
279         UpdateDefaultPaymentBundleInstalledStatus(false);
280         ExternalDepsProxy::GetInstance().WriteDefaultPaymentAppChangeHiSysEvent(
281             defaultPaymentElement_.GetBundleName(), APP_REMOVED);
282         nfcService_.lock()->NotifyMessageToVendor(KITS::DEF_PAYMENT_APP_REMOVED_KEY, bundleName);
283     }
284 
285     if (bundleName == defaultPaymentElement_.GetBundleName() &&
286         action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED) {
287         UpdateDefaultPaymentBundleInstalledStatus(true);
288         ExternalDepsProxy::GetInstance().WriteDefaultPaymentAppChangeHiSysEvent(
289             defaultPaymentElement_.GetBundleName(), APP_ADDED);
290         nfcService_.lock()->NotifyMessageToVendor(KITS::DEF_PAYMENT_APP_ADDED_KEY, bundleName);
291     }
292 
293     if (!nfcService_.lock()->IsNfcEnabled()) {
294         ErrorLog(" NFC not enabled, not need to update routing entry ");
295         return;
296     }
297     InfoLog("OnAppAddOrChangeOrRemove: refresh route table");
298     ConfigRoutingAndCommit();
299     DebugLog("OnAppAddOrChangeOrRemove end");
300 }
301 
AppEventCheckValid(std::shared_ptr<EventFwk::CommonEventData> data)302 bool CeService::AppEventCheckValid(std::shared_ptr<EventFwk::CommonEventData> data)
303 {
304     if (data == nullptr) {
305         ErrorLog("invalid event data");
306         return false;
307     }
308     std::string action = data->GetWant().GetAction();
309     if (action.empty()) {
310         ErrorLog("action is empty");
311         return false;
312     }
313     if ((action != EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED) &&
314         (action != EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED) &&
315         (action != EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED)) {
316         InfoLog("not the interested action");
317         return false;
318     }
319 
320     ElementName element = data->GetWant().GetElement();
321     std::string bundleName = element.GetBundleName();
322     if (bundleName.empty()) {
323         ErrorLog("invalid bundleName.");
324         return false;
325     }
326     return true;
327 }
UpdateDefaultPaymentBundleInstalledStatus(bool installed)328 void CeService::UpdateDefaultPaymentBundleInstalledStatus(bool installed)
329 {
330     InfoLog("UpdateDefaultPaymentBundleInstalledStatus: bundleName %{public}d", installed);
331     std::lock_guard<std::mutex> lock(configRoutingMutex_);
332     defaultPaymentBundleInstalled_ = installed;
333 }
334 
UpdateDefaultPaymentElement(const ElementName & element)335 void CeService::UpdateDefaultPaymentElement(const ElementName &element)
336 {
337     InfoLog("UpdateDefaultPaymentElement: bundleName %{public}s", element.GetURI().c_str());
338     std::lock_guard<std::mutex> lock(configRoutingMutex_);
339     defaultPaymentElement_ = element;
340     defaultPaymentBundleInstalled_ = true;
341 }
GetDefaultPaymentType()342 KITS::DefaultPaymentType CeService::GetDefaultPaymentType()
343 {
344     InfoLog("GetDefaultPaymentType: default payment bundle name %{public}s, "
345             "installed status %{public}d",
346             defaultPaymentElement_.GetBundleName().c_str(), defaultPaymentBundleInstalled_);
347 
348     if (defaultPaymentElement_.GetBundleName().empty()) {
349         return KITS::DefaultPaymentType::TYPE_EMPTY;
350     }
351     if (!defaultPaymentBundleInstalled_) {
352         return KITS::DefaultPaymentType::TYPE_UNINSTALLED;
353     }
354     if (!nciCeProxy_.expired() &&
355         (defaultPaymentElement_.GetBundleName() == nciCeProxy_.lock()->GetSimVendorBundleName())) {
356         return KITS::DefaultPaymentType::TYPE_UICC;
357     }
358     if (ExternalDepsProxy::GetInstance().IsHceApp(defaultPaymentElement_)) {
359         return KITS::DefaultPaymentType::TYPE_HCE;
360     }
361 
362     return KITS::DefaultPaymentType::TYPE_ESE;
363 }
364 
ConfigRoutingAndCommit()365 void CeService::ConfigRoutingAndCommit()
366 {
367     if (nfcService_.expired()) {
368         ErrorLog("ConfigRoutingAndCommit: nfc service is null");
369         return;
370     }
371     std::weak_ptr<NfcRoutingManager> routingManager = nfcService_.lock()->GetNfcRoutingManager();
372     if (routingManager.expired()) {
373         ErrorLog("ConfigRoutingAndCommit: routing manager is null");
374         return;
375     }
376 
377     bool updateAids = false;
378     bool updatePaymentType = UpdateDefaultPaymentType();
379     if (updatePaymentType) {
380         updateAids = InitConfigAidRouting(true);
381     } else {
382         updateAids = InitConfigAidRouting(false);
383     }
384 
385     InfoLog(
386         "ConfigRoutingAndCommit: aids updated status %{public}d, default payment type updated status %{public}d.",
387         updateAids, updatePaymentType);
388     if (updateAids || updatePaymentType) {
389         routingManager.lock()->ComputeRoutingParams(defaultPaymentType_);
390         routingManager.lock()->CommitRouting();
391     }
392 }
393 
SearchElementByAid(const std::string & aid,ElementName & aidElement)394 void CeService::SearchElementByAid(const std::string &aid, ElementName &aidElement)
395 {
396     if (aid.empty()) {
397         InfoLog("aid is empty");
398         return;
399     }
400     // find dynamic aid
401     if (IsDynamicAid(aid) && !foregroundElement_.GetBundleName().empty()) {
402         InfoLog("is foreground element");
403         aidElement.SetBundleName(foregroundElement_.GetBundleName());
404         aidElement.SetAbilityName(foregroundElement_.GetAbilityName());
405         return;
406     }
407     std::vector<AppDataParser::HceAppAidInfo> hceApps;
408     ExternalDepsProxy::GetInstance().GetHceAppsByAid(aid, hceApps);
409     if (hceApps.empty()) {
410         InfoLog("No applications found");
411         return;
412     }
413     // only one element, resolved
414     if (hceApps.size() == 1) {
415         ElementName element = hceApps[0].element;
416         aidElement.SetBundleName(element.GetBundleName());
417         aidElement.SetAbilityName(element.GetAbilityName());
418         return;
419     }
420     InfoLog("Found too many applications");
421     for (const AppDataParser::HceAppAidInfo &hceApp : hceApps) {
422         ElementName elementName = hceApp.element;
423         InfoLog("ElementName: %{public}s", elementName.GetBundleName().c_str());
424         InfoLog("ElementValue: %{public}s", elementName.GetAbilityName().c_str());
425 
426         bool isForeground = elementName.GetBundleName() == foregroundElement_.GetBundleName() &&
427                            elementName.GetAbilityName() == foregroundElement_.GetAbilityName();
428         bool isDefaultPayment = elementName.GetBundleName() == defaultPaymentElement_.GetBundleName() &&
429                                 elementName.GetAbilityName() == defaultPaymentElement_.GetAbilityName();
430         if (isForeground) {
431             // is foregroud, resolved
432             InfoLog("is foreground element");
433             aidElement.SetBundleName(elementName.GetBundleName());
434             aidElement.SetAbilityName(elementName.GetAbilityName());
435             return;
436         } else if (isDefaultPayment && IsPaymentAid(aid, hceApp)) {
437             // is default payment, resolved
438             InfoLog("is default payment element");
439             aidElement.SetBundleName(elementName.GetBundleName());
440             aidElement.SetAbilityName(elementName.GetAbilityName());
441             return;
442         }
443     }
444 
445     HandleOtherAidConflicted(hceApps);
446     InfoLog("SearchElementByAid end.");
447 }
HandleOtherAidConflicted(const std::vector<AppDataParser::HceAppAidInfo> & hceApps)448 void CeService::HandleOtherAidConflicted(const std::vector<AppDataParser::HceAppAidInfo> &hceApps)
449 {
450     InfoLog("too many applications found, let user decide.");
451     TAG::NfcNotificationId notificationId = TAG::NFC_HCE_AID_CONFLICTED_ID;
452     ExternalDepsProxy::GetInstance().PublishNfcNotification(notificationId, "", 0);
453 }
454 
UpdateDefaultPaymentType()455 bool CeService::UpdateDefaultPaymentType()
456 {
457     KITS::DefaultPaymentType defaultPaymentType = GetDefaultPaymentType();
458     InfoLog("The last default payment type %{public}d, the new one %{public}d.", defaultPaymentType_,
459             defaultPaymentType);
460     if (defaultPaymentType == defaultPaymentType_) {
461         return false;
462     }
463     std::lock_guard<std::mutex> lock(configRoutingMutex_);
464     ExternalDepsProxy::GetInstance().WriteDefaultRouteChangeHiSysEvent(
465         static_cast<int>(defaultPaymentType_), static_cast<int>(defaultPaymentType));
466     defaultPaymentType_ = defaultPaymentType;
467     NotifyDefaultPaymentType(static_cast<int>(defaultPaymentType_));
468     return true;
469 }
470 
IsPaymentAid(const std::string & aid,const AppDataParser::HceAppAidInfo & hceApp)471 bool CeService::IsPaymentAid(const std::string &aid, const AppDataParser::HceAppAidInfo &hceApp)
472 {
473     for (const AppDataParser::AidInfo &aidInfo : hceApp.customDataAid) {
474         if (KITS::KEY_PAYMENT_AID == aidInfo.name && aid == aidInfo.value) {
475             return true;
476         }
477     }
478     return false;
479 }
480 
HandleFieldActivated()481 void CeService::HandleFieldActivated()
482 {
483     if (nfcService_.expired() || nfcService_.lock()->eventHandler_ == nullptr) {
484         return;
485     }
486     nfcService_.lock()->eventHandler_->RemoveEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF));
487     nfcService_.lock()->eventHandler_->RemoveEvent(
488         static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF_TIMEOUT));
489     nfcService_.lock()->eventHandler_->SendEvent(
490         static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF_TIMEOUT), DEACTIVATE_TIMEOUT);
491 
492     uint64_t currentTime = KITS::NfcSdkCommon::GetRelativeTime();
493     if (currentTime < lastFieldOnTime_) {
494         WarnLog("currentTime = %{public}lu, lastFieldOnTime_ = %{public}lu", currentTime, lastFieldOnTime_);
495         lastFieldOnTime_ = 0;
496         return;
497     }
498     if (currentTime - lastFieldOnTime_ > FIELD_COMMON_EVENT_INTERVAL) {
499         lastFieldOnTime_ = currentTime;
500         nfcService_.lock()->eventHandler_->SendEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_ON));
501     }
502 }
503 
HandleFieldDeactivated()504 void CeService::HandleFieldDeactivated()
505 {
506     if (nfcService_.expired() || nfcService_.lock()->eventHandler_ == nullptr) {
507         return;
508     }
509     nfcService_.lock()->eventHandler_->RemoveEvent(
510         static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF_TIMEOUT));
511     nfcService_.lock()->eventHandler_->RemoveEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF));
512 
513     uint64_t currentTime = KITS::NfcSdkCommon::GetRelativeTime();
514     if (currentTime < lastFieldOffTime_) {
515         WarnLog("currentTime = %{public}lu, lastFieldOffTime_ = %{public}lu", currentTime, lastFieldOffTime_);
516         lastFieldOffTime_ = 0;
517         return;
518     }
519     if (currentTime - lastFieldOffTime_ > FIELD_COMMON_EVENT_INTERVAL) {
520         lastFieldOffTime_ = currentTime;
521         nfcService_.lock()->eventHandler_->SendEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF),
522                                                      FIELD_COMMON_EVENT_INTERVAL);
523     }
524 }
OnCardEmulationData(const std::vector<uint8_t> & data)525 void CeService::OnCardEmulationData(const std::vector<uint8_t> &data)
526 {
527     if (hostCardEmulationManager_ == nullptr) {
528         ErrorLog("hce is null");
529         return;
530     }
531     hostCardEmulationManager_->OnHostCardEmulationDataNfcA(data);
532 }
OnCardEmulationActivated()533 void CeService::OnCardEmulationActivated()
534 {
535     if (hostCardEmulationManager_ == nullptr) {
536         ErrorLog("hce is null");
537         return;
538     }
539     hostCardEmulationManager_->OnCardEmulationActivated();
540 }
OnCardEmulationDeactivated()541 void CeService::OnCardEmulationDeactivated()
542 {
543     if (hostCardEmulationManager_ == nullptr) {
544         ErrorLog("hce is null");
545         return;
546     }
547     hostCardEmulationManager_->OnCardEmulationDeactivated();
548 }
AsObject()549 OHOS::sptr<OHOS::IRemoteObject> CeService::AsObject()
550 {
551     return nullptr;
552 }
Initialize()553 void CeService::Initialize()
554 {
555     DebugLog("CeService Initialize start");
556     dataRdbObserver_ = sptr<DefaultPaymentServiceChangeCallback>(
557         new (std::nothrow) DefaultPaymentServiceChangeCallback(shared_from_this()));
558     InitDefaultPaymentApp();
559     defaultPaymentType_ = GetDefaultPaymentType();
560     ExternalDepsProxy::GetInstance().WriteDefaultRouteChangeHiSysEvent(
561         static_cast<int>(KITS::DefaultPaymentType::TYPE_UNKNOWN), static_cast<int>(defaultPaymentType_));
562     NotifyDefaultPaymentType(static_cast<int>(defaultPaymentType_));
563     if (hostCardEmulationManager_ == nullptr) {
564         InfoLog("CeService Initialize make_shared hostCardEmulationManager_");
565         hostCardEmulationManager_ =
566             std::make_shared<HostCardEmulationManager>(nfcService_, nciCeProxy_, shared_from_this());
567     }
568     DebugLog("CeService Initialize end");
569 }
570 
InitDefaultPaymentApp()571 bool CeService::InitDefaultPaymentApp()
572 {
573     std::lock_guard<std::mutex> lock(g_defaultPaymentAppInitMutex);
574     if (initDefaultPaymentAppDone_) {
575         WarnLog("InitDefaultPaymentApp: already done");
576         return false;
577     }
578     Uri nfcDefaultPaymentApp(KITS::NFC_DATA_URI_PAYMENT_DEFAULT_APP);
579     KITS::ErrorCode registerResult = DelayedSingleton<SettingDataShareImpl>::GetInstance()->
580         RegisterDataObserver(nfcDefaultPaymentApp, dataRdbObserver_);
581     if (registerResult != KITS::ERR_NONE) {
582         initDefaultPaymentAppDone_ = false;
583         ErrorLog("register default payment app failed");
584         return false;
585     }
586     DelayedSingleton<SettingDataShareImpl>::GetInstance()->GetElementName(
587         nfcDefaultPaymentApp, KITS::DATA_SHARE_KEY_NFC_PAYMENT_DEFAULT_APP, defaultPaymentElement_);
588     defaultPaymentBundleInstalled_ =
589         ExternalDepsProxy::GetInstance().IsBundleInstalled(defaultPaymentElement_.GetBundleName());
590 
591     std::string appStatus = defaultPaymentBundleInstalled_ ? APP_ADDED : APP_REMOVED;
592     ExternalDepsProxy::GetInstance().WriteDefaultPaymentAppChangeHiSysEvent(defaultPaymentElement_.GetBundleName(),
593                                                                             appStatus);
594     initDefaultPaymentAppDone_ = true;
595     return true;
596 }
597 
Deinitialize()598 void CeService::Deinitialize()
599 {
600     DebugLog("CeService Deinitialize start");
601     ClearAidEntriesCache();
602     foregroundElement_.SetBundleName("");
603     foregroundElement_.SetAbilityName("");
604     foregroundElement_.SetDeviceID("");
605     foregroundElement_.SetModuleName("");
606     defaultPaymentElement_.SetBundleName("");
607     defaultPaymentElement_.SetAbilityName("");
608     defaultPaymentElement_.SetDeviceID("");
609     defaultPaymentElement_.SetModuleName("");
610     initDefaultPaymentAppDone_ = false;
611     dynamicAids_.clear();
612     Uri nfcDefaultPaymentApp(KITS::NFC_DATA_URI_PAYMENT_DEFAULT_APP);
613     DelayedSingleton<SettingDataShareImpl>::GetInstance()->ReleaseDataObserver(nfcDefaultPaymentApp,
614                                                                                dataRdbObserver_);
615     DebugLog("CeService Deinitialize end");
616 }
617 
StartHce(const ElementName & element,const std::vector<std::string> & aids)618 bool CeService::StartHce(const ElementName &element, const std::vector<std::string> &aids)
619 {
620     if (nfcService_.expired()) {
621         ErrorLog("nfcService_ is nullptr.");
622         return false;
623     }
624     if (!nfcService_.lock()->IsNfcEnabled()) {
625         ErrorLog("NFC not enabled, should not happen.");
626         return false;
627     }
628     SetHceInfo(element, aids);
629     InfoLog("StartHce: refresh route table");
630     ConfigRoutingAndCommit();
631     return true;
632 }
633 
SetHceInfo(const ElementName & element,const std::vector<std::string> & aids)634 void CeService::SetHceInfo(const ElementName &element, const std::vector<std::string> &aids)
635 {
636     InfoLog("SetHceInfo start.");
637     std::lock_guard<std::mutex> lock(configRoutingMutex_);
638     foregroundElement_ = element;
639     ExternalDepsProxy::GetInstance().WriteForegroundAppChangeHiSysEvent(foregroundElement_.GetBundleName());
640     dynamicAids_.clear();
641     dynamicAids_ = std::move(aids);
642 }
643 
ClearHceInfo()644 void CeService::ClearHceInfo()
645 {
646     InfoLog("ClearHceInfo start.");
647     std::lock_guard<std::mutex> lock(configRoutingMutex_);
648     foregroundElement_.SetBundleName("");
649     foregroundElement_.SetAbilityName("");
650     foregroundElement_.SetDeviceID("");
651     foregroundElement_.SetModuleName("");
652     ExternalDepsProxy::GetInstance().WriteForegroundAppChangeHiSysEvent(foregroundElement_.GetBundleName());
653     dynamicAids_.clear();
654 }
655 
StopHce(const ElementName & element,Security::AccessToken::AccessTokenID callerToken)656 bool CeService::StopHce(const ElementName &element, Security::AccessToken::AccessTokenID callerToken)
657 {
658     bool isForegroud = element.GetBundleName() == foregroundElement_.GetBundleName() &&
659                        element.GetAbilityName() == foregroundElement_.GetAbilityName();
660     if (isForegroud) {
661         ClearHceInfo();
662         InfoLog("StopHce: refresh route table");
663         ConfigRoutingAndCommit();
664     }
665     return hostCardEmulationManager_->UnRegAllCallback(callerToken);
666 }
667 
HandleWhenRemoteDie(Security::AccessToken::AccessTokenID callerToken)668 bool CeService::HandleWhenRemoteDie(Security::AccessToken::AccessTokenID callerToken)
669 {
670     Security::AccessToken::HapTokenInfo hapTokenInfo;
671     int result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(callerToken, hapTokenInfo);
672 
673     InfoLog("get hap token info, result = %{public}d", result);
674     if (result) {
675         return false;
676     }
677     if (hapTokenInfo.bundleName.empty()) {
678         ErrorLog("HandleWhenRemoteDie: not got bundle name");
679         return false;
680     }
681 
682     bool isForegroud = hapTokenInfo.bundleName == foregroundElement_.GetBundleName();
683     if (isForegroud) {
684         ClearHceInfo();
685         InfoLog("remote die: refresh route table");
686         ConfigRoutingAndCommit();
687     }
688     return hostCardEmulationManager_->UnRegAllCallback(callerToken);
689 }
690 
NotifyDefaultPaymentType(int paymentType)691 void CeService::NotifyDefaultPaymentType(int paymentType)
692 {
693     InfoLog("NotifyDefaultPaymentType: %{public}d", paymentType);
694     if (nciCeProxy_.expired()) {
695         ErrorLog("NotifyDefaultPaymentType: nciCeProxy_ is nullptr.");
696         return;
697     }
698     nciCeProxy_.lock()->NotifyDefaultPaymentType(paymentType);
699 }
700 
HandleDataShareReady()701 void CeService::HandleDataShareReady()
702 {
703     // when bundle manager init done, when recv the event of dataShareReady;
704     // app list and default payment app need to get from bundle manager, need init if not been initialized.
705     InfoLog("HandleDataShareReady: Init app list and DefaultPayment App");
706     ExternalDepsProxy::GetInstance().InitAppList();
707     if (InitDefaultPaymentApp()) {
708         ConfigRoutingAndCommit();
709     }
710 }
711 } // namespace NFC
712 } // namespace OHOS