1 /*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "common_event_subscriber_manager.h"
16
17 #include <csignal>
18 #include <utility>
19 #include <vector>
20 #include <set>
21
22 #include "ability_manager_client.h"
23 #include "access_token_helper.h"
24 #include "common_event_permission_manager.h"
25 #include "common_event_support.h"
26 #include "event_log_wrapper.h"
27 #include "event_trace_wrapper.h"
28 #include "event_report.h"
29 #include "hisysevent.h"
30 #include "hitrace_meter_adapter.h"
31 #include "subscriber_death_recipient.h"
32 #ifdef WATCH_CUSTOMIZED_SCREEN_EVENT_TO_OTHER_APP
33 #include <dlfcn.h>
34 #endif
35
36 namespace OHOS {
37 namespace EventFwk {
38 constexpr int32_t LENGTH = 80;
39 constexpr int32_t SIGNAL_KILL = 9;
40 static constexpr int32_t SUBSCRIBE_EVENT_MAX_NUM = 512;
41 static constexpr char CES_REGISTER_EXCEED_LIMIT[] = "Kill Reason: CES Register exceed limit";
42 const std::string CONNECTOR = " or ";
43
44 #ifdef WATCH_CUSTOMIZED_SCREEN_EVENT_TO_OTHER_APP
45 static const char *POWER_MANAGER_EXT_PATH = "libpower_manager_ext.z.so";
46 static const char *WATCH_SUBSCRIBE_SCREEN_EVENT_TO_OTHER_APP = "WatchSubscribeScreenEventToOtherApp";
47 void *handler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
48 typedef bool (*FuncSubscriber)(std::vector<std::string>, std::vector<int32_t>, std::string, int);
49 FuncSubscriber SubscribeScreenEventToBlackListAppFlag =
50 reinterpret_cast<FuncSubscriber>(dlsym(handler, WATCH_SUBSCRIBE_SCREEN_EVENT_TO_OTHER_APP));
51 #endif
52
CommonEventSubscriberManager()53 CommonEventSubscriberManager::CommonEventSubscriberManager()
54 : death_(sptr<IRemoteObject::DeathRecipient>(new (std::nothrow) SubscriberDeathRecipient()))
55 {}
56
~CommonEventSubscriberManager()57 CommonEventSubscriberManager::~CommonEventSubscriberManager() {}
58
InsertSubscriber(const SubscribeInfoPtr & eventSubscribeInfo,const sptr<IRemoteObject> & commonEventListener,const struct tm & recordTime,const EventRecordInfo & eventRecordInfo)59 std::shared_ptr<EventSubscriberRecord> CommonEventSubscriberManager::InsertSubscriber(
60 const SubscribeInfoPtr &eventSubscribeInfo, const sptr<IRemoteObject> &commonEventListener,
61 const struct tm &recordTime, const EventRecordInfo &eventRecordInfo)
62 {
63 NOTIFICATION_HITRACE(HITRACE_TAG_NOTIFICATION);
64 EVENT_LOGD("enter");
65
66 if (eventSubscribeInfo == nullptr) {
67 EVENT_LOGE("eventSubscribeInfo is null");
68 return nullptr;
69 }
70
71 if (commonEventListener == nullptr) {
72 EVENT_LOGE("commonEventListener is null");
73 return nullptr;
74 }
75
76 std::vector<std::string> events = eventSubscribeInfo->GetMatchingSkills().GetEvents();
77 if (events.size() == 0 || events.size() > SUBSCRIBE_EVENT_MAX_NUM) {
78 EVENT_LOGE("subscribed events size is error");
79 return nullptr;
80 }
81
82 auto record = std::make_shared<EventSubscriberRecord>();
83 if (record == nullptr) {
84 EVENT_LOGE("Failed to create EventSubscriberRecord");
85 return nullptr;
86 }
87
88 record->eventSubscribeInfo = eventSubscribeInfo;
89 record->commonEventListener = commonEventListener;
90 record->recordTime = recordTime;
91 record->eventRecordInfo = eventRecordInfo;
92
93 if (death_ != nullptr) {
94 commonEventListener->AddDeathRecipient(death_);
95 }
96
97 if (!InsertSubscriberRecordLocked(events, record)) {
98 return nullptr;
99 }
100
101 if (eventRecordInfo.uid != SAMGR_UID) {
102 for (auto event : events) {
103 bool isSystemEvent = DelayedSingleton<CommonEventSupport>::GetInstance()->IsSystemEvent(event);
104 if (!isSystemEvent && eventSubscribeInfo->GetPermission().empty() &&
105 eventSubscribeInfo->GetPublisherBundleName().empty() && eventSubscribeInfo->GetPublisherUid() == 0) {
106 EVENT_LOGW("Subscribe %{public}s without any restrict subid = %{public}s, bundle = %{public}s",
107 event.c_str(), eventRecordInfo.subId.c_str(), eventRecordInfo.bundleName.c_str());
108 }
109 }
110 }
111
112 return record;
113 }
114
RemoveSubscriber(const sptr<IRemoteObject> & commonEventListener)115 int CommonEventSubscriberManager::RemoveSubscriber(const sptr<IRemoteObject> &commonEventListener)
116 {
117 NOTIFICATION_HITRACE(HITRACE_TAG_NOTIFICATION);
118 EVENT_LOGD("enter");
119
120 if (commonEventListener == nullptr) {
121 EVENT_LOGE("commonEventListener is null");
122 return ERR_INVALID_VALUE;
123 }
124
125 int res = RemoveSubscriberRecordLocked(commonEventListener);
126 return res;
127 }
128
GetSubscriberRecords(const CommonEventRecord & eventRecord)129 std::vector<std::shared_ptr<EventSubscriberRecord>> CommonEventSubscriberManager::GetSubscriberRecords(
130 const CommonEventRecord &eventRecord)
131 {
132 EVENT_LOGD("enter");
133
134 auto records = std::vector<SubscriberRecordPtr>();
135
136 GetSubscriberRecordsByWantLocked(eventRecord, records);
137
138 return records;
139 }
140
GetSubscriberRecord(const sptr<IRemoteObject> & commonEventListener)141 std::shared_ptr<EventSubscriberRecord> CommonEventSubscriberManager::GetSubscriberRecord(
142 const sptr<IRemoteObject> &commonEventListener)
143 {
144 std::lock_guard<ffrt::mutex> lock(mutex_);
145
146 for (auto it = subscribers_.begin(); it != subscribers_.end(); ++it) {
147 if (commonEventListener == (*it)->commonEventListener) {
148 return *it;
149 }
150 }
151
152 return nullptr;
153 }
154
DumpDetailed(const std::string & title,const SubscriberRecordPtr & record,const std::string format,std::string & dumpInfo)155 void CommonEventSubscriberManager::DumpDetailed(
156 const std::string &title, const SubscriberRecordPtr &record, const std::string format, std::string &dumpInfo)
157 {
158 if (record == nullptr || record->eventSubscribeInfo == nullptr) {
159 EVENT_LOGE("record or eventSubscribeInfo is null");
160 return;
161 }
162 char systime[LENGTH];
163 strftime(systime, sizeof(char) * LENGTH, "%Y%m%d %I:%M %p", &record->recordTime);
164
165 std::string recordTime = format + "Time: " + std::string(systime) + "\n";
166 std::string pid = format + "PID: " + std::to_string(record->eventRecordInfo.pid) + "\n";
167 std::string uid = format + "UID: " + std::to_string(record->eventRecordInfo.uid) + "\n";
168 std::string bundleName = format + "BundleName: " + record->eventRecordInfo.bundleName + "\n";
169 std::string priority = format + "Priority: " + std::to_string(record->eventSubscribeInfo->GetPriority()) + "\n";
170 std::string userId;
171 switch (record->eventSubscribeInfo->GetUserId()) {
172 case UNDEFINED_USER:
173 userId = "UNDEFINED_USER";
174 break;
175 case ALL_USER:
176 userId = "ALL_USER";
177 break;
178 default:
179 userId = std::to_string(record->eventSubscribeInfo->GetUserId());
180 break;
181 }
182 userId = format + "USERID: " + userId + "\n";
183 std::string permission = format + "Permission: " + record->eventSubscribeInfo->GetPermission() + "\n";
184 std::string deviceId = format + "DevicedID: " + record->eventSubscribeInfo->GetDeviceId() + "\n";
185
186 std::string events = format + "\tEvent: ";
187 std::string separator;
188 size_t countSize = record->eventSubscribeInfo->GetMatchingSkills().CountEvent();
189 for (size_t eventNum = 0; eventNum < countSize; ++eventNum) {
190 if (eventNum == 0) {
191 separator = "";
192 } else {
193 separator = ", ";
194 }
195 events = events + separator + record->eventSubscribeInfo->GetMatchingSkills().GetEvent(eventNum);
196 }
197 events = events + "\n";
198
199 std::string entities = format + "\tEntity: ";
200 size_t entitySize = record->eventSubscribeInfo->GetMatchingSkills().CountEntities();
201 for (size_t entityNum = 0; entityNum < entitySize; ++entityNum) {
202 if (entityNum == 0) {
203 separator = "";
204 } else {
205 separator = ", ";
206 }
207 entities = entities + separator + record->eventSubscribeInfo->GetMatchingSkills().GetEntity(entityNum);
208 }
209 entities = entities + "\n";
210
211 std::string scheme = format + "\tScheme: ";
212 size_t schemeSize = record->eventSubscribeInfo->GetMatchingSkills().CountSchemes();
213 for (size_t schemeNum = 0; schemeNum < schemeSize; ++schemeNum) {
214 if (schemeNum == 0) {
215 separator = "";
216 } else {
217 separator = ", ";
218 }
219 scheme = scheme + separator + record->eventSubscribeInfo->GetMatchingSkills().GetScheme(schemeNum);
220 }
221 scheme = scheme + "\n";
222
223 std::string matchingSkills = format + "MatchingSkills:\n" + events + entities + scheme;
224
225 std::string isFreeze = record->isFreeze ? "true" : "false";
226 isFreeze = format + "IsFreeze: " + isFreeze + "\n";
227
228 std::string freezeTime;
229 if (record->freezeTime == 0) {
230 freezeTime = format + "FreezeTime: -\n";
231 } else {
232 freezeTime = format + "FreezeTime: " + std::to_string(record->freezeTime) + "\n";
233 }
234
235 dumpInfo = title + recordTime + pid + uid + bundleName + priority + userId + permission + deviceId +
236 matchingSkills + isFreeze + freezeTime;
237 }
238
DumpState(const std::string & event,const int32_t & userId,std::vector<std::string> & state)239 void CommonEventSubscriberManager::DumpState(const std::string &event, const int32_t &userId,
240 std::vector<std::string> &state)
241 {
242 EVENT_LOGD("enter");
243
244 std::vector<SubscriberRecordPtr> records;
245
246 std::lock_guard<ffrt::mutex> lock(mutex_);
247 GetSubscriberRecordsByEvent(event, userId, records);
248
249 if (records.size() == 0) {
250 state.emplace_back("Subscribers:\tNo information");
251 return;
252 }
253
254 size_t num = 0;
255 for (auto record : records) {
256 num++;
257 std::string title = std::to_string(num);
258 if (num == 1) {
259 title = "Subscribers:\tTotal " + std::to_string(records.size()) + " subscribers\nNO " + title + "\n";
260 } else {
261 title = "NO " + title + "\n";
262 }
263 std::string dumpInfo;
264 DumpDetailed(title, record, "\t", dumpInfo);
265 state.emplace_back(dumpInfo);
266 }
267 }
268
InsertSubscriberRecordLocked(const std::vector<std::string> & events,const SubscriberRecordPtr & record)269 __attribute__((no_sanitize("cfi"))) bool CommonEventSubscriberManager::InsertSubscriberRecordLocked(
270 const std::vector<std::string> &events, const SubscriberRecordPtr &record)
271 {
272 EVENT_LOGD("enter");
273
274 if (events.size() == 0) {
275 EVENT_LOGE("No subscribed events");
276 return false;
277 }
278
279 if (record == nullptr) {
280 EVENT_LOGE("record is null");
281 return false;
282 }
283
284 std::lock_guard<ffrt::mutex> lock(mutex_);
285
286 pid_t pid = record->eventRecordInfo.pid;
287
288 if (CheckSubscriberCountReachedMaxinum()) {
289 std::vector<std::pair<pid_t, uint32_t>> vtSubscriberCounts = GetTopSubscriberCounts(1);
290 pid_t killedPid = (*vtSubscriberCounts.begin()).first;
291 if (pid == killedPid) {
292 return false;
293 }
294
295 AAFwk::ExitReason reason = { AAFwk::REASON_RESOURCE_CONTROL, "Kill Reason: CES Register exceed limit"};
296 AAFwk::AbilityManagerClient::GetInstance()->RecordProcessExitReason(killedPid, reason);
297 int killResult = kill(killedPid, SIGNAL_KILL);
298 EVENT_LOGI("kill pid=%{public}d which has the most subscribers %{public}s", killedPid,
299 killResult < 0 ? "failed" : "successfully");
300 int result = HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::FRAMEWORK, "PROCESS_KILL",
301 HiviewDFX::HiSysEvent::EventType::FAULT, "PID", killedPid, "PROCESS_NAME",
302 record->eventRecordInfo.bundleName, "MSG", CES_REGISTER_EXCEED_LIMIT);
303 EVENT_LOGW("hisysevent write result=%{public}d, send event [FRAMEWORK,PROCESS_KILL], pid=%{public}d,"
304 " processName=%{public}s, msg=%{public}s", result, killedPid, record->eventRecordInfo.bundleName.c_str(),
305 CES_REGISTER_EXCEED_LIMIT);
306 }
307
308 for (auto event : events) {
309 auto infoItem = eventSubscribers_.find(event);
310 if (infoItem != eventSubscribers_.end()) {
311 infoItem->second.insert(record);
312
313 if (infoItem->second.size() > MAX_SUBSCRIBER_NUM_PER_EVENT && record->eventSubscribeInfo != nullptr) {
314 EVENT_LOGW("%{public}s event has %{public}zu subscriber, please check", event.c_str(),
315 infoItem->second.size());
316 SendSubscriberExceedMaximumHiSysEvent(record->eventSubscribeInfo->GetUserId(), event,
317 infoItem->second.size());
318 }
319 } else {
320 std::set<SubscriberRecordPtr> EventSubscribersPtr;
321 EventSubscribersPtr.insert(record);
322 eventSubscribers_[event] = EventSubscribersPtr;
323 }
324 }
325
326 subscribers_.emplace_back(record);
327 subscriberCounts_[pid]++;
328
329 return true;
330 }
331
RemoveSubscriberRecordLocked(const sptr<IRemoteObject> & commonEventListener)332 int CommonEventSubscriberManager::RemoveSubscriberRecordLocked(const sptr<IRemoteObject> &commonEventListener)
333 {
334 if (commonEventListener == nullptr) {
335 EVENT_LOGE("commonEventListener is null");
336 return ERR_INVALID_VALUE;
337 }
338
339 if (death_ != nullptr) {
340 commonEventListener->RemoveDeathRecipient(death_);
341 }
342
343 std::lock_guard<ffrt::mutex> lock(mutex_);
344 std::vector<std::string> events;
345
346 for (auto it = subscribers_.begin(); it != subscribers_.end(); ++it) {
347 if (commonEventListener == (*it)->commonEventListener) {
348 RemoveFrozenEventsBySubscriber((*it));
349 RemoveFrozenEventsMapBySubscriber((*it));
350 events = (*it)->eventSubscribeInfo->GetMatchingSkills().GetEvents();
351 EVENT_LOGI("Unsubscribe %{public}s", (*it)->eventRecordInfo.subId.c_str());
352 pid_t pid = (*it)->eventRecordInfo.pid;
353 subscriberCounts_[pid] > 1 ? subscriberCounts_[pid]-- : subscriberCounts_.erase(pid);
354 subscribers_.erase(it);
355 break;
356 }
357 }
358
359 for (auto event : events) {
360 for (auto it = eventSubscribers_[event].begin(); it != eventSubscribers_[event].end(); ++it) {
361 if ((commonEventListener == (*it)->commonEventListener) || ((*it)->commonEventListener == nullptr)) {
362 eventSubscribers_[event].erase(it);
363 break;
364 }
365 }
366 if (eventSubscribers_[event].size() == 0) {
367 eventSubscribers_.erase(event);
368 }
369 }
370
371 return ERR_OK;
372 }
373
CheckSubscriberByUserId(const int32_t & subscriberUserId,const bool & isSystemApp,const int32_t & userId)374 bool CommonEventSubscriberManager::CheckSubscriberByUserId(
375 const int32_t &subscriberUserId, const bool &isSystemApp, const int32_t &userId)
376 {
377 if (subscriberUserId == ALL_USER || subscriberUserId == userId) {
378 return true;
379 }
380
381 if (isSystemApp && (userId == UNDEFINED_USER || userId == ALL_USER ||
382 (subscriberUserId >= SUBSCRIBE_USER_SYSTEM_BEGIN && subscriberUserId <= SUBSCRIBE_USER_SYSTEM_END))) {
383 return true;
384 }
385 EVENT_LOGD("Subscriber userId [%{public}d] isn't equal to publish required userId %{public}d",
386 subscriberUserId, userId);
387 return false;
388 }
389
CheckSubscriberBySpecifiedUids(const int32_t & subscriberUid,const std::vector<int32_t> & specifiedSubscriberUids)390 bool CommonEventSubscriberManager::CheckSubscriberBySpecifiedUids(
391 const int32_t &subscriberUid, const std::vector<int32_t> &specifiedSubscriberUids)
392 {
393 for (auto it = specifiedSubscriberUids.begin(); it != specifiedSubscriberUids.end(); ++it) {
394 if (*it == subscriberUid) {
395 return true;
396 }
397 }
398 return false;
399 }
400
CheckSubscriberBySpecifiedType(const int32_t & specifiedSubscriberType,const bool & isSystemApp)401 bool CommonEventSubscriberManager::CheckSubscriberBySpecifiedType(
402 const int32_t &specifiedSubscriberType, const bool &isSystemApp)
403 {
404 return specifiedSubscriberType == static_cast<int32_t>(SubscriberType::ALL_SUBSCRIBER_TYPE) ||
405 (specifiedSubscriberType == static_cast<int32_t>(SubscriberType::SYSTEM_SUBSCRIBER_TYPE) && isSystemApp);
406 }
407
GetSubscriberRecordsByWantLocked(const CommonEventRecord & eventRecord,std::vector<SubscriberRecordPtr> & records)408 void CommonEventSubscriberManager::GetSubscriberRecordsByWantLocked(const CommonEventRecord &eventRecord,
409 std::vector<SubscriberRecordPtr> &records)
410 {
411 std::lock_guard<ffrt::mutex> lock(mutex_);
412 if (eventSubscribers_.size() <= 0) {
413 return;
414 }
415 auto recordsItem = eventSubscribers_.find(eventRecord.commonEventData->GetWant().GetAction());
416 if (recordsItem == eventSubscribers_.end()) {
417 return;
418 }
419 bool isSystemApp = (eventRecord.eventRecordInfo.isSystemApp || eventRecord.eventRecordInfo.isSubsystem) &&
420 !eventRecord.eventRecordInfo.isProxy;
421 auto bundleName = eventRecord.eventRecordInfo.bundleName;
422 auto uid = eventRecord.eventRecordInfo.uid;
423
424 for (auto it = (recordsItem->second).begin(); it != (recordsItem->second).end(); it++) {
425 SubscriberRecordPtr subscriberRecord = *it;
426 auto subscriberUid = subscriberRecord->eventRecordInfo.uid;
427 auto subscriberUserId = subscriberRecord->eventSubscribeInfo->GetUserId();
428 if (subscriberRecord->eventSubscribeInfo == nullptr) {
429 continue;
430 }
431 if (!subscriberRecord->eventSubscribeInfo->GetMatchingSkills().Match(eventRecord.commonEventData->GetWant())) {
432 continue;
433 }
434 if (!CheckSubscriberByUserId(subscriberUserId, isSystemApp, eventRecord.userId)) {
435 continue;
436 }
437 if (!CheckSubscriberPermission(subscriberRecord, eventRecord)) {
438 continue;
439 }
440 if (!CheckPublisherWhetherMatched(subscriberRecord, eventRecord)) {
441 continue;
442 }
443 if (!CheckSubscriberWhetherMatched(subscriberRecord, eventRecord)) {
444 continue;
445 }
446 SubscribeScreenEventToBlackListApp(eventRecord, bundleName, subscriberUid, records, subscriberRecord);
447 }
448 }
449
CheckPublisherWhetherMatched(const SubscriberRecordPtr & subscriberRecord,const CommonEventRecord & eventRecord)450 bool CommonEventSubscriberManager::CheckPublisherWhetherMatched(
451 const SubscriberRecordPtr &subscriberRecord, const CommonEventRecord &eventRecord)
452 {
453 auto bundleName = eventRecord.eventRecordInfo.bundleName;
454 auto uid = eventRecord.eventRecordInfo.uid;
455 auto subscriberRequiredBundle = subscriberRecord->eventSubscribeInfo->GetPublisherBundleName();
456 if (!subscriberRequiredBundle.empty() && subscriberRequiredBundle != bundleName) {
457 EVENT_LOGD("Publisher[%{public}s] isn't equal to subscriber required bundleName[%{public}s] is not matched",
458 bundleName.c_str(), subscriberRequiredBundle.c_str());
459 return false;
460 }
461 auto subscriberRequiredUid = subscriberRecord->eventSubscribeInfo->GetPublisherUid();
462 if (subscriberRequiredUid > 0 && uid > 0 && static_cast<uid_t>(subscriberRequiredUid) != uid) {
463 EVENT_LOGD("Publisher[%{public}d] isn't equal to subscriber required uid[%{public}d]",
464 uid, subscriberRequiredUid);
465 return false;
466 }
467
468 if (!CheckSubscriberRequiredPermission(subscriberRecord, eventRecord)) {
469 return false;
470 }
471 return true;
472 }
473
CheckSubscriberWhetherMatched(const SubscriberRecordPtr & subscriberRecord,const CommonEventRecord & eventRecord)474 bool CommonEventSubscriberManager::CheckSubscriberWhetherMatched(
475 const SubscriberRecordPtr &subscriberRecord, const CommonEventRecord &eventRecord)
476 {
477 auto specifiedSubscriberUids = eventRecord.publishInfo->GetSubscriberUid();
478 auto specifiedSubscriberType = eventRecord.publishInfo->GetSubscriberType();
479 uint16_t filterSettings = eventRecord.publishInfo->GetFilterSettings();
480 if (filterSettings == 0) {
481 return true;
482 }
483 uint16_t checkResult = 0;
484 if (!eventRecord.publishInfo->GetBundleName().empty() &&
485 eventRecord.publishInfo->GetBundleName() == subscriberRecord->eventRecordInfo.bundleName) {
486 checkResult |= SUBSCRIBER_FILTER_BUNDLE_INDEX;
487 }
488 auto isSubscriberSystemApp = subscriberRecord->eventRecordInfo.isSystemApp ||
489 subscriberRecord->eventRecordInfo.isSubsystem;
490 if (specifiedSubscriberType != UNINITIALIZATED_SUBSCRIBER_TYPE &&
491 CheckSubscriberBySpecifiedType(specifiedSubscriberType, isSubscriberSystemApp)) {
492 checkResult |= SUBSCRIBER_FILTER_SUBSCRIBER_TYPE_INDEX;
493 }
494
495 auto subscriberUid = subscriberRecord->eventRecordInfo.uid;
496 if (!specifiedSubscriberUids.empty() &&
497 CheckSubscriberBySpecifiedUids(static_cast<int32_t>(subscriberUid), specifiedSubscriberUids)) {
498 checkResult |= SUBSCRIBER_FILTER_SUBSCRIBER_UID_INDEX;
499 }
500 std::vector<std::string> publisherRequiredPermissions = eventRecord.publishInfo->GetSubscriberPermissions();
501 if (!publisherRequiredPermissions.empty() &&
502 CheckPublisherRequiredPermissions(subscriberRecord, eventRecord)) {
503 checkResult |= SUBSCRIBER_FILTER_PERMISSION_INDEX;
504 }
505 bool result = false;
506 if (eventRecord.publishInfo->GetValidationRule() == ValidationRule::AND) {
507 result = (checkResult == filterSettings);
508 } else {
509 result = ((checkResult & filterSettings) != 0);
510 }
511 if (!result) {
512 EVENT_LOGD("Not match,%{public}d_%{public}u_%{public}u",
513 static_cast<int32_t>(eventRecord.publishInfo->GetValidationRule()),
514 static_cast<uint32_t>(checkResult), static_cast<uint32_t>(filterSettings));
515 }
516 return result;
517 }
518
CheckSubscriberPermission(const SubscriberRecordPtr & subscriberRecord,const CommonEventRecord & eventRecord)519 bool CommonEventSubscriberManager::CheckSubscriberPermission(
520 const SubscriberRecordPtr &subscriberRecord, const CommonEventRecord &eventRecord)
521 {
522 EVENT_LOGD("enter");
523 bool ret = false;
524 std::string lackPermission {};
525 std::string event = eventRecord.commonEventData->GetWant().GetAction();
526 bool isSystemAPIEvent = DelayedSingleton<CommonEventPermissionManager>::GetInstance()->IsSystemAPIEvent(event);
527 if (isSystemAPIEvent && !(subscriberRecord->eventRecordInfo.isSubsystem
528 || subscriberRecord->eventRecordInfo.isSystemApp)) {
529 EVENT_LOGW("Invalid permission for system api event.");
530 return false;
531 }
532 if (subscriberRecord->eventRecordInfo.uid == eventRecord.eventRecordInfo.uid) {
533 return true;
534 }
535 Permission permission = DelayedSingleton<CommonEventPermissionManager>::GetInstance()->GetEventPermission(event);
536 if (permission.names.empty()) {
537 return true;
538 }
539
540 if (permission.names.size() == 1) {
541 ret = AccessTokenHelper::VerifyAccessToken(subscriberRecord->eventRecordInfo.callerToken, permission.names[0]);
542 lackPermission = permission.names[0];
543 } else if (permission.state == PermissionState::AND) {
544 for (const auto& vec : permission.names) {
545 ret = AccessTokenHelper::VerifyAccessToken(subscriberRecord->eventRecordInfo.callerToken, vec);
546 if (!ret) {
547 lackPermission = vec;
548 break;
549 }
550 }
551 } else if (permission.state == PermissionState::OR) {
552 for (const auto& vec : permission.names) {
553 ret = AccessTokenHelper::VerifyAccessToken(subscriberRecord->eventRecordInfo.callerToken, vec);
554 lackPermission += vec + CONNECTOR;
555 if (ret) {
556 break;
557 }
558 }
559 lackPermission = lackPermission.substr(0, lackPermission.length() - CONNECTOR.length());
560 }
561 if (!ret) {
562 EVENT_LOGD("No permission to receive %{public}s, due to %{public}s lacks the %{public}s permission.",
563 event.c_str(), subscriberRecord->eventRecordInfo.subId.c_str(), lackPermission.c_str());
564 }
565 return ret;
566 }
567
CheckSubscriberRequiredPermission(const SubscriberRecordPtr & subscriberRecord,const CommonEventRecord & eventRecord)568 bool CommonEventSubscriberManager::CheckSubscriberRequiredPermission(const SubscriberRecordPtr &subscriberRecord,
569 const CommonEventRecord &eventRecord)
570 {
571 if (subscriberRecord->eventRecordInfo.uid == eventRecord.eventRecordInfo.uid) {
572 return true;
573 }
574 std::string subscriberRequiredPermission = subscriberRecord->eventSubscribeInfo->GetPermission();
575 if (subscriberRequiredPermission.empty()) {
576 return true;
577 }
578
579 bool ret = AccessTokenHelper::VerifyAccessToken(eventRecord.eventRecordInfo.callerToken,
580 subscriberRequiredPermission);
581 if (!ret) {
582 EVENT_LOGD("No permission to send %{public}s "
583 "to %{public}s due to subscriber requires the %{public}s permission.",
584 eventRecord.commonEventData->GetWant().GetAction().c_str(),
585 subscriberRecord->eventRecordInfo.subId.c_str(),
586 subscriberRequiredPermission.c_str());
587 return false;
588 }
589
590 return true;
591 }
592
CheckPublisherRequiredPermissions(const SubscriberRecordPtr & subscriberRecord,const CommonEventRecord & eventRecord)593 bool CommonEventSubscriberManager::CheckPublisherRequiredPermissions(const SubscriberRecordPtr &subscriberRecord,
594 const CommonEventRecord &eventRecord)
595 {
596 if (subscriberRecord->eventRecordInfo.uid == eventRecord.eventRecordInfo.uid) {
597 return true;
598 }
599 std::vector<std::string> publisherRequiredPermissions = eventRecord.publishInfo->GetSubscriberPermissions();
600 for (const auto& publisherRequiredPermission : publisherRequiredPermissions) {
601 bool ret = AccessTokenHelper::VerifyAccessToken(
602 subscriberRecord->eventRecordInfo.callerToken, publisherRequiredPermission);
603 if (!ret) {
604 EVENT_LOGD("No permission to receive %{public}s to %{public}s"
605 "due to publisher requires the %{public}s permission.",
606 eventRecord.commonEventData->GetWant().GetAction().c_str(),
607 subscriberRecord->eventRecordInfo.subId.c_str(),
608 publisherRequiredPermission.c_str());
609 return false;
610 }
611 }
612 return true;
613 }
614
SubscribeScreenEventToBlackListApp(const CommonEventRecord & eventRecord,std::string subscribeBundleName,int subscribeUid,std::vector<SubscriberRecordPtr> & records,SubscriberRecordPtr it)615 void CommonEventSubscriberManager::SubscribeScreenEventToBlackListApp(const CommonEventRecord &eventRecord,
616 std::string subscribeBundleName, int subscribeUid, std::vector<SubscriberRecordPtr> &records,
617 SubscriberRecordPtr it)
618 {
619 #ifdef WATCH_CUSTOMIZED_SCREEN_EVENT_TO_OTHER_APP
620 std::string action = eventRecord.commonEventData->GetWant().GetAction();
621 if (!action.empty() && (action != CommonEventSupport::COMMON_EVENT_SCREEN_ON &&
622 action != CommonEventSupport::COMMON_EVENT_SCREEN_OFF)) {
623 records.emplace_back(it);
624 return;
625 }
626 std::vector<std::string> excludeSubscriberBundleNames =
627 eventRecord.commonEventData->GetWant().GetStringArrayParam("exceptBundleNames");
628 std::vector<int32_t> excludeSubscriberUids = eventRecord.commonEventData->GetWant().GetIntArrayParam("exceptUids");
629 if (handler != nullptr && SubscribeScreenEventToBlackListAppFlag != nullptr) {
630 bool result = SubscribeScreenEventToBlackListAppFlag(
631 excludeSubscriberBundleNames, excludeSubscriberUids, subscribeBundleName, subscribeUid);
632 if (result) {
633 records.emplace_back(it);
634 }
635 }
636 #else
637 records.emplace_back(it);
638 #endif
639 }
640
GetSubscriberRecordsByEvent(const std::string & event,const int32_t & userId,std::vector<SubscriberRecordPtr> & records)641 void CommonEventSubscriberManager::GetSubscriberRecordsByEvent(
642 const std::string &event, const int32_t &userId, std::vector<SubscriberRecordPtr> &records)
643 {
644 if (event.empty() && userId == ALL_USER) {
645 records = subscribers_;
646 } else if (event.empty()) {
647 for (auto recordPtr : subscribers_) {
648 if (recordPtr->eventSubscribeInfo->GetUserId() == userId) {
649 records.emplace_back(recordPtr);
650 }
651 }
652 } else if (userId == ALL_USER) {
653 auto infoItem = eventSubscribers_.find(event);
654 if (infoItem != eventSubscribers_.end()) {
655 for (auto recordPtr : infoItem->second) {
656 records.emplace_back(recordPtr);
657 }
658 }
659 } else {
660 auto infoItem = eventSubscribers_.find(event);
661 if (infoItem != eventSubscribers_.end()) {
662 for (auto recordPtr : infoItem->second) {
663 if (CheckSubscriberByUserId(recordPtr->eventSubscribeInfo->GetUserId(), true, userId)) {
664 records.emplace_back(recordPtr);
665 }
666 }
667 }
668 }
669 }
670
UpdateFreezeInfo(const uid_t & uid,const bool & freezeState,const int64_t & freezeTime)671 void CommonEventSubscriberManager::UpdateFreezeInfo(
672 const uid_t &uid, const bool &freezeState, const int64_t &freezeTime)
673 {
674 EVENT_LOGD("enter");
675
676 std::lock_guard<ffrt::mutex> lock(mutex_);
677 for (auto recordPtr : subscribers_) {
678 if (recordPtr->eventRecordInfo.uid == uid) {
679 if (freezeState) {
680 recordPtr->freezeTime = freezeTime;
681 } else {
682 recordPtr->freezeTime = 0;
683 }
684 recordPtr->isFreeze = freezeState;
685 EVENT_LOGD("recordPtr->uid: %{public}d, recordPtr->isFreeze: %{public}d",
686 recordPtr->eventRecordInfo.uid, recordPtr->isFreeze);
687 }
688 }
689 }
690
UpdateFreezeInfo(std::set<int> pidList,const bool & freezeState,const int64_t & freezeTime)691 void CommonEventSubscriberManager::UpdateFreezeInfo(
692 std::set<int> pidList, const bool &freezeState, const int64_t &freezeTime)
693 {
694 EVENT_LOGD("enter");
695
696 std::lock_guard<ffrt::mutex> lock(mutex_);
697 for (auto recordPtr : subscribers_) {
698 for (auto it = pidList.begin(); it != pidList.end(); it++) {
699 if (recordPtr->eventRecordInfo.pid == *it) {
700 if (freezeState) {
701 recordPtr->freezeTime = freezeTime;
702 } else {
703 recordPtr->freezeTime = 0;
704 }
705 recordPtr->isFreeze = freezeState;
706 EVENT_LOGD("recordPtr->pid: %{public}d, recordPtr->isFreeze: %{public}d",
707 recordPtr->eventRecordInfo.pid, recordPtr->isFreeze);
708 }
709 }
710 }
711 }
712
UpdateAllFreezeInfos(const bool & freezeState,const int64_t & freezeTime)713 void CommonEventSubscriberManager::UpdateAllFreezeInfos(const bool &freezeState, const int64_t &freezeTime)
714 {
715 EVENT_LOGD("enter");
716
717 std::lock_guard<ffrt::mutex> lock(mutex_);
718 for (auto recordPtr : subscribers_) {
719 if (freezeState) {
720 recordPtr->freezeTime = freezeTime;
721 } else {
722 recordPtr->freezeTime = 0;
723 }
724 recordPtr->isFreeze = freezeState;
725 }
726 EVENT_LOGD("all subscribers update freeze state to %{public}d", freezeState);
727 }
728
InsertFrozenEvents(const SubscriberRecordPtr & subscriberRecord,const CommonEventRecord & eventRecord)729 void CommonEventSubscriberManager::InsertFrozenEvents(
730 const SubscriberRecordPtr &subscriberRecord, const CommonEventRecord &eventRecord)
731 {
732 EVENT_LOGD("enter");
733
734 if (subscriberRecord == nullptr) {
735 EVENT_LOGE("subscriberRecord is null");
736 return;
737 }
738
739 auto record = std::make_shared<CommonEventRecord>(eventRecord);
740 std::lock_guard<ffrt::mutex> lock(mutex_);
741 auto frozenRecordsItem = frozenEvents_.find(subscriberRecord->eventRecordInfo.uid);
742 if (frozenRecordsItem != frozenEvents_.end()) {
743 auto eventRecordsItem = frozenRecordsItem->second.find(*subscriberRecord);
744 if (eventRecordsItem != frozenRecordsItem->second.end()) {
745 eventRecordsItem->second.emplace_back(record);
746 time_t backRecordTime = mktime(&eventRecordsItem->second.back()->recordTime);
747 time_t frontRecordTime = mktime(&eventRecordsItem->second.front()->recordTime);
748 time_t timeDiff = backRecordTime - frontRecordTime;
749 if (timeDiff > FREEZE_EVENT_TIMEOUT) {
750 eventRecordsItem->second.erase(eventRecordsItem->second.begin());
751 }
752 } else {
753 std::vector<EventRecordPtr> EventRecords;
754 EventRecords.emplace_back(record);
755 frozenRecordsItem->second[*subscriberRecord] = EventRecords;
756 }
757 } else {
758 std::map<EventSubscriberRecord, std::vector<EventRecordPtr>> frozenRecords;
759 std::vector<EventRecordPtr> EventRecords;
760 EventRecords.emplace_back(record);
761 frozenRecords[*subscriberRecord] = EventRecords;
762 frozenEvents_[subscriberRecord->eventRecordInfo.uid] = frozenRecords;
763 }
764 }
765
GetFrozenEvents(const uid_t & uid)766 std::map<EventSubscriberRecord, std::vector<EventRecordPtr>> CommonEventSubscriberManager::GetFrozenEvents(
767 const uid_t &uid)
768 {
769 EVENT_LOGD("enter");
770
771 std::map<EventSubscriberRecord, std::vector<EventRecordPtr>> frozenEvents;
772 std::lock_guard<ffrt::mutex> lock(mutex_);
773 auto infoItem = frozenEvents_.find(uid);
774 if (infoItem != frozenEvents_.end()) {
775 frozenEvents = infoItem->second;
776 }
777
778 RemoveFrozenEvents(uid);
779
780 return frozenEvents;
781 }
782
GetAllFrozenEvents()783 std::map<uid_t, FrozenRecords> CommonEventSubscriberManager::GetAllFrozenEvents()
784 {
785 EVENT_LOGD("enter");
786 std::lock_guard<ffrt::mutex> lock(mutex_);
787 return std::move(frozenEvents_);
788 }
789
RemoveFrozenEvents(const uid_t & uid)790 void CommonEventSubscriberManager::RemoveFrozenEvents(const uid_t &uid)
791 {
792 EVENT_LOGD("enter");
793 auto infoItem = frozenEvents_.find(uid);
794 if (infoItem != frozenEvents_.end()) {
795 frozenEvents_.erase(uid);
796 }
797 }
798
RemoveFrozenEventsBySubscriber(const SubscriberRecordPtr & subscriberRecord)799 void CommonEventSubscriberManager::RemoveFrozenEventsBySubscriber(const SubscriberRecordPtr &subscriberRecord)
800 {
801 EVENT_LOGD("enter");
802
803 auto frozenRecordsItem = frozenEvents_.find(subscriberRecord->eventRecordInfo.uid);
804 if (frozenRecordsItem != frozenEvents_.end()) {
805 auto eventRecordsItems = frozenRecordsItem->second.find(*subscriberRecord);
806 if (eventRecordsItems != frozenRecordsItem->second.end()) {
807 frozenRecordsItem->second.erase(*subscriberRecord);
808 }
809 }
810 }
811
InsertFrozenEventsMap(const SubscriberRecordPtr & subscriberRecord,const CommonEventRecord & eventRecord)812 void CommonEventSubscriberManager::InsertFrozenEventsMap(
813 const SubscriberRecordPtr &subscriberRecord, const CommonEventRecord &eventRecord)
814 {
815 EVENT_LOGD("enter");
816
817 if (subscriberRecord == nullptr) {
818 EVENT_LOGE("subscriberRecord is null");
819 return;
820 }
821
822 auto record = std::make_shared<CommonEventRecord>(eventRecord);
823 std::lock_guard<ffrt::mutex> lock(mutex_);
824 auto frozenRecordsItem = frozenEventsMap_.find(subscriberRecord->eventRecordInfo.pid);
825 if (frozenRecordsItem != frozenEventsMap_.end()) {
826 auto eventRecordsItem = frozenRecordsItem->second.find(*subscriberRecord);
827 if (eventRecordsItem != frozenRecordsItem->second.end()) {
828 eventRecordsItem->second.emplace_back(record);
829 time_t backRecordTime = mktime(&eventRecordsItem->second.back()->recordTime);
830 time_t frontRecordTime = mktime(&eventRecordsItem->second.front()->recordTime);
831 time_t timeDiff = backRecordTime - frontRecordTime;
832 if (timeDiff > FREEZE_EVENT_TIMEOUT) {
833 eventRecordsItem->second.erase(eventRecordsItem->second.begin());
834 }
835 } else {
836 std::vector<EventRecordPtr> EventRecords;
837 EventRecords.emplace_back(record);
838 frozenRecordsItem->second[*subscriberRecord] = EventRecords;
839 }
840 } else {
841 std::map<EventSubscriberRecord, std::vector<EventRecordPtr>> frozenRecords;
842 std::vector<EventRecordPtr> EventRecords;
843 EventRecords.emplace_back(record);
844 frozenRecords[*subscriberRecord] = EventRecords;
845 frozenEventsMap_[subscriberRecord->eventRecordInfo.pid] = frozenRecords;
846 }
847 }
848
GetFrozenEventsMapByPid(const pid_t & pid)849 std::map<EventSubscriberRecord, std::vector<EventRecordPtr>> CommonEventSubscriberManager::GetFrozenEventsMapByPid(
850 const pid_t &pid)
851 {
852 EVENT_LOGD("enter");
853
854 std::map<EventSubscriberRecord, std::vector<EventRecordPtr>> frozenEvents;
855 std::lock_guard<ffrt::mutex> lock(mutex_);
856 auto infoItem = frozenEventsMap_.find(pid);
857 if (infoItem != frozenEventsMap_.end()) {
858 frozenEvents = infoItem->second;
859 }
860
861 RemoveFrozenEventsMapByPid(pid);
862
863 return frozenEvents;
864 }
865
GetAllFrozenEventsMap()866 std::map<pid_t, FrozenRecords> CommonEventSubscriberManager::GetAllFrozenEventsMap()
867 {
868 EVENT_LOGD("enter");
869 std::lock_guard<ffrt::mutex> lock(mutex_);
870 return std::move(frozenEventsMap_);
871 }
872
RemoveFrozenEventsMapByPid(const pid_t & pid)873 void CommonEventSubscriberManager::RemoveFrozenEventsMapByPid(const pid_t &pid)
874 {
875 EVENT_LOGD("enter");
876 auto infoItem = frozenEventsMap_.find(pid);
877 if (infoItem != frozenEventsMap_.end()) {
878 frozenEventsMap_.erase(pid);
879 }
880 }
881
RemoveFrozenEventsMapBySubscriber(const SubscriberRecordPtr & subscriberRecord)882 void CommonEventSubscriberManager::RemoveFrozenEventsMapBySubscriber(const SubscriberRecordPtr &subscriberRecord)
883 {
884 EVENT_LOGD("enter");
885
886 auto frozenRecordsItem = frozenEventsMap_.find(subscriberRecord->eventRecordInfo.pid);
887 if (frozenRecordsItem != frozenEventsMap_.end()) {
888 auto eventRecordsItems = frozenRecordsItem->second.find(*subscriberRecord);
889 if (eventRecordsItems != frozenRecordsItem->second.end()) {
890 frozenRecordsItem->second.erase(*subscriberRecord);
891 }
892 }
893 }
894
SendSubscriberExceedMaximumHiSysEvent(int32_t userId,const std::string & eventName,uint32_t subscriberNum)895 void CommonEventSubscriberManager::SendSubscriberExceedMaximumHiSysEvent(int32_t userId, const std::string &eventName,
896 uint32_t subscriberNum)
897 {
898 EventInfo eventInfo;
899 eventInfo.userId = userId;
900 eventInfo.eventName = eventName;
901 eventInfo.subscriberNum = subscriberNum;
902 EventReport::SendHiSysEvent(SUBSCRIBER_EXCEED_MAXIMUM, eventInfo);
903 }
904
CheckSubscriberCountReachedMaxinum()905 bool CommonEventSubscriberManager::CheckSubscriberCountReachedMaxinum()
906 {
907 uint32_t subscriberCount = subscribers_.size();
908 uint32_t maxSubscriberNum = GetUintParameter("hiviewdfx.ces.subscriber_limit",
909 DEFAULT_MAX_SUBSCRIBER_NUM_ALL_APP);
910 if (subscriberCount == (uint32_t)(maxSubscriberNum * WARNING_REPORT_PERCENTAGE)) {
911 EVENT_LOGW("subscribers reaches the alarm threshold");
912 PrintSubscriberCounts(GetTopSubscriberCounts());
913 return false;
914 }
915 if (subscriberCount == maxSubscriberNum) {
916 EVENT_LOGE("subscribers reaches the maxinum");
917 PrintSubscriberCounts(GetTopSubscriberCounts());
918 return true;
919 }
920 return false;
921 }
922
GetTopSubscriberCounts(size_t topNum)923 std::vector<std::pair<pid_t, uint32_t>> CommonEventSubscriberManager::GetTopSubscriberCounts(size_t topNum)
924 {
925 topNum = subscriberCounts_.size() < topNum ? subscriberCounts_.size() : topNum;
926
927 std::vector<std::pair<pid_t, uint32_t>> vtSubscriberCounts;
928 std::set<pid_t> pidSet;
929 for (size_t i = 0; i < topNum; i++) {
930 std::pair<pid_t, uint32_t> curPair;
931 for (auto it = subscriberCounts_.begin(); it != subscriberCounts_.end(); it++) {
932 pid_t pid = it->first;
933 uint32_t count = it->second;
934 if (pidSet.find(pid) != pidSet.end()) {
935 continue;
936 }
937 if (curPair.second < count) {
938 curPair = std::make_pair(pid, count);
939 }
940 }
941 pidSet.insert(curPair.first);
942 vtSubscriberCounts.push_back(curPair);
943 }
944
945 return vtSubscriberCounts;
946 }
947
PrintSubscriberCounts(std::vector<std::pair<pid_t,uint32_t>> vtSubscriberCounts)948 void CommonEventSubscriberManager::PrintSubscriberCounts(std::vector<std::pair<pid_t, uint32_t>> vtSubscriberCounts)
949 {
950 EVENT_LOGI("Print top App by subscribers in descending order");
951 int index = 1;
952 for (auto vtIt = vtSubscriberCounts.begin(); vtIt != vtSubscriberCounts.end(); vtIt++) {
953 EVENT_LOGI("top%{public}d pid=%{public}d subscribers=%{public}d", index, vtIt->first, vtIt->second);
954 index++;
955 }
956 }
957 } // namespace EventFwk
958 } // namespace OHOS