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 (defaultPaymentElement_.GetBundleName() == nciCeProxy_.lock()->GetSimVendorBundleName()) {
355 return KITS::DefaultPaymentType::TYPE_UICC;
356 }
357 if (ExternalDepsProxy::GetInstance().IsHceApp(defaultPaymentElement_)) {
358 return KITS::DefaultPaymentType::TYPE_HCE;
359 }
360
361 return KITS::DefaultPaymentType::TYPE_ESE;
362 }
363
ConfigRoutingAndCommit()364 void CeService::ConfigRoutingAndCommit()
365 {
366 if (nfcService_.expired()) {
367 ErrorLog("ConfigRoutingAndCommit: nfc service is null");
368 return;
369 }
370 std::weak_ptr<NfcRoutingManager> routingManager = nfcService_.lock()->GetNfcRoutingManager();
371 if (routingManager.expired()) {
372 ErrorLog("ConfigRoutingAndCommit: routing manager is null");
373 return;
374 }
375
376 bool updateAids = false;
377 bool updatePaymentType = UpdateDefaultPaymentType();
378 if (updatePaymentType) {
379 updateAids = InitConfigAidRouting(true);
380 } else {
381 updateAids = InitConfigAidRouting(false);
382 }
383
384 InfoLog(
385 "ConfigRoutingAndCommit: aids updated status %{public}d, default payment type updated status %{public}d.",
386 updateAids, updatePaymentType);
387 if (updateAids || updatePaymentType) {
388 routingManager.lock()->ComputeRoutingParams(defaultPaymentType_);
389 routingManager.lock()->CommitRouting();
390 }
391 }
392
SearchElementByAid(const std::string & aid,ElementName & aidElement)393 void CeService::SearchElementByAid(const std::string &aid, ElementName &aidElement)
394 {
395 if (aid.empty()) {
396 InfoLog("aid is empty");
397 return;
398 }
399 // find dynamic aid
400 if (IsDynamicAid(aid) && !foregroundElement_.GetBundleName().empty()) {
401 InfoLog("is foreground element");
402 aidElement.SetBundleName(foregroundElement_.GetBundleName());
403 aidElement.SetAbilityName(foregroundElement_.GetAbilityName());
404 return;
405 }
406 std::vector<AppDataParser::HceAppAidInfo> hceApps;
407 ExternalDepsProxy::GetInstance().GetHceAppsByAid(aid, hceApps);
408 if (hceApps.empty()) {
409 InfoLog("No applications found");
410 return;
411 }
412 // only one element, resolved
413 if (hceApps.size() == 1) {
414 ElementName element = hceApps[0].element;
415 aidElement.SetBundleName(element.GetBundleName());
416 aidElement.SetAbilityName(element.GetAbilityName());
417 return;
418 }
419 InfoLog("Found too many applications");
420 for (const AppDataParser::HceAppAidInfo &hceApp : hceApps) {
421 ElementName elementName = hceApp.element;
422 InfoLog("ElementName: %{public}s", elementName.GetBundleName().c_str());
423 InfoLog("ElementValue: %{public}s", elementName.GetAbilityName().c_str());
424
425 bool isForeground = elementName.GetBundleName() == foregroundElement_.GetBundleName() &&
426 elementName.GetAbilityName() == foregroundElement_.GetAbilityName();
427 bool isDefaultPayment = elementName.GetBundleName() == defaultPaymentElement_.GetBundleName() &&
428 elementName.GetAbilityName() == defaultPaymentElement_.GetAbilityName();
429 if (isForeground) {
430 // is foregroud, resolved
431 InfoLog("is foreground element");
432 aidElement.SetBundleName(elementName.GetBundleName());
433 aidElement.SetAbilityName(elementName.GetAbilityName());
434 return;
435 } else if (isDefaultPayment && IsPaymentAid(aid, hceApp)) {
436 // is default payment, resolved
437 InfoLog("is default payment element");
438 aidElement.SetBundleName(elementName.GetBundleName());
439 aidElement.SetAbilityName(elementName.GetAbilityName());
440 return;
441 }
442 }
443
444 HandleOtherAidConflicted(hceApps);
445 InfoLog("SearchElementByAid end.");
446 }
HandleOtherAidConflicted(const std::vector<AppDataParser::HceAppAidInfo> & hceApps)447 void CeService::HandleOtherAidConflicted(const std::vector<AppDataParser::HceAppAidInfo> &hceApps)
448 {
449 InfoLog("too many applications found, let user decide.");
450 TAG::NfcNotificationId notificationId = TAG::NFC_HCE_AID_CONFLICTED_ID;
451 ExternalDepsProxy::GetInstance().PublishNfcNotification(notificationId, "", 0);
452 }
453
UpdateDefaultPaymentType()454 bool CeService::UpdateDefaultPaymentType()
455 {
456 KITS::DefaultPaymentType defaultPaymentType = GetDefaultPaymentType();
457 InfoLog("The last default payment type %{public}d, the new one %{public}d.", defaultPaymentType_,
458 defaultPaymentType);
459 if (defaultPaymentType == defaultPaymentType_) {
460 return false;
461 }
462 std::lock_guard<std::mutex> lock(configRoutingMutex_);
463 ExternalDepsProxy::GetInstance().WriteDefaultRouteChangeHiSysEvent(
464 static_cast<int>(defaultPaymentType_), static_cast<int>(defaultPaymentType));
465 defaultPaymentType_ = defaultPaymentType;
466 NotifyDefaultPaymentType(static_cast<int>(defaultPaymentType_));
467 return true;
468 }
469
IsPaymentAid(const std::string & aid,const AppDataParser::HceAppAidInfo & hceApp)470 bool CeService::IsPaymentAid(const std::string &aid, const AppDataParser::HceAppAidInfo &hceApp)
471 {
472 for (const AppDataParser::AidInfo &aidInfo : hceApp.customDataAid) {
473 if (KITS::KEY_PAYMENT_AID == aidInfo.name && aid == aidInfo.value) {
474 return true;
475 }
476 }
477 return false;
478 }
479
HandleFieldActivated()480 void CeService::HandleFieldActivated()
481 {
482 if (nfcService_.expired() || nfcService_.lock()->eventHandler_ == nullptr) {
483 return;
484 }
485 nfcService_.lock()->eventHandler_->RemoveEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF));
486 nfcService_.lock()->eventHandler_->RemoveEvent(
487 static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF_TIMEOUT));
488 nfcService_.lock()->eventHandler_->SendEvent(
489 static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF_TIMEOUT), DEACTIVATE_TIMEOUT);
490
491 uint64_t currentTime = KITS::NfcSdkCommon::GetRelativeTime();
492 if (currentTime < lastFieldOnTime_) {
493 WarnLog("currentTime = %{public}lu, lastFieldOnTime_ = %{public}lu", currentTime, lastFieldOnTime_);
494 lastFieldOnTime_ = 0;
495 return;
496 }
497 if (currentTime - lastFieldOnTime_ > FIELD_COMMON_EVENT_INTERVAL) {
498 lastFieldOnTime_ = currentTime;
499 nfcService_.lock()->eventHandler_->SendEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_ON));
500 }
501 }
502
HandleFieldDeactivated()503 void CeService::HandleFieldDeactivated()
504 {
505 if (nfcService_.expired() || nfcService_.lock()->eventHandler_ == nullptr) {
506 return;
507 }
508 nfcService_.lock()->eventHandler_->RemoveEvent(
509 static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF_TIMEOUT));
510 nfcService_.lock()->eventHandler_->RemoveEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF));
511
512 uint64_t currentTime = KITS::NfcSdkCommon::GetRelativeTime();
513 if (currentTime < lastFieldOffTime_) {
514 WarnLog("currentTime = %{public}lu, lastFieldOffTime_ = %{public}lu", currentTime, lastFieldOffTime_);
515 lastFieldOffTime_ = 0;
516 return;
517 }
518 if (currentTime - lastFieldOffTime_ > FIELD_COMMON_EVENT_INTERVAL) {
519 lastFieldOffTime_ = currentTime;
520 nfcService_.lock()->eventHandler_->SendEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF),
521 FIELD_COMMON_EVENT_INTERVAL);
522 }
523 }
OnCardEmulationData(const std::vector<uint8_t> & data)524 void CeService::OnCardEmulationData(const std::vector<uint8_t> &data)
525 {
526 if (hostCardEmulationManager_ == nullptr) {
527 ErrorLog("hce is null");
528 return;
529 }
530 hostCardEmulationManager_->OnHostCardEmulationDataNfcA(data);
531 }
OnCardEmulationActivated()532 void CeService::OnCardEmulationActivated()
533 {
534 if (hostCardEmulationManager_ == nullptr) {
535 ErrorLog("hce is null");
536 return;
537 }
538 hostCardEmulationManager_->OnCardEmulationActivated();
539 }
OnCardEmulationDeactivated()540 void CeService::OnCardEmulationDeactivated()
541 {
542 if (hostCardEmulationManager_ == nullptr) {
543 ErrorLog("hce is null");
544 return;
545 }
546 hostCardEmulationManager_->OnCardEmulationDeactivated();
547 }
AsObject()548 OHOS::sptr<OHOS::IRemoteObject> CeService::AsObject()
549 {
550 return nullptr;
551 }
Initialize()552 void CeService::Initialize()
553 {
554 DebugLog("CeService Initialize start");
555 dataRdbObserver_ = sptr<DefaultPaymentServiceChangeCallback>(
556 new (std::nothrow) DefaultPaymentServiceChangeCallback(shared_from_this()));
557 InitDefaultPaymentApp();
558 defaultPaymentType_ = GetDefaultPaymentType();
559 ExternalDepsProxy::GetInstance().WriteDefaultRouteChangeHiSysEvent(
560 static_cast<int>(KITS::DefaultPaymentType::TYPE_UNKNOWN), static_cast<int>(defaultPaymentType_));
561 NotifyDefaultPaymentType(static_cast<int>(defaultPaymentType_));
562 hostCardEmulationManager_ =
563 std::make_shared<HostCardEmulationManager>(nfcService_, nciCeProxy_, shared_from_this());
564 DebugLog("CeService Initialize end");
565 }
566
InitDefaultPaymentApp()567 bool CeService::InitDefaultPaymentApp()
568 {
569 std::lock_guard<std::mutex> lock(g_defaultPaymentAppInitMutex);
570 if (initDefaultPaymentAppDone_) {
571 WarnLog("InitDefaultPaymentApp: already done");
572 return false;
573 }
574 Uri nfcDefaultPaymentApp(KITS::NFC_DATA_URI_PAYMENT_DEFAULT_APP);
575 KITS::ErrorCode registerResult = DelayedSingleton<SettingDataShareImpl>::GetInstance()->
576 RegisterDataObserver(nfcDefaultPaymentApp, dataRdbObserver_);
577 if (registerResult != KITS::ERR_NONE) {
578 initDefaultPaymentAppDone_ = false;
579 ErrorLog("register default payment app failed");
580 return false;
581 }
582 DelayedSingleton<SettingDataShareImpl>::GetInstance()->GetElementName(
583 nfcDefaultPaymentApp, KITS::DATA_SHARE_KEY_NFC_PAYMENT_DEFAULT_APP, defaultPaymentElement_);
584 defaultPaymentBundleInstalled_ =
585 ExternalDepsProxy::GetInstance().IsBundleInstalled(defaultPaymentElement_.GetBundleName());
586
587 std::string appStatus = defaultPaymentBundleInstalled_ ? APP_ADDED : APP_REMOVED;
588 ExternalDepsProxy::GetInstance().WriteDefaultPaymentAppChangeHiSysEvent(defaultPaymentElement_.GetBundleName(),
589 appStatus);
590 initDefaultPaymentAppDone_ = true;
591 return true;
592 }
593
Deinitialize()594 void CeService::Deinitialize()
595 {
596 DebugLog("CeService Deinitialize start");
597 ClearAidEntriesCache();
598 foregroundElement_.SetBundleName("");
599 foregroundElement_.SetAbilityName("");
600 foregroundElement_.SetDeviceID("");
601 foregroundElement_.SetModuleName("");
602 defaultPaymentElement_.SetBundleName("");
603 defaultPaymentElement_.SetAbilityName("");
604 defaultPaymentElement_.SetDeviceID("");
605 defaultPaymentElement_.SetModuleName("");
606 initDefaultPaymentAppDone_ = false;
607 dynamicAids_.clear();
608 Uri nfcDefaultPaymentApp(KITS::NFC_DATA_URI_PAYMENT_DEFAULT_APP);
609 DelayedSingleton<SettingDataShareImpl>::GetInstance()->ReleaseDataObserver(nfcDefaultPaymentApp,
610 dataRdbObserver_);
611 DebugLog("CeService Deinitialize end");
612 }
613
StartHce(const ElementName & element,const std::vector<std::string> & aids)614 bool CeService::StartHce(const ElementName &element, const std::vector<std::string> &aids)
615 {
616 if (nfcService_.expired()) {
617 ErrorLog("nfcService_ is nullptr.");
618 return false;
619 }
620 if (!nfcService_.lock()->IsNfcEnabled()) {
621 ErrorLog("NFC not enabled, should not happen.");
622 return false;
623 }
624 SetHceInfo(element, aids);
625 InfoLog("StartHce: refresh route table");
626 ConfigRoutingAndCommit();
627 return true;
628 }
629
SetHceInfo(const ElementName & element,const std::vector<std::string> & aids)630 void CeService::SetHceInfo(const ElementName &element, const std::vector<std::string> &aids)
631 {
632 InfoLog("SetHceInfo start.");
633 std::lock_guard<std::mutex> lock(configRoutingMutex_);
634 foregroundElement_ = element;
635 ExternalDepsProxy::GetInstance().WriteForegroundAppChangeHiSysEvent(foregroundElement_.GetBundleName());
636 dynamicAids_.clear();
637 dynamicAids_ = std::move(aids);
638 }
639
ClearHceInfo()640 void CeService::ClearHceInfo()
641 {
642 InfoLog("ClearHceInfo start.");
643 std::lock_guard<std::mutex> lock(configRoutingMutex_);
644 foregroundElement_.SetBundleName("");
645 foregroundElement_.SetAbilityName("");
646 foregroundElement_.SetDeviceID("");
647 foregroundElement_.SetModuleName("");
648 ExternalDepsProxy::GetInstance().WriteForegroundAppChangeHiSysEvent(foregroundElement_.GetBundleName());
649 dynamicAids_.clear();
650 }
651
StopHce(const ElementName & element,Security::AccessToken::AccessTokenID callerToken)652 bool CeService::StopHce(const ElementName &element, Security::AccessToken::AccessTokenID callerToken)
653 {
654 bool isForegroud = element.GetBundleName() == foregroundElement_.GetBundleName() &&
655 element.GetAbilityName() == foregroundElement_.GetAbilityName();
656 if (isForegroud) {
657 ClearHceInfo();
658 InfoLog("StopHce: refresh route table");
659 ConfigRoutingAndCommit();
660 }
661 return hostCardEmulationManager_->UnRegAllCallback(callerToken);
662 }
663
HandleWhenRemoteDie(Security::AccessToken::AccessTokenID callerToken)664 bool CeService::HandleWhenRemoteDie(Security::AccessToken::AccessTokenID callerToken)
665 {
666 Security::AccessToken::HapTokenInfo hapTokenInfo;
667 int result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(callerToken, hapTokenInfo);
668
669 InfoLog("get hap token info, result = %{public}d", result);
670 if (result) {
671 return false;
672 }
673 if (hapTokenInfo.bundleName.empty()) {
674 ErrorLog("HandleWhenRemoteDie: not got bundle name");
675 return false;
676 }
677
678 bool isForegroud = hapTokenInfo.bundleName == foregroundElement_.GetBundleName();
679 if (isForegroud) {
680 ClearHceInfo();
681 InfoLog("remote die: refresh route table");
682 ConfigRoutingAndCommit();
683 }
684 return hostCardEmulationManager_->UnRegAllCallback(callerToken);
685 }
686
NotifyDefaultPaymentType(int paymentType)687 void CeService::NotifyDefaultPaymentType(int paymentType)
688 {
689 InfoLog("NotifyDefaultPaymentType: %{public}d", paymentType);
690 if (nciCeProxy_.expired()) {
691 ErrorLog("NotifyDefaultPaymentType: nciCeProxy_ is nullptr.");
692 return;
693 }
694 nciCeProxy_.lock()->NotifyDefaultPaymentType(paymentType);
695 }
696
HandleDataShareReady()697 void CeService::HandleDataShareReady()
698 {
699 // when bundle manager init done, when recv the event of dataShareReady;
700 // app list and default payment app need to get from bundle manager, need init if not been initialized.
701 InfoLog("HandleDataShareReady: Init app list and DefaultPayment App");
702 ExternalDepsProxy::GetInstance().InitAppList();
703 if (InitDefaultPaymentApp()) {
704 ConfigRoutingAndCommit();
705 }
706 }
707 } // namespace NFC
708 } // namespace OHOS