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