1 /*
2 * Copyright (c) 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
16 #define LOG_TAG "DataShareServiceImpl"
17
18 #include "data_share_service_impl.h"
19
20 #include <cstdint>
21 #include <utility>
22
23 #include "account/account_delegate.h"
24 #include "app_connect_manager.h"
25 #include "common_event_manager.h"
26 #include "common_event_support.h"
27 #include "concurrent_task_client.h"
28 #include "data_ability_observer_interface.h"
29 #include "data_share_profile_config.h"
30 #include "dataobs_mgr_client.h"
31 #include "datashare_errno.h"
32 #include "datashare_radar_reporter.h"
33 #include "device_manager_adapter.h"
34 #include "datashare_template.h"
35 #include "directory/directory_manager.h"
36 #include "eventcenter/event_center.h"
37 #include "extension_connect_adaptor.h"
38 #include "dump/dump_manager.h"
39 #include "extension_ability_manager.h"
40 #include "hap_token_info.h"
41 #include "hiview_adapter.h"
42 #include "if_system_ability_manager.h"
43 #include "ipc_skeleton.h"
44 #include "iservice_registry.h"
45 #include "log_print.h"
46 #include "common/uri_utils.h"
47 #include "metadata/auto_launch_meta_data.h"
48 #include "metadata/meta_data_manager.h"
49 #include "matching_skills.h"
50 #include "permit_delegate.h"
51 #include "rdb_helper.h"
52 #include "scheduler_manager.h"
53 #include "subscriber_managers/published_data_subscriber_manager.h"
54 #include "sys_event_subscriber.h"
55 #include "system_ability_definition.h"
56 #include "system_ability_status_change_stub.h"
57 #include "template_data.h"
58 #include "utils/anonymous.h"
59 #include "xcollie.h"
60 #include "log_debug.h"
61 #include "parameters.h"
62
63 namespace OHOS::DataShare {
64 using FeatureSystem = DistributedData::FeatureSystem;
65 using DumpManager = OHOS::DistributedData::DumpManager;
66 using ProviderInfo = DataProviderConfig::ProviderInfo;
67 using namespace OHOS::DistributedData;
68 __attribute__((used)) DataShareServiceImpl::Factory DataShareServiceImpl::factory_;
69 // decimal base
70 static constexpr int DECIMAL_BASE = 10;
71 class DataShareServiceImpl::SystemAbilityStatusChangeListener
72 : public SystemAbilityStatusChangeStub {
73 public:
SystemAbilityStatusChangeListener()74 SystemAbilityStatusChangeListener()
75 {
76 }
77 ~SystemAbilityStatusChangeListener() = default;
78 void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override;
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)79 void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override
80 {
81 }
82 };
83
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)84 void DataShareServiceImpl::SystemAbilityStatusChangeListener::OnAddSystemAbility(
85 int32_t systemAbilityId, const std::string &deviceId)
86 {
87 ZLOGI("saId:%{public}d", systemAbilityId);
88 if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
89 InitSubEvent();
90 } else if (systemAbilityId == CONCURRENT_TASK_SERVICE_ID) {
91 std::unordered_map<std::string, std::string> payload;
92 // get current thread pid
93 payload["pid"] = std::to_string(getpid());
94 // request qos auth for current pid
95 OHOS::ConcurrentTask::ConcurrentTaskClient::GetInstance().RequestAuth(payload);
96 }
97 return;
98 }
99
Factory()100 DataShareServiceImpl::Factory::Factory()
101 {
102 FeatureSystem::GetInstance().RegisterCreator("data_share", []() {
103 return std::make_shared<DataShareServiceImpl>();
104 });
105 staticActs_ = std::make_shared<DataShareStatic>();
106 FeatureSystem::GetInstance().RegisterStaticActs("data_share", staticActs_);
107 }
108
~Factory()109 DataShareServiceImpl::Factory::~Factory() {}
110
InsertEx(const std::string & uri,const std::string & extUri,const DataShareValuesBucket & valuesBucket)111 std::pair<int32_t, int32_t> DataShareServiceImpl::InsertEx(const std::string &uri, const std::string &extUri,
112 const DataShareValuesBucket &valuesBucket)
113 {
114 std::string func = __FUNCTION__;
115 XCollie xcollie(func, XCollie::XCOLLIE_LOG | XCollie::XCOLLIE_RECOVERY);
116 if (GetSilentProxyStatus(uri, false) != E_OK) {
117 ZLOGW("silent proxy disable, %{public}s", URIUtils::Anonymous(uri).c_str());
118 return std::make_pair(ERROR, 0);
119 }
120 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
121 auto callBack = [&uri, &valuesBucket, this, &callingTokenId, &func](ProviderInfo &providerInfo,
122 DistributedData::StoreMetaData &metaData,
123 std::shared_ptr<DBDelegate> dbDelegate) -> std::pair<int32_t, int32_t> {
124 TimeoutReport timeoutReport({providerInfo.bundleName, providerInfo.moduleName, providerInfo.storeName, func,
125 callingTokenId}, true);
126 auto [errCode, ret] = dbDelegate->InsertEx(providerInfo.tableName, valuesBucket);
127 if (errCode == E_OK && ret > 0) {
128 NotifyChange(uri);
129 RdbSubscriberManager::GetInstance().Emit(uri, providerInfo.visitedUserId, metaData);
130 } else {
131 ReportExcuteFault(callingTokenId, providerInfo, errCode, func);
132 }
133 timeoutReport.Report();
134 return std::make_pair(errCode, ret);
135 };
136 return ExecuteEx(uri, extUri, IPCSkeleton::GetCallingTokenID(), false, callBack);
137 }
138
NotifyChange(const std::string & uri)139 bool DataShareServiceImpl::NotifyChange(const std::string &uri)
140 {
141 RadarReporter::RadarReport report(RadarReporter::NOTIFY_OBSERVER_DATA_CHANGE,
142 RadarReporter::NOTIFY_DATA_CHANGE, __FUNCTION__);
143 auto obsMgrClient = AAFwk::DataObsMgrClient::GetInstance();
144 if (obsMgrClient == nullptr) {
145 ZLOGE("obsMgrClient is nullptr");
146 report.SetError(RadarReporter::DATA_OBS_EMPTY_ERROR);
147 return false;
148 }
149
150 ErrCode ret = obsMgrClient->NotifyChange(Uri(uri));
151 if (ret != ERR_OK) {
152 ZLOGE("obsMgrClient->NotifyChange error return %{public}d", ret);
153 report.SetError(RadarReporter::NOTIFY_ERROR);
154 return false;
155 }
156 return true;
157 }
158
UpdateEx(const std::string & uri,const std::string & extUri,const DataSharePredicates & predicate,const DataShareValuesBucket & valuesBucket)159 std::pair<int32_t, int32_t> DataShareServiceImpl::UpdateEx(const std::string &uri, const std::string &extUri,
160 const DataSharePredicates &predicate, const DataShareValuesBucket &valuesBucket)
161 {
162 std::string func = __FUNCTION__;
163 XCollie xcollie(func, XCollie::XCOLLIE_LOG | XCollie::XCOLLIE_RECOVERY);
164 if (GetSilentProxyStatus(uri, false) != E_OK) {
165 ZLOGW("silent proxy disable, %{public}s", URIUtils::Anonymous(uri).c_str());
166 return std::make_pair(ERROR, 0);
167 }
168 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
169 auto callBack = [&uri, &predicate, &valuesBucket, this, &callingTokenId, &func](ProviderInfo &providerInfo,
170 DistributedData::StoreMetaData &metaData,
171 std::shared_ptr<DBDelegate> dbDelegate) -> std::pair<int32_t, int32_t> {
172 TimeoutReport timeoutReport({providerInfo.bundleName, providerInfo.moduleName, providerInfo.storeName, func,
173 callingTokenId}, true);
174 auto [errCode, ret] = dbDelegate->UpdateEx(providerInfo.tableName, predicate, valuesBucket);
175 if (errCode == E_OK && ret > 0) {
176 NotifyChange(uri);
177 RdbSubscriberManager::GetInstance().Emit(uri, providerInfo.visitedUserId, metaData);
178 } else {
179 ReportExcuteFault(callingTokenId, providerInfo, errCode, func);
180 }
181 timeoutReport.Report();
182 return std::make_pair(errCode, ret);
183 };
184 return ExecuteEx(uri, extUri, callingTokenId, false, callBack);
185 }
186
DeleteEx(const std::string & uri,const std::string & extUri,const DataSharePredicates & predicate)187 std::pair<int32_t, int32_t> DataShareServiceImpl::DeleteEx(const std::string &uri, const std::string &extUri,
188 const DataSharePredicates &predicate)
189 {
190 std::string func = __FUNCTION__;
191 XCollie xcollie(func, XCollie::XCOLLIE_LOG | XCollie::XCOLLIE_RECOVERY);
192 if (GetSilentProxyStatus(uri, false) != E_OK) {
193 ZLOGW("silent proxy disable, %{public}s", URIUtils::Anonymous(uri).c_str());
194 return std::make_pair(ERROR, 0);
195 }
196 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
197 auto callBack = [&uri, &predicate, this, &callingTokenId, &func](ProviderInfo &providerInfo,
198 DistributedData::StoreMetaData &metaData,
199 std::shared_ptr<DBDelegate> dbDelegate) -> std::pair<int32_t, int32_t> {
200 TimeoutReport timeoutReport({providerInfo.bundleName, providerInfo.moduleName, providerInfo.storeName, func,
201 callingTokenId}, true);
202 auto [errCode, ret] = dbDelegate->DeleteEx(providerInfo.tableName, predicate);
203 if (errCode == E_OK && ret > 0) {
204 NotifyChange(uri);
205 RdbSubscriberManager::GetInstance().Emit(uri, providerInfo.visitedUserId, metaData);
206 } else {
207 ReportExcuteFault(callingTokenId, providerInfo, errCode, func);
208 }
209 timeoutReport.Report();
210 return std::make_pair(errCode, ret);
211 };
212 return ExecuteEx(uri, extUri, callingTokenId, false, callBack);
213 }
214
Query(const std::string & uri,const std::string & extUri,const DataSharePredicates & predicates,const std::vector<std::string> & columns,int & errCode)215 std::shared_ptr<DataShareResultSet> DataShareServiceImpl::Query(const std::string &uri, const std::string &extUri,
216 const DataSharePredicates &predicates, const std::vector<std::string> &columns, int &errCode)
217 {
218 std::string func = __FUNCTION__;
219 XCollie xcollie(std::string(LOG_TAG) + "::" + func,
220 XCollie::XCOLLIE_LOG | XCollie::XCOLLIE_RECOVERY);
221 if (GetSilentProxyStatus(uri, false) != E_OK) {
222 ZLOGW("silent proxy disable, %{public}s", URIUtils::Anonymous(uri).c_str());
223 return nullptr;
224 }
225 std::shared_ptr<DataShareResultSet> resultSet;
226 auto callingPid = IPCSkeleton::GetCallingPid();
227 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
228 auto callBack = [&uri, &predicates, &columns, &resultSet, &callingPid, &callingTokenId, &func, this]
229 (ProviderInfo &providerInfo, DistributedData::StoreMetaData &,
230 std::shared_ptr<DBDelegate> dbDelegate) -> std::pair<int32_t, int32_t> {
231 TimeoutReport timeoutReport({providerInfo.bundleName, providerInfo.moduleName, providerInfo.storeName, func,
232 callingTokenId}, true);
233 auto [err, result] = dbDelegate->Query(providerInfo.tableName,
234 predicates, columns, callingPid, callingTokenId);
235 if (err != E_OK) {
236 ReportExcuteFault(callingTokenId, providerInfo, err, func);
237 }
238 resultSet = std::move(result);
239 timeoutReport.Report();
240 return std::make_pair(err, E_OK);
241 };
242 auto [errVal, status] = ExecuteEx(uri, extUri, callingTokenId, true, callBack);
243 errCode = errVal;
244 return resultSet;
245 }
246
AddTemplate(const std::string & uri,const int64_t subscriberId,const Template & tplt)247 int32_t DataShareServiceImpl::AddTemplate(const std::string &uri, const int64_t subscriberId, const Template &tplt)
248 {
249 auto context = std::make_shared<Context>(uri);
250 TemplateId tpltId;
251 tpltId.subscriberId_ = subscriberId;
252 if (!GetCallerBundleName(tpltId.bundleName_)) {
253 ZLOGE("get bundleName error, %{public}s", DistributedData::Anonymous::Change(uri).c_str());
254 return ERROR;
255 }
256 ZLOGI("Add template, uri %{private}s, subscriberId %{public}" PRIi64 ", bundleName %{public}s,"
257 "predicates size %{public}zu.",
258 uri.c_str(), subscriberId, tpltId.bundleName_.c_str(), tplt.predicates_.size());
259 return templateStrategy_.Execute(context, [&uri, &tpltId, &tplt, &context]() -> int32_t {
260 auto result = TemplateManager::GetInstance().Add(
261 Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->currentUserId, tplt);
262 RdbSubscriberManager::GetInstance().Emit(context->uri, tpltId.subscriberId_, tpltId.bundleName_, context);
263 return result;
264 });
265 }
266
DelTemplate(const std::string & uri,const int64_t subscriberId)267 int32_t DataShareServiceImpl::DelTemplate(const std::string &uri, const int64_t subscriberId)
268 {
269 auto context = std::make_shared<Context>(uri);
270 TemplateId tpltId;
271 tpltId.subscriberId_ = subscriberId;
272 if (!GetCallerBundleName(tpltId.bundleName_)) {
273 ZLOGE("get bundleName error, %{public}s", DistributedData::Anonymous::Change(uri).c_str());
274 return ERROR;
275 }
276 ZLOGI("Delete template, uri %{private}s, subscriberId %{public}" PRIi64 ", bundleName %{public}s.",
277 DistributedData::Anonymous::Change(uri).c_str(), subscriberId, tpltId.bundleName_.c_str());
278 return templateStrategy_.Execute(context, [&uri, &tpltId, &context]() -> int32_t {
279 return TemplateManager::GetInstance().Delete(
280 Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->currentUserId);
281 });
282 }
283
GetCallerBundleName(std::string & bundleName)284 bool DataShareServiceImpl::GetCallerBundleName(std::string &bundleName)
285 {
286 auto tokenId = IPCSkeleton::GetCallingTokenID();
287 auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
288 if (type == Security::AccessToken::TOKEN_NATIVE) {
289 return true;
290 }
291 if (type != Security::AccessToken::TOKEN_HAP) {
292 return false;
293 }
294 Security::AccessToken::HapTokenInfo tokenInfo;
295 auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo);
296 if (result != Security::AccessToken::RET_SUCCESS) {
297 ZLOGE("token:0x%{public}x, result:%{public}d", tokenId, result);
298 return false;
299 }
300 bundleName = tokenInfo.bundleName;
301 return true;
302 }
303
GetCallerInfo(std::string & bundleName,int32_t & appIndex)304 std::pair<bool, Security::AccessToken::ATokenTypeEnum> DataShareServiceImpl::GetCallerInfo(
305 std::string &bundleName, int32_t &appIndex)
306 {
307 auto tokenId = IPCSkeleton::GetCallingTokenID();
308 auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
309 if (type == Security::AccessToken::TOKEN_NATIVE) {
310 return std::make_pair(true, type);
311 }
312 if (type != Security::AccessToken::TOKEN_HAP) {
313 return std::make_pair(false, type);
314 }
315 Security::AccessToken::HapTokenInfo tokenInfo;
316 auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo);
317 if (result != Security::AccessToken::RET_SUCCESS) {
318 ZLOGE("token:0x%{public}x, result:%{public}d", tokenId, result);
319 return std::make_pair(false, type);
320 }
321 bundleName = tokenInfo.bundleName;
322 appIndex = tokenInfo.instIndex;
323 return std::make_pair(true, type);
324 }
325
Publish(const Data & data,const std::string & bundleNameOfProvider)326 std::vector<OperationResult> DataShareServiceImpl::Publish(const Data &data, const std::string &bundleNameOfProvider)
327 {
328 std::vector<OperationResult> results;
329 std::vector<PublishedDataKey> publishedData;
330 std::string callerBundleName;
331 if (!GetCallerBundleName(callerBundleName)) {
332 ZLOGE("get bundleName error, %{public}s", callerBundleName.c_str());
333 return results;
334 }
335 int32_t userId = -1;
336 PublishedData::ClearAging();
337 for (const auto &item : data.datas_) {
338 auto context = std::make_shared<Context>(item.key_);
339 context->version = data.version_;
340 context->callerBundleName = callerBundleName;
341 context->calledBundleName = bundleNameOfProvider;
342 int32_t result = publishStrategy_.Execute(context, item);
343 results.emplace_back(item.key_, result);
344 if (result != E_OK) {
345 ZLOGE("publish error, key is %{public}s", DistributedData::Anonymous::Change(item.key_).c_str());
346 continue;
347 }
348 publishedData.emplace_back(context->uri, context->calledBundleName, item.subscriberId_);
349 userId = context->currentUserId;
350 }
351 if (!publishedData.empty()) {
352 PublishedDataSubscriberManager::GetInstance().Emit(publishedData, userId, callerBundleName);
353 PublishedDataSubscriberManager::GetInstance().SetObserversNotifiedOnEnabled(publishedData);
354 }
355 return results;
356 }
357
GetData(const std::string & bundleNameOfProvider,int & errorCode)358 Data DataShareServiceImpl::GetData(const std::string &bundleNameOfProvider, int &errorCode)
359 {
360 std::string callerBundleName;
361 if (!GetCallerBundleName(callerBundleName)) {
362 ZLOGE("get bundleName error, %{public}s", callerBundleName.c_str());
363 return Data();
364 }
365 auto context = std::make_shared<Context>();
366 context->callerBundleName = callerBundleName;
367 context->calledBundleName = bundleNameOfProvider;
368 return getDataStrategy_.Execute(context, errorCode);
369 }
370
SubscribeRdbData(const std::vector<std::string> & uris,const TemplateId & id,const sptr<IDataProxyRdbObserver> observer)371 std::vector<OperationResult> DataShareServiceImpl::SubscribeRdbData(
372 const std::vector<std::string> &uris, const TemplateId &id, const sptr<IDataProxyRdbObserver> observer)
373 {
374 std::vector<OperationResult> results;
375 for (const auto &uri : uris) {
376 auto context = std::make_shared<Context>(uri);
377 results.emplace_back(uri, subscribeStrategy_.Execute(context, [&id, &observer, &context, this]() {
378 return RdbSubscriberManager::GetInstance().Add(
379 Key(context->uri, id.subscriberId_, id.bundleName_), observer, context, binderInfo_.executors);
380 }));
381 }
382 return results;
383 }
384
UnsubscribeRdbData(const std::vector<std::string> & uris,const TemplateId & id)385 std::vector<OperationResult> DataShareServiceImpl::UnsubscribeRdbData(
386 const std::vector<std::string> &uris, const TemplateId &id)
387 {
388 std::vector<OperationResult> results;
389 for (const auto &uri : uris) {
390 auto context = std::make_shared<Context>(uri);
391 results.emplace_back(uri, subscribeStrategy_.Execute(context, [&id, &context]() {
392 return RdbSubscriberManager::GetInstance().Delete(
393 Key(context->uri, id.subscriberId_, id.bundleName_), context->callerTokenId);
394 }));
395 }
396 return results;
397 }
398
EnableRdbSubs(const std::vector<std::string> & uris,const TemplateId & id)399 std::vector<OperationResult> DataShareServiceImpl::EnableRdbSubs(
400 const std::vector<std::string> &uris, const TemplateId &id)
401 {
402 std::vector<OperationResult> results;
403 for (const auto &uri : uris) {
404 auto context = std::make_shared<Context>(uri);
405 results.emplace_back(uri, subscribeStrategy_.Execute(context, [&id, &context]() {
406 return RdbSubscriberManager::GetInstance().Enable(
407 Key(context->uri, id.subscriberId_, id.bundleName_), context);
408 }));
409 }
410 return results;
411 }
412
DisableRdbSubs(const std::vector<std::string> & uris,const TemplateId & id)413 std::vector<OperationResult> DataShareServiceImpl::DisableRdbSubs(
414 const std::vector<std::string> &uris, const TemplateId &id)
415 {
416 std::vector<OperationResult> results;
417 for (const auto &uri : uris) {
418 auto context = std::make_shared<Context>(uri);
419 results.emplace_back(uri, subscribeStrategy_.Execute(context, [&id, &context]() {
420 return RdbSubscriberManager::GetInstance().Disable(
421 Key(context->uri, id.subscriberId_, id.bundleName_), context->callerTokenId);
422 }));
423 }
424 return results;
425 }
426
SubscribePublishedData(const std::vector<std::string> & uris,const int64_t subscriberId,const sptr<IDataProxyPublishedDataObserver> observer)427 std::vector<OperationResult> DataShareServiceImpl::SubscribePublishedData(const std::vector<std::string> &uris,
428 const int64_t subscriberId, const sptr<IDataProxyPublishedDataObserver> observer)
429 {
430 std::vector<OperationResult> results;
431 std::string callerBundleName;
432 if (!GetCallerBundleName(callerBundleName)) {
433 ZLOGE("get bundleName error, %{public}s", callerBundleName.c_str());
434 return results;
435 }
436 std::vector<PublishedDataKey> publishedKeys;
437 int32_t result;
438 int32_t userId;
439 for (const auto &uri : uris) {
440 auto context = std::make_shared<Context>(uri);
441 PublishedDataKey key(uri, callerBundleName, subscriberId);
442 context->callerBundleName = callerBundleName;
443 context->calledBundleName = key.bundleName;
444 result = subscribeStrategy_.Execute(context, [&subscriberId, &observer, &context]() {
445 return PublishedDataSubscriberManager::GetInstance().Add(
446 PublishedDataKey(context->uri, context->callerBundleName, subscriberId), observer,
447 context->callerTokenId);
448 });
449 results.emplace_back(uri, result);
450 if (result == E_OK) {
451 publishedKeys.emplace_back(context->uri, context->callerBundleName, subscriberId);
452 if (binderInfo_.executors != nullptr) {
453 binderInfo_.executors->Execute([context, subscriberId]() {
454 PublishedData::UpdateTimestamp(
455 context->uri, context->calledBundleName, subscriberId, context->currentUserId);
456 });
457 }
458 userId = context->currentUserId;
459 }
460 }
461 if (!publishedKeys.empty()) {
462 PublishedDataSubscriberManager::GetInstance().Emit(publishedKeys, userId, callerBundleName, observer);
463 }
464 return results;
465 }
466
UnsubscribePublishedData(const std::vector<std::string> & uris,const int64_t subscriberId)467 std::vector<OperationResult> DataShareServiceImpl::UnsubscribePublishedData(const std::vector<std::string> &uris,
468 const int64_t subscriberId)
469 {
470 std::vector<OperationResult> results;
471 std::string callerBundleName;
472 if (!GetCallerBundleName(callerBundleName)) {
473 ZLOGE("get bundleName error, %{public}s", callerBundleName.c_str());
474 return results;
475 }
476 for (const auto &uri : uris) {
477 auto context = std::make_shared<Context>(uri);
478 PublishedDataKey key(uri, callerBundleName, subscriberId);
479 context->callerBundleName = callerBundleName;
480 context->calledBundleName = key.bundleName;
481 results.emplace_back(uri, subscribeStrategy_.Execute(context, [&subscriberId, &context, this]() {
482 auto result = PublishedDataSubscriberManager::GetInstance().Delete(
483 PublishedDataKey(context->uri, context->callerBundleName, subscriberId), context->callerTokenId);
484 if (result == E_OK && binderInfo_.executors != nullptr) {
485 binderInfo_.executors->Execute([context, subscriberId]() {
486 PublishedData::UpdateTimestamp(
487 context->uri, context->calledBundleName, subscriberId, context->currentUserId);
488 });
489 }
490 return result;
491 }));
492 }
493 return results;
494 }
495
EnablePubSubs(const std::vector<std::string> & uris,const int64_t subscriberId)496 std::vector<OperationResult> DataShareServiceImpl::EnablePubSubs(const std::vector<std::string> &uris,
497 const int64_t subscriberId)
498 {
499 std::vector<OperationResult> results;
500 std::string callerBundleName;
501 if (!GetCallerBundleName(callerBundleName)) {
502 ZLOGE("get bundleName error, %{public}s", callerBundleName.c_str());
503 return results;
504 }
505 std::vector<PublishedDataKey> publishedKeys;
506 int32_t result;
507 int32_t userId = -1;
508 for (const auto &uri : uris) {
509 auto context = std::make_shared<Context>(uri);
510 PublishedDataKey key(uri, callerBundleName, subscriberId);
511 context->callerBundleName = callerBundleName;
512 context->calledBundleName = key.bundleName;
513 result = subscribeStrategy_.Execute(context, [&subscriberId, &context]() {
514 return PublishedDataSubscriberManager::GetInstance().Enable(
515 PublishedDataKey(context->uri, context->callerBundleName, subscriberId), context->callerTokenId);
516 });
517 if (result == E_OK && binderInfo_.executors != nullptr) {
518 binderInfo_.executors->Execute([context, subscriberId]() {
519 PublishedData::UpdateTimestamp(
520 context->uri, context->calledBundleName, subscriberId, context->currentUserId);
521 });
522 }
523 results.emplace_back(uri, result);
524 if (result == E_OK) {
525 PublishedDataKey pKey(context->uri, context->callerBundleName, subscriberId);
526 if (PublishedDataSubscriberManager::GetInstance().IsNotifyOnEnabled(pKey, context->callerTokenId)) {
527 publishedKeys.emplace_back(pKey);
528 }
529 userId = context->currentUserId;
530 }
531 }
532 if (!publishedKeys.empty()) {
533 PublishedDataSubscriberManager::GetInstance().Emit(publishedKeys, userId, callerBundleName);
534 }
535 return results;
536 }
537
DisablePubSubs(const std::vector<std::string> & uris,const int64_t subscriberId)538 std::vector<OperationResult> DataShareServiceImpl::DisablePubSubs(const std::vector<std::string> &uris,
539 const int64_t subscriberId)
540 {
541 std::vector<OperationResult> results;
542 std::string callerBundleName;
543 if (!GetCallerBundleName(callerBundleName)) {
544 ZLOGE("get bundleName error, %{public}s", callerBundleName.c_str());
545 return results;
546 }
547 for (const auto &uri : uris) {
548 auto context = std::make_shared<Context>(uri);
549 PublishedDataKey key(uri, callerBundleName, subscriberId);
550 context->callerBundleName = callerBundleName;
551 context->calledBundleName = key.bundleName;
552 results.emplace_back(uri, subscribeStrategy_.Execute(context, [&subscriberId, &context, this]() {
553 auto result = PublishedDataSubscriberManager::GetInstance().Disable(
554 PublishedDataKey(context->uri, context->callerBundleName, subscriberId), context->callerTokenId);
555 if (result == E_OK && binderInfo_.executors != nullptr) {
556 binderInfo_.executors->Execute([context, subscriberId]() {
557 PublishedData::UpdateTimestamp(
558 context->uri, context->calledBundleName, subscriberId, context->currentUserId);
559 });
560 }
561 return result;
562 }));
563 }
564 return results;
565 }
566
567 enum DataShareKvStoreType : int32_t {
568 DATA_SHARE_SINGLE_VERSION = 0,
569 DISTRIBUTED_TYPE_BUTT
570 };
571
OnBind(const BindInfo & binderInfo)572 int32_t DataShareServiceImpl::OnBind(const BindInfo &binderInfo)
573 {
574 binderInfo_ = binderInfo;
575 const std::string accountId = AccountDelegate::GetInstance()->GetCurrentAccountId();
576 const auto userId = AccountDelegate::GetInstance()->GetUserByToken(binderInfo.selfTokenId);
577 DistributedData::StoreMetaData saveMeta;
578 saveMeta.appType = "default";
579 saveMeta.storeId = "data_share_data_";
580 saveMeta.isAutoSync = false;
581 saveMeta.isBackup = false;
582 saveMeta.isEncrypt = false;
583 saveMeta.bundleName = binderInfo.selfName;
584 saveMeta.appId = binderInfo.selfName;
585 saveMeta.user = std::to_string(userId);
586 saveMeta.account = accountId;
587 saveMeta.tokenId = binderInfo.selfTokenId;
588 saveMeta.securityLevel = DistributedKv::SecurityLevel::S1;
589 saveMeta.area = DistributedKv::Area::EL1;
590 saveMeta.uid = IPCSkeleton::GetCallingUid();
591 saveMeta.storeType = DATA_SHARE_SINGLE_VERSION;
592 saveMeta.dataDir = DistributedData::DirectoryManager::GetInstance().GetStorePath(saveMeta);
593 KvDBDelegate::GetInstance(false, saveMeta.dataDir, binderInfo.executors);
594 SchedulerManager::GetInstance().SetExecutorPool(binderInfo.executors);
595 ExtensionAbilityManager::GetInstance().SetExecutorPool(binderInfo.executors);
596 DBDelegate::SetExecutorPool(binderInfo.executors);
597 HiViewAdapter::GetInstance().SetThreadPool(binderInfo.executors);
598 SubscribeCommonEvent();
599 SubscribeConcurrentTask();
600 SubscribeTimeChanged();
601 SubscribeChange();
602 ZLOGI("end");
603 return E_OK;
604 }
605
SubscribeCommonEvent()606 void DataShareServiceImpl::SubscribeCommonEvent()
607 {
608 sptr<ISystemAbilityManager> systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
609 if (systemManager == nullptr) {
610 ZLOGE("System mgr is nullptr");
611 return;
612 }
613 sptr<SystemAbilityStatusChangeListener> callback(new SystemAbilityStatusChangeListener());
614 systemManager->SubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, callback);
615 }
616
SubscribeConcurrentTask()617 void DataShareServiceImpl::SubscribeConcurrentTask()
618 {
619 sptr<ISystemAbilityManager> systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
620 if (systemManager == nullptr) {
621 ZLOGE("System mgr is nullptr");
622 return;
623 }
624 sptr<SystemAbilityStatusChangeListener> callback(new SystemAbilityStatusChangeListener());
625 systemManager->SubscribeSystemAbility(CONCURRENT_TASK_SERVICE_ID, callback);
626 }
627
SubscribeChange()628 void DataShareServiceImpl::SubscribeChange()
629 {
630 EventCenter::GetInstance().Subscribe(RemoteChangeEvent::RDB_META_SAVE, [this](const Event &event) {
631 auto &evt = static_cast<const RemoteChangeEvent &>(event);
632 auto dataInfo = evt.GetDataInfo();
633 SaveLaunchInfo(dataInfo.bundleName, dataInfo.userId, dataInfo.deviceId);
634 });
635 EventCenter::GetInstance().Subscribe(RemoteChangeEvent::DATA_CHANGE, [this](const Event &event) {
636 AutoLaunch(event);
637 });
638 }
639
SaveLaunchInfo(const std::string & bundleName,const std::string & userId,const std::string & deviceId)640 void DataShareServiceImpl::SaveLaunchInfo(const std::string &bundleName, const std::string &userId,
641 const std::string &deviceId)
642 {
643 std::map<std::string, ProfileInfo> profileInfos;
644 char *endptr = nullptr;
645 errno = 0;
646 long userIdLong = strtol(userId.c_str(), &endptr, DECIMAL_BASE);
647 if (endptr == nullptr || endptr == userId.c_str() || *endptr != '\0') {
648 ZLOGE("UserId:%{public}s is invalid", userId.c_str());
649 return;
650 }
651 if (errno == ERANGE || userIdLong >= INT32_MAX || userIdLong <= INT32_MIN) {
652 ZLOGE("UserId:%{public}s is out of range", userId.c_str());
653 return;
654 }
655 int32_t currentUserId = static_cast<int32_t>(userIdLong);
656 if (!DataShareProfileConfig::GetProfileInfo(bundleName, currentUserId, profileInfos)) {
657 ZLOGE("Get profileInfo failed.");
658 return;
659 }
660 if (profileInfos.empty()) {
661 return;
662 }
663 for (auto &[uri, value] : profileInfos) {
664 if (uri.find(EXT_URI_SCHEMA) == std::string::npos) {
665 continue;
666 }
667 std::string extUri = uri;
668 extUri.insert(strlen(EXT_URI_SCHEMA), "/");
669 StoreMetaData meta = MakeMetaData(bundleName, userId, deviceId);
670 if (value.launchInfos.empty()) {
671 meta.storeId = "";
672 AutoLaunchMetaData autoLaunchMetaData = {};
673 std::vector<std::string> tempData = {};
674 autoLaunchMetaData.datas.emplace(extUri, tempData);
675 autoLaunchMetaData.launchForCleanData = value.launchForCleanData;
676 MetaDataManager::GetInstance().SaveMeta(meta.GetAutoLaunchKey(), autoLaunchMetaData, true);
677 ZLOGI("Without launchInfos, save meta end, bundleName = %{public}s.", bundleName.c_str());
678 continue;
679 }
680 for (const auto &launchInfo : value.launchInfos) {
681 AutoLaunchMetaData autoLaunchMetaData = {};
682 autoLaunchMetaData.datas.emplace(extUri, launchInfo.tableNames);
683 autoLaunchMetaData.launchForCleanData = value.launchForCleanData;
684 meta.storeId = launchInfo.storeId;
685 MetaDataManager::GetInstance().SaveMeta(meta.GetAutoLaunchKey(), autoLaunchMetaData, true);
686 }
687 }
688 }
689
AllowCleanDataLaunchApp(const Event & event,bool launchForCleanData)690 bool DataShareServiceImpl::AllowCleanDataLaunchApp(const Event &event, bool launchForCleanData)
691 {
692 auto &evt = static_cast<const RemoteChangeEvent &>(event);
693 auto dataInfo = evt.GetDataInfo();
694 // 1 means CLOUD_DATA_CLEAN
695 if (dataInfo.changeType == 1) {
696 return launchForCleanData; // Applications can be started by default
697 }
698 return true;
699 }
700
AutoLaunch(const Event & event)701 void DataShareServiceImpl::AutoLaunch(const Event &event)
702 {
703 auto &evt = static_cast<const RemoteChangeEvent &>(event);
704 auto dataInfo = evt.GetDataInfo();
705 StoreMetaData meta = MakeMetaData(dataInfo.bundleName, dataInfo.userId, dataInfo.deviceId, dataInfo.storeId);
706 AutoLaunchMetaData autoLaunchMetaData;
707 if (!MetaDataManager::GetInstance().LoadMeta(std::move(meta.GetAutoLaunchKey()), autoLaunchMetaData, true)) {
708 meta.storeId = "";
709 if (!MetaDataManager::GetInstance().LoadMeta(std::move(meta.GetAutoLaunchKey()), autoLaunchMetaData, true)) {
710 ZLOGE("No launch meta without storeId, bundleName = %{public}s.", dataInfo.bundleName.c_str());
711 return;
712 }
713 }
714 if (autoLaunchMetaData.datas.empty() || !AllowCleanDataLaunchApp(event, autoLaunchMetaData.launchForCleanData)) {
715 return;
716 }
717 for (const auto &[uri, metaTables] : autoLaunchMetaData.datas) {
718 if (dataInfo.tables.empty() && dataInfo.changeType == 1) {
719 ZLOGI("Start to connect extension, bundlename = %{public}s.", dataInfo.bundleName.c_str());
720 AAFwk::WantParams wantParams;
721 ExtensionConnectAdaptor::TryAndWait(uri, dataInfo.bundleName, wantParams);
722 return;
723 }
724 for (const auto &table : dataInfo.tables) {
725 if (std::find(metaTables.begin(), metaTables.end(), table) != metaTables.end()) {
726 ZLOGI("Find table, start to connect extension, bundlename = %{public}s.", dataInfo.bundleName.c_str());
727 AAFwk::WantParams wantParams;
728 ExtensionConnectAdaptor::TryAndWait(uri, dataInfo.bundleName, wantParams);
729 break;
730 }
731 }
732 }
733 }
734
MakeMetaData(const std::string & bundleName,const std::string & userId,const std::string & deviceId,const std::string storeId)735 StoreMetaData DataShareServiceImpl::MakeMetaData(const std::string &bundleName, const std::string &userId,
736 const std::string &deviceId, const std::string storeId)
737 {
738 StoreMetaData meta;
739 meta.user = userId;
740 meta.storeId = storeId;
741 meta.deviceId = deviceId;
742 meta.bundleName = bundleName;
743 return meta;
744 }
745
OnConnectDone()746 void DataShareServiceImpl::OnConnectDone()
747 {
748 std::string callerBundleName;
749 if (!GetCallerBundleName(callerBundleName)) {
750 ZLOGE("get bundleName error, %{public}s", callerBundleName.c_str());
751 return;
752 }
753 AppConnectManager::Notify(callerBundleName);
754 }
755
OnAppUninstall(const std::string & bundleName,int32_t user,int32_t index)756 int32_t DataShareServiceImpl::DataShareStatic::OnAppUninstall(const std::string &bundleName, int32_t user,
757 int32_t index)
758 {
759 ZLOGI("%{public}s uninstalled", bundleName.c_str());
760 PublishedData::Delete(bundleName, user);
761 PublishedData::ClearAging();
762 TemplateData::Delete(bundleName, user);
763 NativeRdb::RdbHelper::ClearCache();
764 BundleMgrProxy::GetInstance()->Delete(bundleName, user, index);
765 uint32_t tokenId = Security::AccessToken::AccessTokenKit::GetHapTokenID(user, bundleName, index);
766 DBDelegate::EraseStoreCache(tokenId);
767 return E_OK;
768 }
769
OnAppExit(pid_t uid,pid_t pid,uint32_t tokenId,const std::string & bundleName)770 int32_t DataShareServiceImpl::OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &bundleName)
771 {
772 ZLOGI("AppExit uid=%{public}d, pid=%{public}d, tokenId=0x%{public}x, bundleName=%{public}s",
773 uid, pid, tokenId, bundleName.c_str());
774 RdbSubscriberManager::GetInstance().Delete(tokenId, pid);
775 PublishedDataSubscriberManager::GetInstance().Delete(tokenId, pid);
776 return E_OK;
777 }
778
OnAppUpdate(const std::string & bundleName,int32_t user,int32_t index)779 int32_t DataShareServiceImpl::DataShareStatic::OnAppUpdate(const std::string &bundleName, int32_t user,
780 int32_t index)
781 {
782 ZLOGI("%{public}s updated", bundleName.c_str());
783 BundleMgrProxy::GetInstance()->Delete(bundleName, user, index);
784 std::string prefix = StoreMetaData::GetPrefix(
785 { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid, std::to_string(user), "default", bundleName });
786 std::vector<StoreMetaData> storeMetaData;
787 MetaDataManager::GetInstance().LoadMeta(prefix, storeMetaData, true);
788 for (auto &meta : storeMetaData) {
789 MetaDataManager::GetInstance().DelMeta(meta.GetAutoLaunchKey(), true);
790 }
791 SaveLaunchInfo(bundleName, std::to_string(user), DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid);
792 return E_OK;
793 }
794
OnClearAppStorage(const std::string & bundleName,int32_t user,int32_t index,int32_t tokenId)795 int32_t DataShareServiceImpl::DataShareStatic::OnClearAppStorage(const std::string &bundleName,
796 int32_t user, int32_t index, int32_t tokenId)
797 {
798 ZLOGI("ClearAppStorage user=%{public}d, index=%{public}d, token:0x%{public}x, bundleName=%{public}s",
799 user, index, tokenId, bundleName.c_str());
800 DBDelegate::EraseStoreCache(tokenId);
801 return E_OK;
802 }
803
OnAppUninstall(const std::string & bundleName,int32_t user,int32_t index)804 int32_t DataShareServiceImpl::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index)
805 {
806 ZLOGI("AppUninstall user=%{public}d, index=%{public}d, bundleName=%{public}s",
807 user, index, bundleName.c_str());
808 BundleMgrProxy::GetInstance()->Delete(bundleName, user, index);
809 return E_OK;
810 }
811
OnAppUpdate(const std::string & bundleName,int32_t user,int32_t index)812 int32_t DataShareServiceImpl::OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index)
813 {
814 ZLOGI("AppUpdate user=%{public}d, index=%{public}d, bundleName=%{public}s",
815 user, index, bundleName.c_str());
816 BundleMgrProxy::GetInstance()->Delete(bundleName, user, index);
817 return E_OK;
818 }
819
NotifyObserver(const std::string & uri)820 void DataShareServiceImpl::NotifyObserver(const std::string &uri)
821 {
822 ZLOGD_MACRO("%{private}s try notified", uri.c_str());
823 auto context = std::make_shared<Context>(uri);
824 if (!GetCallerBundleName(context->callerBundleName)) {
825 ZLOGE("get bundleName error, %{private}s", uri.c_str());
826 return;
827 }
828 auto ret = rdbNotifyStrategy_.Execute(context);
829 if (ret) {
830 ZLOGI("%{private}s start notified", uri.c_str());
831 RdbSubscriberManager::GetInstance().Emit(uri, context);
832 }
833 }
834
SubscribeTimeChanged()835 bool DataShareServiceImpl::SubscribeTimeChanged()
836 {
837 ZLOGD_MACRO("start");
838 EventFwk::MatchingSkills matchingSkills;
839 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_TIME_CHANGED);
840 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED);
841 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
842 subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
843 timerReceiver_ = std::make_shared<TimerReceiver>(subscribeInfo);
844 auto result = EventFwk::CommonEventManager::SubscribeCommonEvent(timerReceiver_);
845 if (!result) {
846 ZLOGE("SubscribeCommonEvent err");
847 }
848 return result;
849 }
850
OnReceiveEvent(const EventFwk::CommonEventData & eventData)851 void DataShareServiceImpl::TimerReceiver::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
852 {
853 AAFwk::Want want = eventData.GetWant();
854 std::string action = want.GetAction();
855 ZLOGI("action:%{public}s.", action.c_str());
856 if (action == EventFwk::CommonEventSupport::COMMON_EVENT_TIME_CHANGED
857 || action == EventFwk::CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED) {
858 SchedulerManager::GetInstance().ReExecuteAll();
859 }
860 }
861
TimerReceiver(const EventFwk::CommonEventSubscribeInfo & subscriberInfo)862 DataShareServiceImpl::TimerReceiver::TimerReceiver(const EventFwk::CommonEventSubscribeInfo &subscriberInfo)
863 : CommonEventSubscriber(subscriberInfo)
864 {
865 }
866
RegisterDataShareServiceInfo()867 void DataShareServiceImpl::RegisterDataShareServiceInfo()
868 {
869 DumpManager::Config serviceInfoConfig;
870 serviceInfoConfig.fullCmd = "--feature-info";
871 serviceInfoConfig.abbrCmd = "-f";
872 serviceInfoConfig.dumpName = "FEATURE_INFO";
873 serviceInfoConfig.dumpCaption = { "| Display all the service statistics" };
874 DumpManager::GetInstance().AddConfig("FEATURE_INFO", serviceInfoConfig);
875 }
876
RegisterHandler()877 void DataShareServiceImpl::RegisterHandler()
878 {
879 Handler handler =
880 std::bind(&DataShareServiceImpl::DumpDataShareServiceInfo, this, std::placeholders::_1, std::placeholders::_2);
881 DumpManager::GetInstance().AddHandler("FEATURE_INFO", uintptr_t(this), handler);
882 }
883
DumpDataShareServiceInfo(int fd,std::map<std::string,std::vector<std::string>> & params)884 void DataShareServiceImpl::DumpDataShareServiceInfo(int fd, std::map<std::string, std::vector<std::string>> ¶ms)
885 {
886 (void)params;
887 std::string info;
888 dprintf(fd, "-------------------------------------DataShareServiceInfo------------------------------\n%s\n",
889 info.c_str());
890 }
891
OnInitialize()892 int32_t DataShareServiceImpl::OnInitialize()
893 {
894 RegisterDataShareServiceInfo();
895 RegisterHandler();
896 SetServiceReady();
897 ZLOGI("Init dataShare service end");
898 return 0;
899 }
900
~DataShareServiceImpl()901 DataShareServiceImpl::~DataShareServiceImpl()
902 {
903 DumpManager::GetInstance().RemoveHandler("FEATURE_INFO", uintptr_t(this));
904 }
905
EnableSilentProxy(const std::string & uri,bool enable)906 int32_t DataShareServiceImpl::EnableSilentProxy(const std::string &uri, bool enable)
907 {
908 uint32_t callerTokenId = IPCSkeleton::GetCallingTokenID();
909 bool ret = dataShareSilentConfig_.EnableSilentProxy(callerTokenId, uri, enable);
910 if (!ret) {
911 ZLOGE("Enable silent proxy err, %{public}s", URIUtils::Anonymous(uri).c_str());
912 return ERROR;
913 }
914 return E_OK;
915 }
916
GetSilentProxyStatus(const std::string & uri,bool isCreateHelper)917 int32_t DataShareServiceImpl::GetSilentProxyStatus(const std::string &uri, bool isCreateHelper)
918 {
919 XCollie xcollie(std::string(LOG_TAG) + "::" + std::string(__FUNCTION__),
920 XCollie::XCOLLIE_LOG | XCollie::XCOLLIE_RECOVERY);
921 uint32_t callerTokenId = IPCSkeleton::GetCallingTokenID();
922 if (isCreateHelper) {
923 auto errCode = GetBMSAndMetaDataStatus(uri, callerTokenId);
924 if (errCode != E_OK) {
925 ZLOGE("BMS or metaData not ready to complete, token:0x%{public}x, uri:%{public}s",
926 callerTokenId, URIUtils::Anonymous(uri).c_str());
927 return errCode;
928 }
929 }
930 int32_t currentUserId = AccountDelegate::GetInstance()->GetUserByToken(callerTokenId);
931 UriInfo uriInfo;
932 // GetInfoFromUri will first perform a four-part URI check. Only if the URI contains more than four parts
933 // is it necessary to continue to check the SilentProxyEnable status. The URI part length is used as an
934 // indicator to determine whether the SilentProxyEnable status needs to be checked.
935 if (!URIUtils::GetInfoFromURI(uri, uriInfo)) {
936 return E_OK;
937 }
938 std::string calledBundleName = uriInfo.bundleName;
939 int32_t appIndex = 0;
940 if (!URIUtils::GetAppIndexFromProxyURI(uri, appIndex)) {
941 return E_APPINDEX_INVALID;
942 }
943 uint32_t calledTokenId = Security::AccessToken::AccessTokenKit::GetHapTokenID(
944 currentUserId, calledBundleName, appIndex);
945 if (calledTokenId == 0) {
946 calledTokenId = Security::AccessToken::AccessTokenKit::GetHapTokenID(0, calledBundleName, 0);
947 }
948 auto success = dataShareSilentConfig_.IsSilentProxyEnable(calledTokenId, currentUserId, calledBundleName, uri);
949 if (!success) {
950 ZLOGW("silent proxy disable, %{public}s", URIUtils::Anonymous(uri).c_str());
951 return E_SILENT_PROXY_DISABLE;
952 }
953 return E_OK;
954 }
955
RegisterObserver(const std::string & uri,const sptr<OHOS::IRemoteObject> & remoteObj)956 int32_t DataShareServiceImpl::RegisterObserver(const std::string &uri,
957 const sptr<OHOS::IRemoteObject> &remoteObj)
958 {
959 return ERROR;
960 }
961
UnregisterObserver(const std::string & uri,const sptr<OHOS::IRemoteObject> & remoteObj)962 int32_t DataShareServiceImpl::UnregisterObserver(const std::string &uri,
963 const sptr<OHOS::IRemoteObject> &remoteObj)
964 {
965 return ERROR;
966 }
967
VerifyAcrossAccountsPermission(int32_t currentUserId,int32_t visitedUserId,const std::string & acrossAccountsPermission,uint32_t callerTokenId)968 bool DataShareServiceImpl::VerifyAcrossAccountsPermission(int32_t currentUserId, int32_t visitedUserId,
969 const std::string &acrossAccountsPermission, uint32_t callerTokenId)
970 {
971 // if it's SA, or visit itself, no need to verify permission
972 if (currentUserId == 0 || currentUserId == visitedUserId) {
973 return true;
974 }
975 return system::GetBoolParameter(CONNECT_SUPPORT_CROSS_USER, false) &&
976 PermitDelegate::VerifyPermission(acrossAccountsPermission, callerTokenId);
977 }
978
ExecuteEx(const std::string & uri,const std::string & extUri,const int32_t tokenId,bool isRead,ExecuteCallbackEx callback)979 std::pair<int32_t, int32_t> DataShareServiceImpl::ExecuteEx(const std::string &uri, const std::string &extUri,
980 const int32_t tokenId, bool isRead, ExecuteCallbackEx callback)
981 {
982 DataProviderConfig providerConfig(uri, tokenId);
983 auto [errCode, providerInfo] = providerConfig.GetProviderInfo();
984 if (errCode != E_OK) {
985 ZLOGE("Provider failed! token:0x%{public}x,ret:%{public}d,uri:%{public}s,visitedUserId:%{public}d", tokenId,
986 errCode, URIUtils::Anonymous(providerInfo.uri).c_str(), providerInfo.visitedUserId);
987 RADAR_REPORT(__FUNCTION__, RadarReporter::SILENT_ACCESS, RadarReporter::PROXY_GET_SUPPLIER,
988 RadarReporter::FAILED, RadarReporter::ERROR_CODE, RadarReporter::SUPPLIER_ERROR);
989 return std::make_pair(errCode, 0);
990 }
991 // when HAP interacts across users, it needs to check across users permission
992 if (!VerifyAcrossAccountsPermission(providerInfo.currentUserId, providerInfo.visitedUserId,
993 providerInfo.acrossAccountsPermission, tokenId)) {
994 ZLOGE("Across accounts permission denied! token:0x%{public}x, uri:%{public}s, current user:%{public}d,"
995 "visited user:%{public}d", tokenId, URIUtils::Anonymous(providerInfo.uri).c_str(),
996 providerInfo.currentUserId, providerInfo.visitedUserId);
997 RADAR_REPORT(__FUNCTION__, RadarReporter::SILENT_ACCESS, RadarReporter::PROXY_PERMISSION,
998 RadarReporter::FAILED, RadarReporter::ERROR_CODE, RadarReporter::PERMISSION_DENIED_ERROR);
999 return std::make_pair(ERROR_PERMISSION_DENIED, 0);
1000 }
1001 if (!CheckAllowList(providerInfo.currentUserId, tokenId, providerInfo.allowLists)) {
1002 ZLOGE("CheckAllowList failed, permission denied! token:0x%{public}x, uri:%{public}s",
1003 tokenId, URIUtils::Anonymous(providerInfo.uri).c_str());
1004 return std::make_pair(ERROR_PERMISSION_DENIED, 0);
1005 }
1006 std::string permission = isRead ? providerInfo.readPermission : providerInfo.writePermission;
1007 if (!VerifyPermission(providerInfo.bundleName, permission, providerInfo.isFromExtension, tokenId)) {
1008 ZLOGE("Permission denied! token:0x%{public}x, permission:%{public}s,isFromExtension:%{public}d,uri:%{public}s",
1009 tokenId, permission.c_str(), providerInfo.isFromExtension, URIUtils::Anonymous(providerInfo.uri).c_str());
1010 RADAR_REPORT(__FUNCTION__, RadarReporter::SILENT_ACCESS, RadarReporter::PROXY_PERMISSION,
1011 RadarReporter::FAILED, RadarReporter::ERROR_CODE, RadarReporter::PERMISSION_DENIED_ERROR);
1012 return std::make_pair(ERROR_PERMISSION_DENIED, 0);
1013 }
1014 DataShareDbConfig dbConfig;
1015 std::string extensionUri = extUri;
1016 if (extensionUri.empty()) {
1017 extensionUri = providerInfo.extensionUri;
1018 }
1019 DataShareDbConfig::DbConfig config {providerInfo.uri, extensionUri, providerInfo.bundleName,
1020 providerInfo.storeName, providerInfo.backup, providerInfo.singleton ? 0 : providerInfo.visitedUserId,
1021 providerInfo.appIndex, providerInfo.hasExtension};
1022 auto [code, metaData, dbDelegate] = dbConfig.GetDbConfig(config);
1023 if (code != E_OK) {
1024 ZLOGE("Get dbConfig fail,bundleName:%{public}s,tableName:%{public}s,tokenId:0x%{public}x, uri:%{public}s",
1025 providerInfo.bundleName.c_str(), providerInfo.tableName.c_str(), tokenId,
1026 URIUtils::Anonymous(providerInfo.uri).c_str());
1027 return std::make_pair(code, 0);
1028 }
1029 return callback(providerInfo, metaData, dbDelegate);
1030 }
1031
CheckAllowList(const uint32_t & currentUserId,const uint32_t & callerTokenId,const std::vector<AllowList> & allowLists)1032 bool DataShareServiceImpl::CheckAllowList(const uint32_t ¤tUserId, const uint32_t &callerTokenId,
1033 const std::vector<AllowList> &allowLists)
1034 {
1035 if (allowLists.empty()) {
1036 return true;
1037 }
1038 std::string callerBundleName;
1039 int32_t callerAppIndex = 0;
1040 auto [success, type] = GetCallerInfo(callerBundleName, callerAppIndex);
1041 if (!success) {
1042 ZLOGE("Get caller info failed, token:0x%{public}x", callerTokenId);
1043 return false;
1044 }
1045 // SA calling
1046 if (type == Security::AccessToken::TOKEN_NATIVE) {
1047 return true;
1048 }
1049
1050 auto [ret, callerAppIdentifier] = BundleMgrProxy::GetInstance()->GetCallerAppIdentifier(
1051 callerBundleName, currentUserId);
1052 if (ret != 0) {
1053 ZLOGE("Get caller appIdentifier failed, callerBundleName is %{public}s", callerBundleName.c_str());
1054 return false;
1055 }
1056
1057 for (auto const& allowList : allowLists) {
1058 if (callerAppIdentifier == allowList.appIdentifier) {
1059 if (callerAppIndex != 0 && allowList.onlyMain) {
1060 ZLOGE("Provider only allow main application!");
1061 return false;
1062 }
1063 return true;
1064 }
1065 }
1066 return false;
1067 }
1068
GetBMSAndMetaDataStatus(const std::string & uri,const int32_t tokenId)1069 int32_t DataShareServiceImpl::GetBMSAndMetaDataStatus(const std::string &uri, const int32_t tokenId)
1070 {
1071 DataProviderConfig calledConfig(uri, tokenId);
1072 auto [errCode, calledInfo] = calledConfig.GetProviderInfo();
1073 if (errCode == E_URI_NOT_EXIST) {
1074 ZLOGE("Create helper invalid uri, token:0x%{public}x, uri:%{public}s", tokenId,
1075 URIUtils::Anonymous(calledInfo.uri).c_str());
1076 return E_OK;
1077 }
1078 if (errCode != E_OK) {
1079 ZLOGE("CalledInfo failed! token:0x%{public}x,ret:%{public}d,uri:%{public}s", tokenId,
1080 errCode, URIUtils::Anonymous(calledInfo.uri).c_str());
1081 return errCode;
1082 }
1083 DataShareDbConfig dbConfig;
1084 DataShareDbConfig::DbConfig dbArg;
1085 dbArg.uri = calledInfo.uri;
1086 dbArg.bundleName = calledInfo.bundleName;
1087 dbArg.storeName = calledInfo.storeName;
1088 dbArg.userId = calledInfo.singleton ? 0 : calledInfo.visitedUserId;
1089 dbArg.hasExtension = calledInfo.hasExtension;
1090 dbArg.appIndex = calledInfo.appIndex;
1091 auto [code, metaData] = dbConfig.GetMetaData(dbArg);
1092 if (code != E_OK) {
1093 ZLOGE("Get metaData fail,bundleName:%{public}s,tableName:%{public}s,tokenId:0x%{public}x, uri:%{public}s",
1094 calledInfo.bundleName.c_str(), calledInfo.tableName.c_str(), tokenId,
1095 URIUtils::Anonymous(calledInfo.uri).c_str());
1096 return E_METADATA_NOT_EXISTS;
1097 }
1098 return E_OK;
1099 }
1100
InitSubEvent()1101 void DataShareServiceImpl::InitSubEvent()
1102 {
1103 static std::atomic<bool> alreadySubscribe = false;
1104 bool except = false;
1105 if (!alreadySubscribe.compare_exchange_strong(except, true)) {
1106 return;
1107 }
1108 EventFwk::MatchingSkills matchingSkills;
1109 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BUNDLE_SCAN_FINISHED);
1110 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
1111 subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
1112 auto sysEventSubscriber = std::make_shared<SysEventSubscriber>(subscribeInfo);
1113 if (!EventFwk::CommonEventManager::SubscribeCommonEvent(sysEventSubscriber)) {
1114 ZLOGE("Subscribe sys event failed.");
1115 alreadySubscribe = false;
1116 }
1117 if (BundleMgrProxy::GetInstance()->CheckBMS() != nullptr) {
1118 sysEventSubscriber->OnBMSReady();
1119 }
1120 }
1121
OnUserChange(uint32_t code,const std::string & user,const std::string & account)1122 int32_t DataShareServiceImpl::OnUserChange(uint32_t code, const std::string &user, const std::string &account)
1123 {
1124 ZLOGI("code:%{public}d, user:%{public}s, account:%{public}s", code, user.c_str(),
1125 Anonymous::Change(account).c_str());
1126 switch (code) {
1127 case static_cast<uint32_t>(AccountStatus::DEVICE_ACCOUNT_DELETE):
1128 case static_cast<uint32_t>(AccountStatus::DEVICE_ACCOUNT_STOPPED): {
1129 std::vector<int32_t> users;
1130 AccountDelegate::GetInstance()->QueryUsers(users);
1131 std::set<int32_t> userIds(users.begin(), users.end());
1132 userIds.insert(0);
1133 DBDelegate::Close([&userIds](const std::string &userId) {
1134 if (userIds.count(atoi(userId.c_str())) == 0) {
1135 ZLOGW("Illegal use of database by user %{public}s", userId.c_str());
1136 return true;
1137 }
1138 return false;
1139 });
1140 break;
1141 }
1142 case static_cast<uint32_t>(AccountStatus::DEVICE_ACCOUNT_STOPPING):
1143 DBDelegate::Close([&user](const std::string &userId) {
1144 return user == userId;
1145 });
1146 break;
1147 default:
1148 break;
1149 }
1150 return E_OK;
1151 }
1152
ReportExcuteFault(uint32_t callingTokenId,DataProviderConfig::ProviderInfo & providerInfo,int32_t errCode,std::string & func)1153 void DataShareServiceImpl::ReportExcuteFault(uint32_t callingTokenId, DataProviderConfig::ProviderInfo &providerInfo,
1154 int32_t errCode, std::string &func)
1155 {
1156 std::string appendix = "callingName:" + HiViewFaultAdapter::GetCallingName(callingTokenId).first;
1157 DataShareFaultInfo faultInfo = {HiViewFaultAdapter::curdFailed, providerInfo.bundleName, providerInfo.moduleName,
1158 providerInfo.storeName, func, errCode, appendix};
1159 HiViewFaultAdapter::ReportDataFault(faultInfo);
1160 }
1161
VerifyPermission(const std::string & bundleName,const std::string & permission,bool isFromExtension,const int32_t tokenId)1162 bool DataShareServiceImpl::VerifyPermission(const std::string &bundleName, const std::string &permission,
1163 bool isFromExtension, const int32_t tokenId)
1164 {
1165 // Provider from extension, allows empty permissions, not configured to allow access.
1166 if (isFromExtension) {
1167 if (!permission.empty() && !PermitDelegate::VerifyPermission(permission, tokenId)) {
1168 return false;
1169 }
1170 } else {
1171 Security::AccessToken::HapTokenInfo tokenInfo;
1172 auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo);
1173 if (result == Security::AccessToken::RET_SUCCESS && tokenInfo.bundleName == bundleName) {
1174 return true;
1175 }
1176 // Provider from ProxyData, which does not allow empty permissions and cannot be access without configured
1177 if (permission.empty()) {
1178 ZLOGE("Permission empty! token:0x%{public}x, bundleName:%{public}s", tokenId, bundleName.c_str());
1179 return false;
1180 }
1181 // If the permission is NO_PERMISSION, access is also allowed
1182 if (permission != NO_PERMISSION && !PermitDelegate::VerifyPermission(permission, tokenId)) {
1183 return false;
1184 }
1185 }
1186 return true;
1187 }
1188 } // namespace OHOS::DataShare
1189