1 /*
2 * Copyright (c) 2022-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 #include "static_subscriber_manager.h"
17
18 #include <fstream>
19 #include <set>
20
21 #include "ability_manager_helper.h"
22 #include "access_token_helper.h"
23 #include "bundle_manager_helper.h"
24 #include "ces_inner_error_code.h"
25 #include "common_event_constant.h"
26 #include "common_event_support.h"
27 #include "event_log_wrapper.h"
28 #include "event_report.h"
29 #include "hitrace_meter_adapter.h"
30 #include "ipc_skeleton.h"
31 #include "os_account_manager_helper.h"
32 #include "static_subscriber_data_manager.h"
33
34 namespace OHOS {
35 namespace EventFwk {
36 namespace {
37 const std::string CONFIG_APPS = "apps";
38 constexpr static char JSON_KEY_COMMON_EVENTS[] = "commonEvents";
39 constexpr static char JSON_KEY_NAME[] = "name";
40 constexpr static char JSON_KEY_PERMISSION[] = "permission";
41 constexpr static char JSON_KEY_EVENTS[] = "events";
42 }
43
StaticSubscriberManager()44 StaticSubscriberManager::StaticSubscriberManager() {}
45
~StaticSubscriberManager()46 StaticSubscriberManager::~StaticSubscriberManager() {}
47
InitAllowList()48 bool StaticSubscriberManager::InitAllowList()
49 {
50 EVENT_LOGD("enter");
51
52 std::vector<AppExecFwk::ApplicationInfo> appInfos {};
53 if (!DelayedSingleton<BundleManagerHelper>::GetInstance()
54 ->GetApplicationInfos(AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, appInfos)) {
55 EVENT_LOGE("GetApplicationInfos failed");
56 return false;
57 }
58
59 for (auto const &appInfo : appInfos) {
60 std::vector<std::string> allowCommonEvents = appInfo.allowCommonEvent;
61 std::string bundleName = appInfo.bundleName;
62 for (auto e : allowCommonEvents) {
63 if (staticSubscribers_.find(bundleName) == staticSubscribers_.end()) {
64 std::set<std::string> s = {};
65 s.emplace(e);
66 StaticSubscriber subscriber = { .events = s, .enable = true };
67 staticSubscribers_.insert(std::make_pair(bundleName, subscriber));
68 } else {
69 staticSubscribers_[bundleName].events.emplace(e);
70 }
71 }
72 }
73
74 hasInitAllowList_ = true;
75 return true;
76 }
77
InitValidSubscribers()78 bool StaticSubscriberManager::InitValidSubscribers()
79 {
80 EVENT_LOGD("enter");
81
82 if (!validSubscribers_.empty()) {
83 validSubscribers_.clear();
84 }
85 std::vector<AppExecFwk::ExtensionAbilityInfo> extensions;
86 // get all static subscriber type extensions
87 if (!DelayedSingleton<BundleManagerHelper>::GetInstance()->QueryExtensionInfos(extensions)) {
88 EVENT_LOGE("QueryExtensionInfos failed");
89 return false;
90 }
91 std::set<std::string> disableStaticSubscribeAllData;
92 int32_t ret = DelayedSingleton<StaticSubscriberDataManager>::GetInstance()->QueryDisableStaticSubscribeAllData(
93 disableStaticSubscribeAllData);
94 // filter legal extensions and add them to valid map
95 for (auto extension : extensions) {
96 if (staticSubscribers_.find(extension.bundleName) == staticSubscribers_.end()) {
97 continue;
98 }
99 if (ret == ERR_OK) {
100 InitDisableStaticSubscribersStates(disableStaticSubscribeAllData, extension.bundleName);
101 }
102 EVENT_LOGD("find legal extension, bundlename = %{public}s", extension.bundleName.c_str());
103 AddSubscriber(extension, staticSubscribers_[extension.bundleName].enable);
104 }
105 hasInitValidSubscribers_ = true;
106 return true;
107 }
108
PublishCommonEvent(const CommonEventData & data,const CommonEventPublishInfo & publishInfo,const Security::AccessToken::AccessTokenID & callerToken,const int32_t & userId,const sptr<IRemoteObject> & service,const std::string & bundleName)109 void StaticSubscriberManager::PublishCommonEvent(const CommonEventData &data,
110 const CommonEventPublishInfo &publishInfo, const Security::AccessToken::AccessTokenID &callerToken,
111 const int32_t &userId, const sptr<IRemoteObject> &service, const std::string &bundleName)
112 {
113 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
114 EVENT_LOGD("enter, event = %{public}s, userId = %{public}d", data.GetWant().GetAction().c_str(), userId);
115
116 std::lock_guard<std::mutex> lock(subscriberMutex_);
117 if (!hasInitAllowList_ && !InitAllowList()) {
118 EVENT_LOGE("failed to init subscriber list");
119 return;
120 }
121
122 if ((!hasInitValidSubscribers_ ||
123 data.GetWant().GetAction() == CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED ||
124 data.GetWant().GetAction() == CommonEventSupport::COMMON_EVENT_LOCKED_BOOT_COMPLETED ||
125 data.GetWant().GetAction() == CommonEventSupport::COMMON_EVENT_USER_SWITCHED ||
126 data.GetWant().GetAction() == CommonEventSupport::COMMON_EVENT_UID_REMOVED ||
127 data.GetWant().GetAction() == CommonEventSupport::COMMON_EVENT_USER_STARTED) &&
128 !InitValidSubscribers()) {
129 EVENT_LOGE("failed to init Init valid subscribers map!");
130 return;
131 }
132
133 UpdateSubscriber(data);
134
135 auto targetSubscribers = validSubscribers_.find(data.GetWant().GetAction());
136 if (targetSubscribers != validSubscribers_.end()) {
137 for (auto subscriber : targetSubscribers->second) {
138 EVENT_LOGI("subscriber.userId = %{public}d, userId = %{public}d, event = %{public}s", subscriber.userId,
139 userId, data.GetWant().GetAction().c_str());
140 if (!subscriber.enable) {
141 EVENT_LOGW("current subscriber is disable, subscriber.userId = %{public}d", subscriber.userId);
142 SendStaticEventProcErrHiSysEvent(userId, bundleName, subscriber.bundleName, data.GetWant().GetAction());
143 continue;
144 }
145 if (subscriber.userId < SUBSCRIBE_USER_SYSTEM_BEGIN) {
146 EVENT_LOGW("subscriber userId is invalid, subscriber.userId = %{public}d", subscriber.userId);
147 SendStaticEventProcErrHiSysEvent(userId, bundleName, subscriber.bundleName, data.GetWant().GetAction());
148 continue;
149 }
150 if ((subscriber.userId > SUBSCRIBE_USER_SYSTEM_END) && (userId != ALL_USER)
151 && (subscriber.userId != userId)) {
152 EVENT_LOGW("subscriber userId is not match, subscriber.userId = %{public}d, userId = %{public}d",
153 subscriber.userId, userId);
154 SendStaticEventProcErrHiSysEvent(userId, bundleName, subscriber.bundleName, data.GetWant().GetAction());
155 continue;
156 }
157 // judge if app is system app.
158 if (!DelayedSingleton<BundleManagerHelper>::GetInstance()->
159 CheckIsSystemAppByBundleName(subscriber.bundleName, subscriber.userId)) {
160 EVENT_LOGW("subscriber is not system app, not allow.");
161 continue;
162 }
163 if (!VerifyPublisherPermission(callerToken, subscriber.permission)) {
164 EVENT_LOGW("publisher does not have required permission %{public}s", subscriber.permission.c_str());
165 SendStaticEventProcErrHiSysEvent(userId, bundleName, subscriber.bundleName, data.GetWant().GetAction());
166 continue;
167 }
168 if (!VerifySubscriberPermission(subscriber.bundleName, subscriber.userId,
169 publishInfo.GetSubscriberPermissions())) {
170 EVENT_LOGW("subscriber does not have required permissions");
171 SendStaticEventProcErrHiSysEvent(userId, bundleName, subscriber.bundleName, data.GetWant().GetAction());
172 continue;
173 }
174 if (!publishInfo.GetBundleName().empty() && subscriber.bundleName != publishInfo.GetBundleName()) {
175 EVENT_LOGW("subscriber bundleName is not match, subscriber.bundleName = %{public}s, "
176 "bundleName = %{public}s", subscriber.bundleName.c_str(), publishInfo.GetBundleName().c_str());
177 continue;
178 }
179 AAFwk::Want want;
180 want.SetElementName(subscriber.bundleName, subscriber.name);
181 EVENT_LOGD("Ready to connect to subscriber %{public}s in bundle %{public}s",
182 subscriber.name.c_str(), subscriber.bundleName.c_str());
183 DelayedSingleton<AbilityManagerHelper>::GetInstance()->
184 ConnectAbility(want, data, service, subscriber.userId);
185 }
186 }
187 }
188
VerifyPublisherPermission(const Security::AccessToken::AccessTokenID & callerToken,const std::string & permission)189 bool StaticSubscriberManager::VerifyPublisherPermission(const Security::AccessToken::AccessTokenID &callerToken,
190 const std::string &permission)
191 {
192 EVENT_LOGD("enter");
193 if (permission.empty()) {
194 EVENT_LOGD("no need permission");
195 return true;
196 }
197 return AccessTokenHelper::VerifyAccessToken(callerToken, permission);
198 }
199
VerifySubscriberPermission(const std::string & bundleName,const int32_t & userId,const std::vector<std::string> & permissions)200 bool StaticSubscriberManager::VerifySubscriberPermission(const std::string &bundleName, const int32_t &userId,
201 const std::vector<std::string> &permissions)
202 {
203 // get hap tokenid with default instindex(0), this should be modified later.
204 Security::AccessToken::AccessTokenID tokenId = AccessTokenHelper::GetHapTokenID(userId, bundleName, 0);
205 for (auto permission : permissions) {
206 if (permission.empty()) {
207 continue;
208 }
209 if (!AccessTokenHelper::VerifyAccessToken(tokenId, permission)) {
210 EVENT_LOGW("subscriber does not have required permission : %{public}s", permission.c_str());
211 return false;
212 }
213 }
214 return true;
215 }
216
ParseEvents(const std::string & extensionName,const std::string & extensionBundleName,const int32_t & extensionUserId,const std::string & profile,bool enable)217 void StaticSubscriberManager::ParseEvents(const std::string &extensionName, const std::string &extensionBundleName,
218 const int32_t &extensionUserId, const std::string &profile, bool enable)
219 {
220 EVENT_LOGD("enter, subscriber name = %{public}s, bundle name = %{public}s, userId = %{public}d",
221 extensionName.c_str(), extensionBundleName.c_str(), extensionUserId);
222
223 if (profile.empty()) {
224 EVENT_LOGE("invalid profile");
225 return;
226 }
227 if (!nlohmann::json::accept(profile.c_str())) {
228 EVENT_LOGE("invalid format profile");
229 return;
230 }
231
232 nlohmann::json jsonObj = nlohmann::json::parse(profile, nullptr, false);
233 if (jsonObj.is_null() || jsonObj.empty()) {
234 EVENT_LOGE("invalid jsonObj");
235 return;
236 }
237 nlohmann::json commonEventsObj = jsonObj[JSON_KEY_COMMON_EVENTS];
238 if (commonEventsObj.is_null() || !commonEventsObj.is_array() || commonEventsObj.empty()) {
239 EVENT_LOGE("invalid common event obj size");
240 return;
241 }
242 for (auto commonEventObj : commonEventsObj) {
243 if (commonEventObj.is_null() || !commonEventObj.is_object()) {
244 EVENT_LOGW("invalid common event obj");
245 continue;
246 }
247 if (commonEventObj[JSON_KEY_NAME].is_null() || !commonEventObj[JSON_KEY_NAME].is_string()) {
248 EVENT_LOGW("invalid common event ability name obj");
249 continue;
250 }
251 if (commonEventObj[JSON_KEY_NAME].get<std::string>() != extensionName) {
252 EVENT_LOGW("extensionName is not match");
253 continue;
254 }
255 if (commonEventObj[JSON_KEY_PERMISSION].is_null() || !commonEventObj[JSON_KEY_PERMISSION].is_string()) {
256 EVENT_LOGW("invalid permission obj");
257 continue;
258 }
259 if (commonEventObj[JSON_KEY_EVENTS].is_null() || !commonEventObj[JSON_KEY_EVENTS].is_array() ||
260 commonEventObj[JSON_KEY_EVENTS].empty()) {
261 EVENT_LOGW("invalid events obj");
262 continue;
263 }
264
265 for (auto e : commonEventObj[JSON_KEY_EVENTS]) {
266 if (e.is_null() || !e.is_string() ||
267 (staticSubscribers_[extensionBundleName].events.find(e) ==
268 staticSubscribers_[extensionBundleName].events.end())) {
269 EVENT_LOGW("invalid event obj");
270 continue;
271 }
272 StaticSubscriberInfo subscriber = { .name = extensionName,
273 .bundleName = extensionBundleName,
274 .userId = extensionUserId,
275 .permission = commonEventObj[JSON_KEY_PERMISSION].get<std::string>(),
276 .enable = enable };
277 AddToValidSubscribers(e.get<std::string>(), subscriber);
278 }
279 }
280 }
281
AddSubscriber(const AppExecFwk::ExtensionAbilityInfo & extension,bool enable)282 void StaticSubscriberManager::AddSubscriber(const AppExecFwk::ExtensionAbilityInfo &extension, bool enable)
283 {
284 EVENT_LOGD("enter, subscriber bundlename = %{public}s", extension.bundleName.c_str());
285
286 std::vector<std::string> profileInfos;
287 if (!DelayedSingleton<BundleManagerHelper>::GetInstance()->GetResConfigFile(extension, profileInfos)) {
288 EVENT_LOGE("GetProfile failed");
289 return;
290 }
291 for (auto profile : profileInfos) {
292 int32_t userId = -1;
293 if (DelayedSingleton<OsAccountManagerHelper>::GetInstance()->GetOsAccountLocalIdFromUid(
294 extension.applicationInfo.uid, userId) != ERR_OK) {
295 EVENT_LOGE("GetOsAccountLocalIdFromUid failed, uid = %{public}d", extension.applicationInfo.uid);
296 return;
297 }
298 ParseEvents(extension.name, extension.bundleName, userId, profile, enable);
299 }
300 }
301
AddToValidSubscribers(const std::string & eventName,const StaticSubscriberInfo & subscriber)302 void StaticSubscriberManager::AddToValidSubscribers(const std::string &eventName,
303 const StaticSubscriberInfo &subscriber)
304 {
305 if (validSubscribers_.find(eventName) != validSubscribers_.end()) {
306 for (auto sub : validSubscribers_[eventName]) {
307 if ((sub.name == subscriber.name) &&
308 (sub.bundleName == subscriber.bundleName) &&
309 (sub.userId == subscriber.userId)) {
310 EVENT_LOGD("subscriber already exist, event = %{public}s, bundlename = %{public}s, name = %{public}s,"
311 "userId = %{public}d", eventName.c_str(), subscriber.bundleName.c_str(), subscriber.name.c_str(),
312 subscriber.userId);
313 return;
314 }
315 }
316 }
317 validSubscribers_[eventName].emplace_back(subscriber);
318 EVENT_LOGD("subscriber added, event = %{public}s, bundlename = %{public}s, name = %{public}s, userId = %{public}d",
319 eventName.c_str(), subscriber.bundleName.c_str(), subscriber.name.c_str(), subscriber.userId);
320 }
321
AddSubscriberWithBundleName(const std::string & bundleName,const int32_t & userId)322 void StaticSubscriberManager::AddSubscriberWithBundleName(const std::string &bundleName, const int32_t &userId)
323 {
324 EVENT_LOGD("enter, bundleName = %{public}s, userId = %{public}d", bundleName.c_str(), userId);
325
326 std::vector<AppExecFwk::ExtensionAbilityInfo> extensions;
327 if (!DelayedSingleton<BundleManagerHelper>::GetInstance()->QueryExtensionInfos(extensions, userId)) {
328 EVENT_LOGE("QueryExtensionInfos failed");
329 return;
330 }
331
332 for (auto extension : extensions) {
333 if ((extension.bundleName == bundleName) &&
334 staticSubscribers_.find(extension.bundleName) != staticSubscribers_.end()) {
335 AddSubscriber(extension, staticSubscribers_[bundleName].enable);
336 }
337 }
338 }
339
RemoveSubscriberWithBundleName(const std::string & bundleName,const int32_t & userId)340 void StaticSubscriberManager::RemoveSubscriberWithBundleName(const std::string &bundleName, const int32_t &userId)
341 {
342 EVENT_LOGD("enter, bundleName = %{public}s, userId = %{public}d", bundleName.c_str(), userId);
343
344 for (auto it = validSubscribers_.begin(); it != validSubscribers_.end();) {
345 auto subIt = it->second.begin();
346 while (subIt != it->second.end()) {
347 if ((subIt->bundleName == bundleName) && (subIt->userId == userId)) {
348 EVENT_LOGD("remove subscriber, event = %{public}s, bundlename = %{public}s, userId = %{public}d",
349 it->first.c_str(), bundleName.c_str(), userId);
350 subIt = it->second.erase(subIt);
351 } else {
352 subIt++;
353 }
354 }
355 if (it->second.empty()) {
356 validSubscribers_.erase(it++);
357 } else {
358 it++;
359 }
360 }
361 }
362
UpdateSubscriber(const CommonEventData & data)363 void StaticSubscriberManager::UpdateSubscriber(const CommonEventData &data)
364 {
365 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
366 EVENT_LOGD("enter");
367
368 if ((data.GetWant().GetAction() != CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED) &&
369 (data.GetWant().GetAction() != CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED) &&
370 (data.GetWant().GetAction() != CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED)) {
371 EVENT_LOGD("no need to update map");
372 return;
373 }
374
375 std::string bundleName = data.GetWant().GetElement().GetBundleName();
376 int32_t uid = data.GetWant().GetIntParam(AppExecFwk::Constants::UID, -1);
377 int32_t userId = -1;
378 if (DelayedSingleton<OsAccountManagerHelper>::GetInstance()->GetOsAccountLocalIdFromUid(uid, userId) != ERR_OK) {
379 EVENT_LOGW("GetOsAccountLocalIdFromUid failed, uid = %{public}d", uid);
380 return;
381 }
382 std::vector<int> osAccountIds;
383 if (DelayedSingleton<OsAccountManagerHelper>::GetInstance()->QueryActiveOsAccountIds(osAccountIds) != ERR_OK) {
384 EVENT_LOGW("failed to QueryActiveOsAccountIds!");
385 return;
386 }
387 if (find(osAccountIds.begin(), osAccountIds.end(), userId) == osAccountIds.end()) {
388 EVENT_LOGW("userId is not active, no need to update.");
389 return;
390 }
391 EVENT_LOGD("active uid = %{public}d, userId = %{public}d", uid, userId);
392 if (data.GetWant().GetAction() == CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED) {
393 EVENT_LOGD("UpdateSubscribersMap bundle %{public}s ready to add", bundleName.c_str());
394 AddSubscriberWithBundleName(bundleName, userId);
395 } else if (data.GetWant().GetAction() == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) {
396 EVENT_LOGD("UpdateSubscribersMap bundle %{public}s ready to remove", bundleName.c_str());
397 RemoveSubscriberWithBundleName(bundleName, userId);
398 } else {
399 EVENT_LOGD("UpdateSubscribersMap bundle %{public}s ready to update", bundleName.c_str());
400 RemoveSubscriberWithBundleName(bundleName, userId);
401 AddSubscriberWithBundleName(bundleName, userId);
402 }
403 }
404
SendStaticEventProcErrHiSysEvent(int32_t userId,const std::string & publisherName,const std::string & subscriberName,const std::string & eventName)405 void StaticSubscriberManager::SendStaticEventProcErrHiSysEvent(int32_t userId, const std::string &publisherName,
406 const std::string &subscriberName, const std::string &eventName)
407 {
408 EventInfo eventInfo;
409 eventInfo.userId = userId;
410 eventInfo.publisherName = publisherName;
411 eventInfo.subscriberName = subscriberName;
412 eventInfo.eventName = eventName;
413 EventReport::SendHiSysEvent(STATIC_EVENT_PROC_ERROR, eventInfo);
414 }
415
SetStaticSubscriberState(bool enable)416 int32_t StaticSubscriberManager::SetStaticSubscriberState(bool enable)
417 {
418 uid_t uid = IPCSkeleton::GetCallingUid();
419 std::string bundleName = DelayedSingleton<BundleManagerHelper>::GetInstance()->GetBundleName(uid);
420 EVENT_LOGI("current bundleName:%{public}s, enable:%{public}d.", bundleName.c_str(), enable);
421 if (staticSubscribers_.find(bundleName) != staticSubscribers_.end()) {
422 staticSubscribers_[bundleName].enable = enable;
423 }
424 for (auto it = validSubscribers_.begin(); it != validSubscribers_.end();) {
425 for (auto subIt = it->second.begin(); subIt != it->second.end();) {
426 if (subIt->bundleName == bundleName) {
427 EVENT_LOGI("validSubscribers_ bundleName:%{public}s, enable:%{public}d.", bundleName.c_str(), enable);
428 subIt->enable = enable;
429 }
430 subIt++;
431 }
432 it++;
433 }
434 int32_t result = 0;
435 if (enable) {
436 result =
437 DelayedSingleton<StaticSubscriberDataManager>::GetInstance()->DeleteDisableStaticSubscribeData(bundleName);
438 } else {
439 result =
440 DelayedSingleton<StaticSubscriberDataManager>::GetInstance()->InsertDisableStaticSubscribeData(bundleName);
441 }
442 return result;
443 }
444
InitDisableStaticSubscribersStates(const std::set<std::string> & disableStaticSubscribeAllData,const std::string & bundleName)445 void StaticSubscriberManager::InitDisableStaticSubscribersStates(
446 const std::set<std::string> &disableStaticSubscribeAllData, const std::string &bundleName)
447 {
448 if (disableStaticSubscribeAllData.find(bundleName) != disableStaticSubscribeAllData.end()) {
449 if (staticSubscribers_.find(bundleName) != staticSubscribers_.end()) {
450 staticSubscribers_[bundleName].enable = false;
451 EVENT_LOGI("Current static subscriber bundleName:%{public}s is disable.", bundleName.c_str());
452 return;
453 }
454 }
455 }
456 } // namespace EventFwk
457 } // namespace OHOS
458