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