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