• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.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_LOGW("subscriber.userId = %{public}d, userId = %{public}d", subscriber.userId, userId);
139             if (!subscriber.enable) {
140                 EVENT_LOGW("current subscriber is disable, subscriber.userId = %{public}d", subscriber.userId);
141                 SendStaticEventProcErrHiSysEvent(userId, bundleName, subscriber.bundleName, data.GetWant().GetAction());
142                 continue;
143             }
144             if (subscriber.userId < SUBSCRIBE_USER_SYSTEM_BEGIN) {
145                 EVENT_LOGW("subscriber userId is invalid, subscriber.userId = %{public}d", subscriber.userId);
146                 SendStaticEventProcErrHiSysEvent(userId, bundleName, subscriber.bundleName, data.GetWant().GetAction());
147                 continue;
148             }
149             if ((subscriber.userId > SUBSCRIBE_USER_SYSTEM_END) && (userId != ALL_USER)
150                 && (subscriber.userId != userId)) {
151                 EVENT_LOGW("subscriber userId is not match, subscriber.userId = %{public}d, userId = %{public}d",
152                     subscriber.userId, userId);
153                 SendStaticEventProcErrHiSysEvent(userId, bundleName, subscriber.bundleName, data.GetWant().GetAction());
154                 continue;
155             }
156             // judge if app is system app.
157             if (!DelayedSingleton<BundleManagerHelper>::GetInstance()->
158                 CheckIsSystemAppByBundleName(subscriber.bundleName, subscriber.userId)) {
159                 EVENT_LOGW("subscriber is not system app, not allow.");
160                 continue;
161             }
162             if (!VerifyPublisherPermission(callerToken, subscriber.permission)) {
163                 EVENT_LOGW("publisher does not have required permission %{public}s", subscriber.permission.c_str());
164                 SendStaticEventProcErrHiSysEvent(userId, bundleName, subscriber.bundleName, data.GetWant().GetAction());
165                 continue;
166             }
167             if (!VerifySubscriberPermission(subscriber.bundleName, subscriber.userId,
168                 publishInfo.GetSubscriberPermissions())) {
169                 EVENT_LOGW("subscriber does not have required permissions");
170                 SendStaticEventProcErrHiSysEvent(userId, bundleName, subscriber.bundleName, data.GetWant().GetAction());
171                 continue;
172             }
173             if (!publishInfo.GetBundleName().empty() && subscriber.bundleName != publishInfo.GetBundleName()) {
174                 EVENT_LOGW("subscriber bundleName is not match, subscriber.bundleName = %{public}s, "
175                     "bundleName = %{public}s", subscriber.bundleName.c_str(), publishInfo.GetBundleName().c_str());
176                 continue;
177             }
178             AAFwk::Want want;
179             want.SetElementName(subscriber.bundleName, subscriber.name);
180             EVENT_LOGD("Ready to connect to subscriber %{public}s in bundle %{public}s",
181                 subscriber.name.c_str(), subscriber.bundleName.c_str());
182             DelayedSingleton<AbilityManagerHelper>::GetInstance()->
183                 ConnectAbility(want, data, service, subscriber.userId);
184         }
185     }
186 }
187 
VerifyPublisherPermission(const Security::AccessToken::AccessTokenID & callerToken,const std::string & permission)188 bool StaticSubscriberManager::VerifyPublisherPermission(const Security::AccessToken::AccessTokenID &callerToken,
189     const std::string &permission)
190 {
191     EVENT_LOGD("enter");
192     if (permission.empty()) {
193         EVENT_LOGD("no need permission");
194         return true;
195     }
196     return AccessTokenHelper::VerifyAccessToken(callerToken, permission);
197 }
198 
VerifySubscriberPermission(const std::string & bundleName,const int32_t & userId,const std::vector<std::string> & permissions)199 bool StaticSubscriberManager::VerifySubscriberPermission(const std::string &bundleName, const int32_t &userId,
200     const std::vector<std::string> &permissions)
201 {
202     // get hap tokenid with default instindex(0), this should be modified later.
203     Security::AccessToken::AccessTokenID tokenId = AccessTokenHelper::GetHapTokenID(userId, bundleName, 0);
204     for (auto permission : permissions) {
205         if (permission.empty()) {
206             continue;
207         }
208         if (!AccessTokenHelper::VerifyAccessToken(tokenId, permission)) {
209             EVENT_LOGW("subscriber does not have required permission : %{public}s", permission.c_str());
210             return false;
211         }
212     }
213     return true;
214 }
215 
ParseEvents(const std::string & extensionName,const std::string & extensionBundleName,const int32_t & extensionUserId,const std::string & profile,bool enable)216 void StaticSubscriberManager::ParseEvents(const std::string &extensionName, const std::string &extensionBundleName,
217     const int32_t &extensionUserId, const std::string &profile, bool enable)
218 {
219     EVENT_LOGD("enter, subscriber name = %{public}s, bundle name = %{public}s, userId = %{public}d",
220         extensionName.c_str(), extensionBundleName.c_str(), extensionUserId);
221 
222     if (profile.empty()) {
223         EVENT_LOGE("invalid profile");
224         return;
225     }
226     if (!nlohmann::json::accept(profile.c_str())) {
227         EVENT_LOGE("invalid format profile");
228         return;
229     }
230 
231     nlohmann::json jsonObj = nlohmann::json::parse(profile, nullptr, false);
232     if (jsonObj.is_null() || jsonObj.empty()) {
233         EVENT_LOGE("invalid jsonObj");
234         return;
235     }
236     nlohmann::json commonEventsObj = jsonObj[JSON_KEY_COMMON_EVENTS];
237     if (commonEventsObj.is_null() || !commonEventsObj.is_array() || commonEventsObj.empty()) {
238         EVENT_LOGE("invalid common event obj size");
239         return;
240     }
241     for (auto commonEventObj : commonEventsObj) {
242         if (commonEventObj.is_null() || !commonEventObj.is_object()) {
243             EVENT_LOGW("invalid common event obj");
244             continue;
245         }
246         if (commonEventObj[JSON_KEY_NAME].is_null() || !commonEventObj[JSON_KEY_NAME].is_string()) {
247             EVENT_LOGW("invalid common event ability name obj");
248             continue;
249         }
250         if (commonEventObj[JSON_KEY_NAME].get<std::string>() != extensionName) {
251             EVENT_LOGW("extensionName is not match");
252             continue;
253         }
254         if (commonEventObj[JSON_KEY_PERMISSION].is_null() || !commonEventObj[JSON_KEY_PERMISSION].is_string()) {
255             EVENT_LOGW("invalid permission obj");
256             continue;
257         }
258         if (commonEventObj[JSON_KEY_EVENTS].is_null() || !commonEventObj[JSON_KEY_EVENTS].is_array() ||
259             commonEventObj[JSON_KEY_EVENTS].empty()) {
260             EVENT_LOGW("invalid events obj");
261             continue;
262         }
263 
264         for (auto e : commonEventObj[JSON_KEY_EVENTS]) {
265             if (e.is_null() || !e.is_string() ||
266                 (staticSubscribers_[extensionBundleName].events.find(e) ==
267                     staticSubscribers_[extensionBundleName].events.end())) {
268                 EVENT_LOGW("invalid event obj");
269                 continue;
270             }
271             StaticSubscriberInfo subscriber = { .name = extensionName,
272                 .bundleName = extensionBundleName,
273                 .userId = extensionUserId,
274                 .permission = commonEventObj[JSON_KEY_PERMISSION].get<std::string>(),
275                 .enable = enable };
276             AddToValidSubscribers(e.get<std::string>(), subscriber);
277         }
278     }
279 }
280 
AddSubscriber(const AppExecFwk::ExtensionAbilityInfo & extension,bool enable)281 void StaticSubscriberManager::AddSubscriber(const AppExecFwk::ExtensionAbilityInfo &extension, bool enable)
282 {
283     EVENT_LOGD("enter, subscriber bundlename = %{public}s", extension.bundleName.c_str());
284 
285     std::vector<std::string> profileInfos;
286     if (!DelayedSingleton<BundleManagerHelper>::GetInstance()->GetResConfigFile(extension, profileInfos)) {
287         EVENT_LOGE("GetProfile failed");
288         return;
289     }
290     for (auto profile : profileInfos) {
291         int32_t userId = -1;
292         if (DelayedSingleton<OsAccountManagerHelper>::GetInstance()->GetOsAccountLocalIdFromUid(
293             extension.applicationInfo.uid, userId) != ERR_OK) {
294             EVENT_LOGE("GetOsAccountLocalIdFromUid failed, uid = %{public}d", extension.applicationInfo.uid);
295             return;
296         }
297         ParseEvents(extension.name, extension.bundleName, userId, profile, enable);
298     }
299 }
300 
AddToValidSubscribers(const std::string & eventName,const StaticSubscriberInfo & subscriber)301 void StaticSubscriberManager::AddToValidSubscribers(const std::string &eventName,
302     const StaticSubscriberInfo &subscriber)
303 {
304     if (validSubscribers_.find(eventName) != validSubscribers_.end()) {
305         for (auto sub : validSubscribers_[eventName]) {
306             if ((sub.name == subscriber.name) &&
307                 (sub.bundleName == subscriber.bundleName) &&
308                 (sub.userId == subscriber.userId)) {
309                 EVENT_LOGD("subscriber already exist, event = %{public}s, bundlename = %{public}s, name = %{public}s,"
310                     "userId = %{public}d", eventName.c_str(), subscriber.bundleName.c_str(), subscriber.name.c_str(),
311                     subscriber.userId);
312                 return;
313             }
314         }
315     }
316     validSubscribers_[eventName].emplace_back(subscriber);
317     EVENT_LOGD("subscriber added, event = %{public}s, bundlename = %{public}s, name = %{public}s, userId = %{public}d",
318         eventName.c_str(), subscriber.bundleName.c_str(), subscriber.name.c_str(), subscriber.userId);
319 }
320 
AddSubscriberWithBundleName(const std::string & bundleName,const int32_t & userId)321 void StaticSubscriberManager::AddSubscriberWithBundleName(const std::string &bundleName, const int32_t &userId)
322 {
323     EVENT_LOGD("enter, bundleName = %{public}s, userId = %{public}d", bundleName.c_str(), userId);
324 
325     std::vector<AppExecFwk::ExtensionAbilityInfo> extensions;
326     if (!DelayedSingleton<BundleManagerHelper>::GetInstance()->QueryExtensionInfos(extensions, userId)) {
327         EVENT_LOGE("QueryExtensionInfos failed");
328         return;
329     }
330 
331     for (auto extension : extensions) {
332         if ((extension.bundleName == bundleName) &&
333             staticSubscribers_.find(extension.bundleName) != staticSubscribers_.end()) {
334             AddSubscriber(extension, staticSubscribers_[bundleName].enable);
335         }
336     }
337 }
338 
RemoveSubscriberWithBundleName(const std::string & bundleName,const int32_t & userId)339 void StaticSubscriberManager::RemoveSubscriberWithBundleName(const std::string &bundleName, const int32_t &userId)
340 {
341     EVENT_LOGD("enter, bundleName = %{public}s, userId = %{public}d", bundleName.c_str(), userId);
342 
343     for (auto it = validSubscribers_.begin(); it != validSubscribers_.end();) {
344         auto subIt = it->second.begin();
345         while (subIt != it->second.end()) {
346             if ((subIt->bundleName == bundleName) && (subIt->userId == userId)) {
347                 EVENT_LOGD("remove subscriber, event = %{public}s, bundlename = %{public}s, userId = %{public}d",
348                     it->first.c_str(), bundleName.c_str(), userId);
349                 subIt = it->second.erase(subIt);
350             } else {
351                 subIt++;
352             }
353         }
354         if (it->second.empty()) {
355             validSubscribers_.erase(it++);
356         } else {
357             it++;
358         }
359     }
360 }
361 
UpdateSubscriber(const CommonEventData & data)362 void StaticSubscriberManager::UpdateSubscriber(const CommonEventData &data)
363 {
364     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
365     EVENT_LOGD("enter");
366 
367     if ((data.GetWant().GetAction() != CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED) &&
368         (data.GetWant().GetAction() != CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED) &&
369         (data.GetWant().GetAction() != CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED)) {
370         EVENT_LOGD("no need to update map");
371         return;
372     }
373 
374     std::string bundleName = data.GetWant().GetElement().GetBundleName();
375     int32_t uid = data.GetWant().GetIntParam(AppExecFwk::Constants::UID, -1);
376     int32_t userId = -1;
377     if (DelayedSingleton<OsAccountManagerHelper>::GetInstance()->GetOsAccountLocalIdFromUid(uid, userId) != ERR_OK) {
378         EVENT_LOGW("GetOsAccountLocalIdFromUid failed, uid = %{public}d", uid);
379         return;
380     }
381     std::vector<int> osAccountIds;
382     if (DelayedSingleton<OsAccountManagerHelper>::GetInstance()->QueryActiveOsAccountIds(osAccountIds) != ERR_OK) {
383         EVENT_LOGW("failed to QueryActiveOsAccountIds!");
384         return;
385     }
386     if (find(osAccountIds.begin(), osAccountIds.end(), userId) == osAccountIds.end()) {
387         EVENT_LOGW("userId is not active, no need to update.");
388         return;
389     }
390     EVENT_LOGD("active uid = %{public}d, userId = %{public}d", uid, userId);
391     if (data.GetWant().GetAction() == CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED) {
392         EVENT_LOGD("UpdateSubscribersMap bundle %{public}s ready to add", bundleName.c_str());
393         AddSubscriberWithBundleName(bundleName, userId);
394     } else if (data.GetWant().GetAction() == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) {
395         EVENT_LOGD("UpdateSubscribersMap bundle %{public}s ready to remove", bundleName.c_str());
396         RemoveSubscriberWithBundleName(bundleName, userId);
397     } else {
398         EVENT_LOGD("UpdateSubscribersMap bundle %{public}s ready to update", bundleName.c_str());
399         RemoveSubscriberWithBundleName(bundleName, userId);
400         AddSubscriberWithBundleName(bundleName, userId);
401     }
402 }
403 
SendStaticEventProcErrHiSysEvent(int32_t userId,const std::string & publisherName,const std::string & subscriberName,const std::string & eventName)404 void StaticSubscriberManager::SendStaticEventProcErrHiSysEvent(int32_t userId, const std::string &publisherName,
405     const std::string &subscriberName, const std::string &eventName)
406 {
407     EventInfo eventInfo;
408     eventInfo.userId = userId;
409     eventInfo.publisherName = publisherName;
410     eventInfo.subscriberName = subscriberName;
411     eventInfo.eventName = eventName;
412     EventReport::SendHiSysEvent(STATIC_EVENT_PROC_ERROR, eventInfo);
413 }
414 
SetStaticSubscriberState(bool enable)415 int32_t StaticSubscriberManager::SetStaticSubscriberState(bool enable)
416 {
417     uid_t uid = IPCSkeleton::GetCallingUid();
418     std::string bundleName = DelayedSingleton<BundleManagerHelper>::GetInstance()->GetBundleName(uid);
419     EVENT_LOGI("current bundleName:%{public}s, enable:%{public}d.", bundleName.c_str(), enable);
420     if (staticSubscribers_.find(bundleName) != staticSubscribers_.end()) {
421         staticSubscribers_[bundleName].enable = enable;
422     }
423     for (auto it = validSubscribers_.begin(); it != validSubscribers_.end();) {
424         for (auto subIt = it->second.begin(); subIt != it->second.end();) {
425             if (subIt->bundleName == bundleName) {
426                 EVENT_LOGI("validSubscribers_ bundleName:%{public}s, enable:%{public}d.", bundleName.c_str(), enable);
427                 subIt->enable = enable;
428             }
429             subIt++;
430         }
431         it++;
432     }
433     int32_t result = 0;
434     if (enable) {
435         result =
436             DelayedSingleton<StaticSubscriberDataManager>::GetInstance()->DeleteDisableStaticSubscribeData(bundleName);
437     } else {
438         result =
439             DelayedSingleton<StaticSubscriberDataManager>::GetInstance()->InsertDisableStaticSubscribeData(bundleName);
440     }
441     return result;
442 }
443 
InitDisableStaticSubscribersStates(const std::set<std::string> & disableStaticSubscribeAllData,const std::string & bundleName)444 void StaticSubscriberManager::InitDisableStaticSubscribersStates(
445     const std::set<std::string> &disableStaticSubscribeAllData, const std::string &bundleName)
446 {
447     if (disableStaticSubscribeAllData.find(bundleName) != disableStaticSubscribeAllData.end()) {
448         if (staticSubscribers_.find(bundleName) != staticSubscribers_.end()) {
449             staticSubscribers_[bundleName].enable = false;
450             EVENT_LOGI("Current static subscriber bundleName:%{public}s is disable.", bundleName.c_str());
451             return;
452         }
453     }
454 }
455 }  // namespace EventFwk
456 }  // namespace OHOS
457