• 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 
23 namespace OHOS {
24 namespace NFC {
25 const int FIELD_COMMON_EVENT_INTERVAL = 1000;
26 const int DEACTIVATE_TIMEOUT = 6000;
27 static const int DEFAULT_HOST_ROUTE_DEST = 0x00;
28 static const int PWR_STA_SWTCH_ON_SCRN_UNLCK = 0x01;
29 static const int DEFAULT_PWR_STA_HOST = PWR_STA_SWTCH_ON_SCRN_UNLCK;
30 
CeService(std::weak_ptr<NfcService> nfcService,std::weak_ptr<NCI::INciCeInterface> nciCeProxy)31 CeService::CeService(std::weak_ptr<NfcService> nfcService, std::weak_ptr<NCI::INciCeInterface> nciCeProxy)
32     : nfcService_(nfcService),
33       nciCeProxy_(nciCeProxy),
34       hostCardEmulationManager_(std::make_shared<HostCardEmulationManager>(nfcService, nciCeProxy))
35 {
36     Uri nfcDefaultPaymentApp(KITS::NFC_DATA_URI_PAYMENT_DEFAULT_APP);
37     DelayedSingleton<SettingDataShareImpl>::GetInstance()->GetElementName(
38         nfcDefaultPaymentApp, KITS::DATA_SHARE_KEY_NFC_PAYMENT_DEFAULT_APP, defaultPaymentElement_);
39     DebugLog("CeService constructor end");
40 }
41 
~CeService()42 CeService::~CeService()
43 {
44     hostCardEmulationManager_ = nullptr;
45     aidToAidEntry_.clear();
46     DebugLog("CeService deconstructor end");
47 }
48 
PublishFieldOnOrOffCommonEvent(bool isFieldOn)49 void CeService::PublishFieldOnOrOffCommonEvent(bool isFieldOn)
50 {
51     ExternalDepsProxy::GetInstance().PublishNfcFieldStateChanged(isFieldOn);
52 }
53 
RegHceCmdCallback(const sptr<KITS::IHceCmdCallback> & callback,const std::string & type,Security::AccessToken::AccessTokenID callerToken)54 bool CeService::RegHceCmdCallback(const sptr<KITS::IHceCmdCallback> &callback, const std::string &type,
55                                   Security::AccessToken::AccessTokenID callerToken)
56 {
57     return hostCardEmulationManager_->RegHceCmdCallback(callback, type, callerToken);
58 }
59 
UnRegHceCmdCallback(const std::string & type,Security::AccessToken::AccessTokenID callerToken)60 bool CeService::UnRegHceCmdCallback(const std::string &type, Security::AccessToken::AccessTokenID callerToken)
61 {
62     return hostCardEmulationManager_->UnRegHceCmdCallback(type, callerToken);
63 }
64 
UnRegAllCallback(Security::AccessToken::AccessTokenID callerToken)65 bool CeService::UnRegAllCallback(Security::AccessToken::AccessTokenID callerToken)
66 {
67     return hostCardEmulationManager_->UnRegAllCallback(callerToken);
68 }
69 
IsDefaultService(ElementName & element,const std::string & type)70 bool CeService::IsDefaultService(ElementName &element, const std::string &type)
71 {
72     return type == KITS::TYPE_PAYMENT && element.GetBundleName() == defaultPaymentElement_.GetBundleName() &&
73            element.GetAbilityName() == defaultPaymentElement_.GetAbilityName();
74 }
75 
SendHostApduData(const std::string & hexCmdData,bool raw,std::string & hexRespData,Security::AccessToken::AccessTokenID callerToken)76 bool CeService::SendHostApduData(const std::string &hexCmdData, bool raw, std::string &hexRespData,
77                                  Security::AccessToken::AccessTokenID callerToken)
78 {
79     return hostCardEmulationManager_->SendHostApduData(hexCmdData, raw, hexRespData, callerToken);
80 }
81 
InitConfigAidRouting()82 bool CeService::InitConfigAidRouting()
83 {
84     DebugLog("AddAidRoutingHceAids: start");
85     std::lock_guard<std::mutex> lock(configRoutingMutex_);
86     std::map<std::string, AidEntry> aidEntries;
87     BuildAidEntries(aidEntries);
88     InfoLog("AddAidRoutingHceAids, aid entries cache size %{public}zu,aid entries newly builded size %{public}zu",
89             aidToAidEntry_.size(), aidEntries.size());
90     if (aidEntries == aidToAidEntry_) {
91         InfoLog("aid entries do not change.");
92         return false;
93     }
94 
95     nciCeProxy_.lock()->ClearAidTable();
96     aidToAidEntry_.clear();
97     bool addAllResult = true;
98     for (const auto &pair : aidEntries) {
99         AidEntry entry = pair.second;
100         std::string aid = entry.aid;
101         int aidInfo = entry.aidInfo;
102         int power = entry.power;
103         int route = entry.route;
104         InfoLog("AddAidRoutingHceAids: aid= %{public}s, aidInfo= "
105                 "0x%{public}x, route=0x%{public}x, power=0x%{public}x",
106                 aid.c_str(), aidInfo, route, power);
107         bool addResult = nciCeProxy_.lock()->AddAidRouting(aid, route, aidInfo, power);
108         if (!addResult) {
109             ErrorLog("AddAidRoutingHceAids: add aid failed aid= %{public}s", aid.c_str());
110             addAllResult = false;
111         }
112     }
113     if (addAllResult) {
114         InfoLog("AddAidRoutingHceAids: add aids success, update the aid entries cache");
115         aidToAidEntry_ = std::move(aidEntries);
116     }
117     DebugLog("AddAidRoutingHceAids: end");
118     return true;
119 }
120 
BuildAidEntries(std::map<std::string,AidEntry> & aidEntries)121 void CeService::BuildAidEntries(std::map<std::string, AidEntry> &aidEntries)
122 {
123     std::vector<AppDataParser::HceAppAidInfo> hceApps;
124     ExternalDepsProxy::GetInstance().GetHceApps(hceApps);
125     InfoLog("AddAidRoutingHceOtherAids: hce apps size %{public}zu", hceApps.size());
126     for (const AppDataParser::HceAppAidInfo &appAidInfo : hceApps) {
127         bool isDefaultPayment = appAidInfo.element.GetBundleName() == defaultPaymentElement_.GetBundleName() &&
128                                 appAidInfo.element.GetAbilityName() == defaultPaymentElement_.GetAbilityName();
129         for (const AppDataParser::AidInfo &aidInfo : appAidInfo.customDataAid) {
130             // add payment aid of default payment app and other aid of all apps
131             bool shouldAdd = KITS::KEY_OHTER_AID == aidInfo.name || isDefaultPayment;
132             if (shouldAdd) {
133                 AidEntry aidEntry;
134                 aidEntry.aid = aidInfo.value;
135                 aidEntry.aidInfo = 0;
136                 aidEntry.power = DEFAULT_PWR_STA_HOST;
137                 aidEntry.route = DEFAULT_HOST_ROUTE_DEST;
138                 aidEntries[aidInfo.value] = aidEntry;
139             }
140         }
141     }
142 }
143 
ClearAidEntriesCache()144 void CeService::ClearAidEntriesCache()
145 {
146     std::lock_guard<std::mutex> lock(configRoutingMutex_);
147     aidToAidEntry_.clear();
148     DebugLog("ClearAidEntriesCache end");
149 }
150 
OnDefaultPaymentServiceChange()151 void CeService::OnDefaultPaymentServiceChange()
152 {
153     ElementName newElement;
154     Uri nfcDefaultPaymentApp(KITS::NFC_DATA_URI_PAYMENT_DEFAULT_APP);
155     DelayedSingleton<SettingDataShareImpl>::GetInstance()->GetElementName(
156         nfcDefaultPaymentApp, KITS::DATA_SHARE_KEY_NFC_PAYMENT_DEFAULT_APP, newElement);
157     if (newElement.GetURI() == defaultPaymentElement_.GetURI()) {
158         InfoLog("OnDefaultPaymentServiceChange: payment service not change");
159         return;
160     }
161 
162     if (nfcService_.expired()) {
163         ErrorLog("nfcService_ is nullptr.");
164         return;
165     }
166     if (!nfcService_.lock()->IsNfcEnabled()) {
167         ErrorLog("NFC not enabled, should not happen.The default payment app is be set when nfc is enabled.");
168         return;
169     }
170     ExternalDepsProxy::GetInstance().WriteDefaultPaymentAppChangeHiSysEvent(defaultPaymentElement_.GetBundleName(),
171                                                                             newElement.GetBundleName());
172     defaultPaymentElement_ = newElement;
173 
174     ConfigRoutingAndCommit();
175 }
OnAppAddOrChangeOrRemove(std::shared_ptr<EventFwk::CommonEventData> data)176 void CeService::OnAppAddOrChangeOrRemove(std::shared_ptr<EventFwk::CommonEventData> data)
177 {
178     DebugLog("OnAppAddOrChangeOrRemove start");
179     if (data == nullptr) {
180         ErrorLog("invalid event data");
181         return;
182     }
183     std::string action = data->GetWant().GetAction();
184     if (action.empty()) {
185         ErrorLog("action is empty");
186         return;
187     }
188     if ((action != EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED) &&
189         (action != EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED) &&
190         (action != EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED)) {
191         InfoLog("not the interested action");
192         return;
193     }
194 
195     ElementName element = data->GetWant().GetElement();
196     std::string bundleName = element.GetBundleName();
197     if (bundleName.empty()) {
198         ErrorLog("invalid bundleName.");
199         return;
200     }
201 
202     if (nfcService_.expired()) {
203         ErrorLog("nfcService_ is nullptr.");
204         return;
205     }
206     if (!nfcService_.lock()->IsNfcEnabled()) {
207         ErrorLog(" NFC not enabled, not need to update routing entry ");
208         return;
209     }
210     ConfigRoutingAndCommit();
211     DebugLog("OnAppAddOrChangeOrRemove end");
212 }
213 
ConfigRoutingAndCommit()214 void CeService::ConfigRoutingAndCommit()
215 {
216     if (nfcService_.expired()) {
217         ErrorLog("ConfigRoutingAndCommit: nfc service is null");
218         return;
219     }
220     std::weak_ptr<NfcRoutingManager> routingManager = nfcService_.lock()->GetNfcRoutingManager();
221     if (routingManager.expired()) {
222         ErrorLog("ConfigRoutingAndCommit: routing manager is null");
223         return;
224     }
225 
226     bool updateAids = InitConfigAidRouting();
227     if (updateAids) {
228         std::lock_guard<std::mutex> lock(configRoutingMutex_);
229         routingManager.lock()->ComputeRoutingParams();
230         routingManager.lock()->CommitRouting();
231     }
232 }
233 
HandleFieldActivated()234 void CeService::HandleFieldActivated()
235 {
236     if (nfcService_.expired() || nfcService_.lock()->eventHandler_ == nullptr) {
237         return;
238     }
239     nfcService_.lock()->eventHandler_->RemoveEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF));
240     nfcService_.lock()->eventHandler_->RemoveEvent(
241         static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF_TIMEOUT));
242     nfcService_.lock()->eventHandler_->SendEvent(
243         static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF_TIMEOUT), DEACTIVATE_TIMEOUT);
244 
245     uint64_t currentTime = KITS::NfcSdkCommon::GetCurrentTime();
246     if (currentTime - lastFieldOnTime_ > FIELD_COMMON_EVENT_INTERVAL) {
247         lastFieldOnTime_ = currentTime;
248         nfcService_.lock()->eventHandler_->SendEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_ON));
249     }
250 }
251 
HandleFieldDeactivated()252 void CeService::HandleFieldDeactivated()
253 {
254     if (nfcService_.expired() || nfcService_.lock()->eventHandler_ == nullptr) {
255         return;
256     }
257     nfcService_.lock()->eventHandler_->RemoveEvent(
258         static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF_TIMEOUT));
259     nfcService_.lock()->eventHandler_->RemoveEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF));
260 
261     uint64_t currentTime = KITS::NfcSdkCommon::GetCurrentTime();
262     if (currentTime - lastFieldOffTime_ > FIELD_COMMON_EVENT_INTERVAL) {
263         lastFieldOffTime_ = currentTime;
264         nfcService_.lock()->eventHandler_->SendEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_NOTIFY_FIELD_OFF),
265                                                      FIELD_COMMON_EVENT_INTERVAL);
266     }
267 }
OnCardEmulationData(const std::vector<uint8_t> & data)268 void CeService::OnCardEmulationData(const std::vector<uint8_t> &data)
269 {
270     hostCardEmulationManager_->OnHostCardEmulationDataNfcA(data);
271 }
OnCardEmulationActivated()272 void CeService::OnCardEmulationActivated()
273 {
274     hostCardEmulationManager_->OnCardEmulationActivated();
275 }
OnCardEmulationDeactivated()276 void CeService::OnCardEmulationDeactivated()
277 {
278     hostCardEmulationManager_->OnCardEmulationDeactivated();
279 }
AsObject()280 OHOS::sptr<OHOS::IRemoteObject> CeService::AsObject()
281 {
282     return nullptr;
283 }
Initialize()284 void CeService::Initialize()
285 {
286     DebugLog("CeService Initialize start");
287     dataRdbObserver_ = sptr<DefaultPaymentServiceChangeCallback>(
288         new (std::nothrow) DefaultPaymentServiceChangeCallback(shared_from_this()));
289     Uri nfcDefaultPaymentApp(KITS::NFC_DATA_URI_PAYMENT_DEFAULT_APP);
290     DelayedSingleton<SettingDataShareImpl>::GetInstance()->RegisterDataObserver(nfcDefaultPaymentApp,
291                                                                                 dataRdbObserver_);
292     DebugLog("CeService Initialize end");
293 }
Deinitialize()294 void CeService::Deinitialize()
295 {
296     DebugLog("CeService Deinitialize start");
297     ClearAidEntriesCache();
298     Uri nfcDefaultPaymentApp(KITS::NFC_DATA_URI_PAYMENT_DEFAULT_APP);
299     DelayedSingleton<SettingDataShareImpl>::GetInstance()->ReleaseDataObserver(nfcDefaultPaymentApp,
300                                                                                dataRdbObserver_);
301     DebugLog("CeService Deinitialize end");
302 }
303 } // namespace NFC
304 } // namespace OHOS