• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 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 "screenlock_system_ability.h"
16 
17 #include <cerrno>
18 #include <ctime>
19 #include <fcntl.h>
20 #include <functional>
21 #include <iostream>
22 #include <string>
23 #include <sys/time.h>
24 #include <unistd.h>
25 #include <memory>
26 
27 #include "ability_manager_client.h"
28 #include "common_event_support.h"
29 #include "accesstoken_kit.h"
30 #include "command.h"
31 #include "common_event_manager.h"
32 #include "display_manager.h"
33 #include "dump_helper.h"
34 #include "hitrace_meter.h"
35 #include "ipc_skeleton.h"
36 #include "iservice_registry.h"
37 #include "os_account_manager.h"
38 #include "parameter.h"
39 #include "sclock_log.h"
40 #include "screenlock_appinfo.h"
41 #include "screenlock_common.h"
42 #include "screenlock_get_info_callback.h"
43 #include "system_ability.h"
44 #include "system_ability_definition.h"
45 #include "tokenid_kit.h"
46 #include "user_idm_client.h"
47 #include "want.h"
48 #include "xcollie/watchdog.h"
49 #include "window_manager.h"
50 
51 namespace OHOS {
52 namespace ScreenLock {
53 using namespace std;
54 using namespace OHOS::HiviewDFX;
55 using namespace OHOS::Rosen;
56 using namespace OHOS::UserIam::UserAuth;
57 using namespace OHOS::Security::AccessToken;
58 REGISTER_SYSTEM_ABILITY_BY_ID(ScreenLockSystemAbility, SCREENLOCK_SERVICE_ID, true);
59 const std::int64_t TIME_OUT_MILLISECONDS = 10000L;
60 const std::int64_t INIT_INTERVAL = 5000000L;
61 const std::int64_t DELAY_TIME = 1000000L;
62 std::mutex ScreenLockSystemAbility::instanceLock_;
63 sptr<ScreenLockSystemAbility> ScreenLockSystemAbility::instance_;
64 constexpr int32_t MAX_RETRY_TIMES = 20;
65 std::shared_ptr<ffrt::queue> ScreenLockSystemAbility::queue_;
ScreenLockSystemAbility(int32_t systemAbilityId,bool runOnCreate)66 ScreenLockSystemAbility::ScreenLockSystemAbility(int32_t systemAbilityId, bool runOnCreate)
67     : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START)
68 {
69 }
70 
~ScreenLockSystemAbility()71 ScreenLockSystemAbility::~ScreenLockSystemAbility()
72 {
73 }
74 
GetInstance()75 sptr<ScreenLockSystemAbility> ScreenLockSystemAbility::GetInstance()
76 {
77     if (instance_ == nullptr) {
78         std::lock_guard<std::mutex> autoLock(instanceLock_);
79         if (instance_ == nullptr) {
80             SCLOCK_HILOGI("ScreenLockSystemAbility create instance.");
81             instance_ = new ScreenLockSystemAbility(SCREENLOCK_SERVICE_ID, true);
82         }
83     }
84     return instance_;
85 }
86 
Init()87 int32_t ScreenLockSystemAbility::Init()
88 {
89     bool ret = Publish(ScreenLockSystemAbility::GetInstance());
90     if (!ret) {
91         SCLOCK_HILOGE("Publish ScreenLockSystemAbility failed.");
92         return E_SCREENLOCK_PUBLISH_FAIL;
93     }
94     stateValue_.Reset();
95     SCLOCK_HILOGI("Init ScreenLockSystemAbility success.");
96     return ERR_OK;
97 }
98 
OnStart()99 void ScreenLockSystemAbility::OnStart()
100 {
101     SCLOCK_HILOGI("ScreenLockSystemAbility::Enter OnStart.");
102     if (instance_ == nullptr) {
103         instance_ = this;
104     }
105     if (state_ == ServiceRunningState::STATE_RUNNING) {
106         SCLOCK_HILOGW("ScreenLockSystemAbility is already running.");
107         return;
108     }
109     InitServiceHandler();
110     if (Init() != ERR_OK) {
111         auto callback = [=]() { Init(); };
112         queue_->submit(callback, ffrt::task_attr().delay(INIT_INTERVAL));
113         SCLOCK_HILOGW("ScreenLockSystemAbility Init failed. Try again 5s later");
114     }
115     AddSystemAbilityListener(DISPLAY_MANAGER_SERVICE_SA_ID);
116     RegisterDumpCommand();
117     return;
118 }
119 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)120 void ScreenLockSystemAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
121 {
122     SCLOCK_HILOGI("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
123     if (systemAbilityId == DISPLAY_MANAGER_SERVICE_SA_ID) {
124         int times = 0;
125         if (displayPowerEventListener_ == nullptr) {
126             displayPowerEventListener_ = new ScreenLockSystemAbility::ScreenLockDisplayPowerEventListener();
127         }
128         RegisterDisplayPowerEventListener(times);
129     }
130 }
131 
RegisterDisplayPowerEventListener(int32_t times)132 void ScreenLockSystemAbility::RegisterDisplayPowerEventListener(int32_t times)
133 {
134     times++;
135     systemReady_ = (DisplayManager::GetInstance().RegisterDisplayPowerEventListener(displayPowerEventListener_)
136                     == DMError::DM_OK);
137     if (systemReady_ == false && times <= MAX_RETRY_TIMES) {
138         SCLOCK_HILOGW("RegisterDisplayPowerEventListener failed");
139         auto callback = [this, times]() { RegisterDisplayPowerEventListener(times); };
140         queue_->submit(callback, ffrt::task_attr().delay(DELAY_TIME));
141     } else if (systemReady_) {
142         state_ = ServiceRunningState::STATE_RUNNING;
143         SCLOCK_HILOGI("systemReady_ is true");
144     }
145     SCLOCK_HILOGI("RegisterDisplayPowerEventListener, times:%{public}d", times);
146 }
147 
InitServiceHandler()148 void ScreenLockSystemAbility::InitServiceHandler()
149 {
150     if (queue_ != nullptr) {
151         SCLOCK_HILOGI("InitServiceHandler already init.");
152         return;
153     }
154     queue_ = std::make_shared<ffrt::queue>("ScreenLockSystemAbility");
155     SCLOCK_HILOGI("InitServiceHandler succeeded.");
156 }
157 
OnStop()158 void ScreenLockSystemAbility::OnStop()
159 {
160     SCLOCK_HILOGI("OnStop started.");
161     if (state_ != ServiceRunningState::STATE_RUNNING) {
162         return;
163     }
164     queue_ = nullptr;
165     instance_ = nullptr;
166     state_ = ServiceRunningState::STATE_NOT_START;
167     DisplayManager::GetInstance().UnregisterDisplayPowerEventListener(displayPowerEventListener_);
168     SCLOCK_HILOGI("OnStop end.");
169 }
170 
OnDisplayPowerEvent(DisplayPowerEvent event,EventStatus status)171 void ScreenLockSystemAbility::ScreenLockDisplayPowerEventListener::OnDisplayPowerEvent(DisplayPowerEvent event,
172     EventStatus status)
173 {
174     SCLOCK_HILOGI("OnDisplayPowerEvent event=%{public}d,status= %{public}d", static_cast<int>(event),
175         static_cast<int>(status));
176     switch (event) {
177         case DisplayPowerEvent::WAKE_UP:
178             instance_->OnWakeUp(status);
179             break;
180         case DisplayPowerEvent::SLEEP:
181             instance_->OnSleep(status);
182             break;
183         case DisplayPowerEvent::DISPLAY_ON:
184             instance_->OnScreenOn(status);
185             break;
186         case DisplayPowerEvent::DISPLAY_OFF:
187             instance_->OnScreenOff(status);
188             break;
189         case DisplayPowerEvent::DESKTOP_READY:
190             instance_->OnExitAnimation();
191             break;
192         default:
193             break;
194     }
195 }
196 
OnScreenOff(EventStatus status)197 void ScreenLockSystemAbility::OnScreenOff(EventStatus status)
198 {
199     SystemEvent systemEvent(BEGIN_SCREEN_OFF);
200     if (status == EventStatus::BEGIN) {
201         stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_BEGIN_OFF));
202     } else if (status == EventStatus::END) {
203         stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_END_OFF));
204         systemEvent.eventType_ = END_SCREEN_OFF;
205     }
206     SystemEventCallBack(systemEvent);
207 }
208 
OnScreenOn(EventStatus status)209 void ScreenLockSystemAbility::OnScreenOn(EventStatus status)
210 {
211     SystemEvent systemEvent(BEGIN_SCREEN_ON);
212     if (status == EventStatus::BEGIN) {
213         stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_BEGIN_ON));
214     } else if (status == EventStatus::END) {
215         stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_END_ON));
216         systemEvent.eventType_ = END_SCREEN_ON;
217     }
218     SystemEventCallBack(systemEvent);
219 }
220 
OnSystemReady()221 void ScreenLockSystemAbility::OnSystemReady()
222 {
223     SCLOCK_HILOGI("ScreenLockSystemAbility OnSystemReady started.");
224     bool isExitFlag = false;
225     int tryTime = 50;
226     int minTryTime = 0;
227     while (!isExitFlag && (tryTime > minTryTime)) {
228         if (systemEventListener_ != nullptr && systemReady_) {
229             SCLOCK_HILOGI("ScreenLockSystemAbility OnSystemReady started1.");
230             std::lock_guard<std::mutex> lck(listenerMutex_);
231             SystemEvent systemEvent(SYSTEM_READY);
232             systemEventListener_->OnCallBack(systemEvent);
233             isExitFlag = true;
234         } else {
235             SCLOCK_HILOGE("ScreenLockSystemAbility OnSystemReady type not found., tryTime = %{public}d", tryTime);
236             sleep(1);
237         }
238         --tryTime;
239     }
240 }
241 
OnWakeUp(EventStatus status)242 void ScreenLockSystemAbility::OnWakeUp(EventStatus status)
243 {
244     SystemEvent systemEvent(BEGIN_WAKEUP);
245     if (status == EventStatus::BEGIN) {
246         stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_BEGIN_WAKEUP));
247     } else if (status == EventStatus::END) {
248         stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_END_WAKEUP));
249         systemEvent.eventType_ = END_WAKEUP;
250     }
251     SystemEventCallBack(systemEvent);
252 }
253 
OnSleep(EventStatus status)254 void ScreenLockSystemAbility::OnSleep(EventStatus status)
255 {
256     SystemEvent systemEvent(BEGIN_SLEEP);
257     if (status == EventStatus::BEGIN) {
258         stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_BEGIN_SLEEP));
259     } else if (status == EventStatus::END) {
260         stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_END_SLEEP));
261         systemEvent.eventType_ = END_SLEEP;
262     }
263     SystemEventCallBack(systemEvent);
264 }
265 
OnExitAnimation()266 void ScreenLockSystemAbility::OnExitAnimation()
267 {
268     SystemEvent systemEvent(EXIT_ANIMATION);
269     SystemEventCallBack(systemEvent);
270 }
271 
UnlockScreen(const sptr<ScreenLockCallbackInterface> & listener)272 int32_t ScreenLockSystemAbility::UnlockScreen(const sptr<ScreenLockCallbackInterface> &listener)
273 {
274     StartAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen begin", HITRACE_UNLOCKSCREEN);
275     return UnlockInner(listener);
276 }
277 
Unlock(const sptr<ScreenLockCallbackInterface> & listener)278 int32_t ScreenLockSystemAbility::Unlock(const sptr<ScreenLockCallbackInterface> &listener)
279 {
280     StartAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen begin", HITRACE_UNLOCKSCREEN);
281     if (!IsSystemApp()) {
282         FinishAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen end, Calling app is not system app", HITRACE_UNLOCKSCREEN);
283         SCLOCK_HILOGE("Calling app is not system app");
284         return E_SCREENLOCK_NOT_SYSTEM_APP;
285     }
286     return UnlockInner(listener);
287 }
288 
UnlockInner(const sptr<ScreenLockCallbackInterface> & listener)289 int32_t ScreenLockSystemAbility::UnlockInner(const sptr<ScreenLockCallbackInterface> &listener)
290 {
291     if (state_ != ServiceRunningState::STATE_RUNNING) {
292         SCLOCK_HILOGW("UnlockScreen restart.");
293         OnStart();
294     }
295     // check whether the page of app request unlock is the focus page
296     if (!IsAppInForeground(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingTokenID())) {
297         FinishAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen end, Unfocused", HITRACE_UNLOCKSCREEN);
298         SCLOCK_HILOGE("UnlockScreen  Unfocused.");
299         return E_SCREENLOCK_NOT_FOCUS_APP;
300     }
301     unlockListenerMutex_.lock();
302     unlockVecListeners_.push_back(listener);
303     unlockListenerMutex_.unlock();
304     SystemEvent systemEvent(UNLOCKSCREEN);
305     SystemEventCallBack(systemEvent, HITRACE_UNLOCKSCREEN);
306     FinishAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen end", HITRACE_UNLOCKSCREEN);
307     return E_SCREENLOCK_OK;
308 }
309 
Lock(const sptr<ScreenLockCallbackInterface> & listener)310 int32_t ScreenLockSystemAbility::Lock(const sptr<ScreenLockCallbackInterface> &listener)
311 {
312     if (!IsSystemApp()) {
313         SCLOCK_HILOGE("Calling app is not system app");
314         return E_SCREENLOCK_NOT_SYSTEM_APP;
315     }
316     if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
317         return E_SCREENLOCK_NO_PERMISSION;
318     }
319     if (stateValue_.GetScreenlockedState()) {
320         SCLOCK_HILOGI("Currently in a locked screen state");
321     }
322     lockListenerMutex_.lock();
323     lockVecListeners_.push_back(listener);
324     lockListenerMutex_.unlock();
325 
326     SystemEvent systemEvent(LOCKSCREEN);
327     SystemEventCallBack(systemEvent, HITRACE_LOCKSCREEN);
328     return E_SCREENLOCK_OK;
329 }
330 
Lock(int32_t userId)331 int32_t ScreenLockSystemAbility::Lock(int32_t userId)
332 {
333     if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
334         return E_SCREENLOCK_NO_PERMISSION;
335     }
336     if (stateValue_.GetScreenlockedState()) {
337         SCLOCK_HILOGI("Currently in a locked screen state");
338     }
339     SystemEvent systemEvent(LOCKSCREEN);
340     SystemEventCallBack(systemEvent, HITRACE_LOCKSCREEN);
341     return E_SCREENLOCK_OK;
342 }
343 
IsLocked(bool & isLocked)344 int32_t ScreenLockSystemAbility::IsLocked(bool &isLocked)
345 {
346     AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
347     auto tokenType = AccessTokenKit::GetTokenTypeFlag(callerToken);
348     if (tokenType == TOKEN_HAP && !IsSystemApp()) {
349         SCLOCK_HILOGE("Calling app is not system app");
350         return E_SCREENLOCK_NOT_SYSTEM_APP;
351     }
352     isLocked = IsScreenLocked();
353     return E_SCREENLOCK_OK;
354 }
355 
IsScreenLocked()356 bool ScreenLockSystemAbility::IsScreenLocked()
357 {
358     if (state_ != ServiceRunningState::STATE_RUNNING) {
359         SCLOCK_HILOGW("IsScreenLocked restart.");
360         OnStart();
361     }
362     return stateValue_.GetScreenlockedState();
363 }
364 
GetSecure()365 bool ScreenLockSystemAbility::GetSecure()
366 {
367     if (state_ != ServiceRunningState::STATE_RUNNING) {
368         SCLOCK_HILOGW("ScreenLockSystemAbility GetSecure restart.");
369         OnStart();
370     }
371     SCLOCK_HILOGI("ScreenLockSystemAbility GetSecure started.");
372     int callingUid = IPCSkeleton::GetCallingUid();
373     SCLOCK_HILOGD("ScreenLockSystemAbility::GetSecure callingUid=%{public}d", callingUid);
374     int userId = 0;
375     AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId);
376     SCLOCK_HILOGD("userId=%{public}d", userId);
377     auto getInfoCallback = std::make_shared<ScreenLockGetInfoCallback>();
378     int32_t result = UserIdmClient::GetInstance().GetCredentialInfo(userId, AuthType::PIN, getInfoCallback);
379     SCLOCK_HILOGI("GetCredentialInfo AuthType::PIN result = %{public}d", result);
380     if (result == static_cast<int32_t>(ResultCode::SUCCESS) && getInfoCallback->IsSecure()) {
381         return true;
382     }
383     result = UserIdmClient::GetInstance().GetCredentialInfo(userId, AuthType::FACE, getInfoCallback);
384     SCLOCK_HILOGI("GetCredentialInfo AuthType::FACE result = %{public}d", result);
385     if (result == static_cast<int32_t>(ResultCode::SUCCESS) && getInfoCallback->IsSecure()) {
386         return true;
387     }
388     return false;
389 }
390 
OnSystemEvent(const sptr<ScreenLockSystemAbilityInterface> & listener)391 int32_t ScreenLockSystemAbility::OnSystemEvent(const sptr<ScreenLockSystemAbilityInterface> &listener)
392 {
393     if (!IsSystemApp()) {
394         SCLOCK_HILOGE("Calling app is not system app");
395         return E_SCREENLOCK_NOT_SYSTEM_APP;
396     }
397     if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
398         return E_SCREENLOCK_NO_PERMISSION;
399     }
400     std::lock_guard<std::mutex> lck(listenerMutex_);
401     systemEventListener_ = listener;
402     stateValue_.Reset();
403     auto callback = [this]() { OnSystemReady(); };
404     queue_->submit(callback);
405     SCLOCK_HILOGI("ScreenLockSystemAbility::OnSystemEvent end.");
406     return E_SCREENLOCK_OK;
407 }
408 
SendScreenLockEvent(const std::string & event,int param)409 int32_t ScreenLockSystemAbility::SendScreenLockEvent(const std::string &event, int param)
410 {
411     SCLOCK_HILOGI("SendScreenLockEvent event=%{public}s ,param=%{public}d", event.c_str(), param);
412     if (!IsSystemApp()) {
413         SCLOCK_HILOGE("Calling app is not system app");
414         return E_SCREENLOCK_NOT_SYSTEM_APP;
415     }
416     if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
417         return E_SCREENLOCK_NO_PERMISSION;
418     }
419     int stateResult = param;
420     if (event == UNLOCK_SCREEN_RESULT) {
421         UnlockScreenEvent(stateResult);
422     } else if (event == SCREEN_DRAWDONE) {
423         NotifyDisplayEvent(DisplayEvent::KEYGUARD_DRAWN);
424     } else if (event == LOCK_SCREEN_RESULT) {
425         LockScreenEvent(stateResult);
426     }
427     return E_SCREENLOCK_OK;
428 }
429 
SetScreenlocked(bool isScreenlocked)430 void ScreenLockSystemAbility::SetScreenlocked(bool isScreenlocked)
431 {
432     SCLOCK_HILOGI("ScreenLockSystemAbility SetScreenlocked state:%{public}d.", isScreenlocked);
433     stateValue_.SetScreenlocked(isScreenlocked);
434 }
435 
Reset()436 void StateValue::Reset()
437 {
438     isScreenlocked_ = true;
439     screenlockEnabled_ = true;
440     currentUser_ = USER_NULL;
441 }
442 
Dump(int fd,const std::vector<std::u16string> & args)443 int ScreenLockSystemAbility::Dump(int fd, const std::vector<std::u16string> &args)
444 {
445     int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
446     const int maxUid = 10000;
447     if (uid > maxUid) {
448         return 0;
449     }
450 
451     std::vector<std::string> argsStr;
452     for (auto item : args) {
453         argsStr.emplace_back(Str16ToStr8(item));
454     }
455 
456     DumpHelper::GetInstance().Dispatch(fd, argsStr);
457     return ERR_OK;
458 }
459 
RegisterDumpCommand()460 void ScreenLockSystemAbility::RegisterDumpCommand()
461 {
462     auto cmd = std::make_shared<Command>(std::vector<std::string>{ "-all" }, "dump all screenlock information",
463         [this](const std::vector<std::string> &input, std::string &output) -> bool {
464             bool screenLocked = stateValue_.GetScreenlockedState();
465             bool screenState = stateValue_.GetScreenState();
466             int32_t offReason = stateValue_.GetOffReason();
467             int32_t interactiveState = stateValue_.GetInteractiveState();
468             string temp_screenLocked = "";
469             screenLocked ? temp_screenLocked = "true" : temp_screenLocked = "false";
470             string temp_screenState = "";
471             screenState ? temp_screenState = "true" : temp_screenState = "false";
472             output.append("\n Screenlock system state\\tValue\\t\\tDescription\n")
473                 .append(" * screenLocked  \t\t" + temp_screenLocked + "\t\twhether there is lock screen status\n")
474                 .append(" * screenState  \t\t" + temp_screenState + "\t\tscreen on / off status\n")
475                 .append(" * offReason  \t\t\t" + std::to_string(offReason) + "\t\tscreen failure reason\n")
476                 .append(
477                 " * interactiveState \t\t" + std::to_string(interactiveState) + "\t\tscreen interaction status\n");
478             return true;
479         });
480     DumpHelper::GetInstance().RegisterCommand(cmd);
481 }
482 
PublishEvent(const std::string & eventAction)483 void ScreenLockSystemAbility::PublishEvent(const std::string &eventAction)
484 {
485     AAFwk::Want want;
486     want.SetAction(eventAction);
487     EventFwk::CommonEventData commonData(want);
488     bool ret = EventFwk::CommonEventManager::PublishCommonEvent(commonData);
489     SCLOCK_HILOGD("Publish event result is:%{public}d", ret);
490 }
491 
LockScreenEvent(int stateResult)492 void ScreenLockSystemAbility::LockScreenEvent(int stateResult)
493 {
494     SCLOCK_HILOGD("ScreenLockSystemAbility LockScreenEvent stateResult:%{public}d", stateResult);
495     if (stateResult == ScreenChange::SCREEN_SUCC) {
496         SetScreenlocked(true);
497     }
498     std::lock_guard<std::mutex> autoLock(lockListenerMutex_);
499     if (lockVecListeners_.size()) {
500         auto callback = [this, stateResult]() {
501             std::lock_guard<std::mutex> guard(lockListenerMutex_);
502             for (size_t i = 0; i < lockVecListeners_.size(); i++) {
503                 lockVecListeners_[i]->OnCallBack(stateResult);
504             }
505             lockVecListeners_.clear();
506         };
507         ffrt::submit(callback);
508     }
509     if (stateResult == ScreenChange::SCREEN_SUCC) {
510         PublishEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED);
511     }
512 }
513 
UnlockScreenEvent(int stateResult)514 void ScreenLockSystemAbility::UnlockScreenEvent(int stateResult)
515 {
516     SCLOCK_HILOGD("ScreenLockSystemAbility UnlockScreenEvent stateResult:%{public}d", stateResult);
517     if (stateResult == ScreenChange::SCREEN_SUCC) {
518         SetScreenlocked(false);
519         NotifyDisplayEvent(DisplayEvent::UNLOCK);
520     }
521     NotifyUnlockListener(stateResult);
522     if (stateResult == ScreenChange::SCREEN_SUCC) {
523         PublishEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
524     }
525 }
526 
SystemEventCallBack(const SystemEvent & systemEvent,TraceTaskId traceTaskId)527 void ScreenLockSystemAbility::SystemEventCallBack(const SystemEvent &systemEvent, TraceTaskId traceTaskId)
528 {
529     SCLOCK_HILOGI("eventType is %{public}s, params is %{public}s", systemEvent.eventType_.c_str(),
530         systemEvent.params_.c_str());
531     if (systemEventListener_ == nullptr) {
532         SCLOCK_HILOGE("systemEventListener_ is nullptr.");
533         return;
534     }
535     auto callback = [this, systemEvent, traceTaskId]() {
536         if (traceTaskId != HITRACE_BUTT) {
537             StartAsyncTrace(HITRACE_TAG_MISC, "ScreenLockSystemAbility::" + systemEvent.eventType_ + "begin callback",
538                 traceTaskId);
539         }
540         std::lock_guard<std::mutex> lck(listenerMutex_);
541         systemEventListener_->OnCallBack(systemEvent);
542         if (traceTaskId != HITRACE_BUTT) {
543             FinishAsyncTrace(
544                 HITRACE_TAG_MISC, "ScreenLockSystemAbility::" + systemEvent.eventType_ + "end callback", traceTaskId);
545         }
546     };
547     if (queue_ != nullptr) {
548         queue_->submit(callback);
549     }
550 }
551 
NotifyUnlockListener(const int32_t screenLockResult)552 void ScreenLockSystemAbility::NotifyUnlockListener(const int32_t screenLockResult)
553 {
554     std::lock_guard<std::mutex> autoLock(unlockListenerMutex_);
555     if (unlockVecListeners_.size()) {
556         auto callback = [this, screenLockResult]() {
557             std::lock_guard<std::mutex> guard(unlockListenerMutex_);
558             for (size_t i = 0; i < unlockVecListeners_.size(); i++) {
559                 unlockVecListeners_[i]->OnCallBack(screenLockResult);
560             }
561             unlockVecListeners_.clear();
562         };
563         ffrt::submit(callback);
564     }
565 }
566 
NotifyDisplayEvent(DisplayEvent event)567 void ScreenLockSystemAbility::NotifyDisplayEvent(DisplayEvent event)
568 {
569     if (queue_ == nullptr) {
570         SCLOCK_HILOGE("NotifyDisplayEvent queue_ is nullptr.");
571         return;
572     }
573     auto callback = [event]() { DisplayManager::GetInstance().NotifyDisplayEvent(event); };
574     queue_->submit(callback);
575 }
576 
ResetFfrtQueue()577 void ScreenLockSystemAbility::ResetFfrtQueue()
578 {
579     queue_.reset();
580 }
581 
IsAppInForeground(int32_t callingPid,uint32_t callingTokenId)582 bool ScreenLockSystemAbility::IsAppInForeground(int32_t callingPid, uint32_t callingTokenId)
583 {
584 #ifdef CONFIG_FACTORY_MODE
585     return true;
586 #endif
587     FocusChangeInfo focusInfo;
588     WindowManager::GetInstance().GetFocusWindowInfo(focusInfo);
589     if (callingPid == focusInfo.pid_) {
590         return true;
591     }
592     bool isFocused = false;
593     std::string identity = IPCSkeleton::ResetCallingIdentity();
594     auto ret = AAFwk::AbilityManagerClient::GetInstance()->CheckUIExtensionIsFocused(callingTokenId, isFocused);
595     IPCSkeleton::SetCallingIdentity(identity);
596     SCLOCK_HILOGI("tokenId:%{public}d check result:%{public}d, isFocused:%{public}d", callingTokenId, ret, isFocused);
597     return ret == ERR_OK && isFocused;
598 }
599 
IsSystemApp()600 bool ScreenLockSystemAbility::IsSystemApp()
601 {
602     return TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID());
603 }
604 
CheckPermission(const std::string & permissionName)605 bool ScreenLockSystemAbility::CheckPermission(const std::string &permissionName)
606 {
607     AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
608     int result = AccessTokenKit::VerifyAccessToken(callerToken, permissionName);
609     if (result != PERMISSION_GRANTED) {
610         SCLOCK_HILOGE("check permission failed.");
611         return false;
612     }
613     return true;
614 }
615 } // namespace ScreenLock
616 } // namespace OHOS