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 #include <mutex>
27
28 #include "ability_manager_client.h"
29 #include "common_event_support.h"
30 #include "accesstoken_kit.h"
31 #include "common_event_manager.h"
32 #include "display_manager.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_common.h"
40 #include "screenlock_get_info_callback.h"
41 #include "system_ability.h"
42 #include "system_ability_definition.h"
43 #include "tokenid_kit.h"
44 #include "user_idm_client.h"
45 #include "want.h"
46 #include "window_manager.h"
47 #include "commeventsubscriber.h"
48 #include "user_auth_client_callback.h"
49 #include "user_auth_client_impl.h"
50 #ifndef IS_SO_CROP_H
51 #include "command.h"
52 #include "dump_helper.h"
53 #include "strongauthmanager.h"
54 #include "innerlistenermanager.h"
55 #include "common_helper.h"
56 #endif // IS_SO_CROP_H
57
58 using namespace OHOS;
59 using namespace OHOS::ScreenLock;
60
61 namespace OHOS {
62 namespace ScreenLock {
63 using namespace std;
64 using namespace OHOS::HiviewDFX;
65 using namespace OHOS::Rosen;
66 using namespace OHOS::UserIam::UserAuth;
67 using namespace OHOS::Security::AccessToken;
68 using namespace OHOS::AccountSA;
69 REGISTER_SYSTEM_ABILITY_BY_ID(ScreenLockSystemAbility, SCREENLOCK_SERVICE_ID, true);
70 const std::int64_t TIME_OUT_MILLISECONDS = 10000L;
71 const std::int64_t INIT_INTERVAL = 5000000L;
72 const std::int64_t DELAY_TIME = 1000000L;
73 std::mutex ScreenLockSystemAbility::instanceLock_;
74 sptr<ScreenLockSystemAbility> ScreenLockSystemAbility::instance_;
75 constexpr int32_t MAX_RETRY_TIMES = 20;
76 std::shared_ptr<ffrt::queue> ScreenLockSystemAbility::queue_;
ScreenLockSystemAbility(int32_t systemAbilityId,bool runOnCreate)77 ScreenLockSystemAbility::ScreenLockSystemAbility(int32_t systemAbilityId, bool runOnCreate)
78 : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START)
79 {}
80
~ScreenLockSystemAbility()81 ScreenLockSystemAbility::~ScreenLockSystemAbility() {}
82
GetInstance()83 sptr<ScreenLockSystemAbility> ScreenLockSystemAbility::GetInstance()
84 {
85 if (instance_ == nullptr) {
86 std::lock_guard<std::mutex> autoLock(instanceLock_);
87 if (instance_ == nullptr) {
88 SCLOCK_HILOGI("ScreenLockSystemAbility create instance.");
89 instance_ = new ScreenLockSystemAbility(SCREENLOCK_SERVICE_ID, true);
90 }
91 }
92 return instance_;
93 }
94
GetCurrentActiveOsAccountId()95 static int32_t GetCurrentActiveOsAccountId()
96 {
97 std::vector<int> activatedOsAccountIds;
98 OHOS::ErrCode res = OsAccountManager::QueryActiveOsAccountIds(activatedOsAccountIds);
99 if (res != OHOS::ERR_OK || (activatedOsAccountIds.size() <= 0)) {
100 SCLOCK_HILOGE("QueryActiveOsAccountIds fail. [Res]: %{public}d", res);
101 return SCREEN_FAIL;
102 }
103 int osAccountId = activatedOsAccountIds[0];
104 SCLOCK_HILOGI("GetCurrentActiveOsAccountId.[osAccountId]:%{public}d", osAccountId);
105 return osAccountId;
106 }
107
AccountSubscriber(const OsAccountSubscribeInfo & subscribeInfo)108 ScreenLockSystemAbility::AccountSubscriber::AccountSubscriber(const OsAccountSubscribeInfo &subscribeInfo)
109 : OsAccountSubscriber(subscribeInfo)
110 {}
111
OnAccountsChanged(const int & id)112 void ScreenLockSystemAbility::AccountSubscriber::OnAccountsChanged(const int &id)
113 {
114 SCLOCK_HILOGI("OnAccountsChanged.[osAccountId]:%{public}d, [lastId]:%{public}d", id, userId_);
115 #ifndef IS_SO_CROP_H
116 StrongAuthManger::GetInstance()->StartStrongAuthTimer(id);
117 #endif // IS_SO_CROP_H
118 userId_ = id;
119 ScreenLockSystemAbility::GetInstance()->authStateInit(userId_);
120 auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
121 if (preferencesUtil == nullptr) {
122 SCLOCK_HILOGE("preferencesUtil is nullptr!");
123 return;
124 }
125 if (preferencesUtil->ObtainBool(std::to_string(id), false)) {
126 return;
127 }
128 preferencesUtil->SaveBool(std::to_string(id), false);
129 preferencesUtil->Refresh();
130 return;
131 }
132
AccountRemoveSubscriber(const OsAccountSubscribeInfo & subscribeInfo)133 ScreenLockSystemAbility::AccountRemoveSubscriber::AccountRemoveSubscriber(const OsAccountSubscribeInfo &subscribeInfo)
134 : OsAccountSubscriber(subscribeInfo)
135 {}
136
OnAccountsChanged(const int & id)137 void ScreenLockSystemAbility::AccountRemoveSubscriber::OnAccountsChanged(const int &id)
138 {
139 SCLOCK_HILOGI("AccountRemoveSubscriber OnAccountsChanged remove user: %{public}d", id);
140 ScreenLockSystemAbility::GetInstance()->onRemoveUser(id);
141 }
142
onRemoveUser(const int32_t userId)143 void ScreenLockSystemAbility::onRemoveUser(const int32_t userId)
144 {
145 std::unique_lock<std::mutex> authLock(authStateMutex_);
146 auto authIter = authStateInfo.find(userId);
147 if (authIter != authStateInfo.end()) {
148 authStateInfo.erase(authIter);
149 } else {
150 SCLOCK_HILOGI("onRemoveUser authStateInfo user not exit, userId: %{public}d", userId);
151 }
152 authLock.unlock();
153
154 std::unique_lock<std::mutex> screenStateLock(screenLockMutex_);
155 auto lockIter = isScreenlockedMap_.find(userId);
156 if (lockIter != isScreenlockedMap_.end()) {
157 isScreenlockedMap_.erase(lockIter);
158 } else {
159 SCLOCK_HILOGI("onRemoveUser screenStateLock user not exit, userId: %{public}d", userId);
160 }
161 screenStateLock.unlock();
162 }
163
Init()164 int32_t ScreenLockSystemAbility::Init()
165 {
166 bool ret = Publish(ScreenLockSystemAbility::GetInstance());
167 if (!ret) {
168 SCLOCK_HILOGE("Publish ScreenLockSystemAbility failed.");
169 return E_SCREENLOCK_PUBLISH_FAIL;
170 }
171 stateValue_.Reset();
172 SCLOCK_HILOGI("Init ScreenLockSystemAbility success.");
173 return ERR_OK;
174 }
175
OnStart()176 void ScreenLockSystemAbility::OnStart()
177 {
178 SCLOCK_HILOGI("ScreenLockSystemAbility::Enter OnStart.");
179 if (instance_ == nullptr) {
180 instance_ = this;
181 }
182 if (state_ == ServiceRunningState::STATE_RUNNING) {
183 SCLOCK_HILOGW("ScreenLockSystemAbility is already running.");
184 return;
185 }
186 InitServiceHandler();
187 if (Init() != ERR_OK) {
188 auto callback = [=]() { Init(); };
189 queue_->submit(callback, ffrt::task_attr().delay(INIT_INTERVAL));
190 SCLOCK_HILOGW("ScreenLockSystemAbility Init failed. Try again 5s later");
191 }
192 AddSystemAbilityListener(DISPLAY_MANAGER_SERVICE_SA_ID);
193 AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN);
194 AddSystemAbilityListener(SUBSYS_USERIAM_SYS_ABILITY_USERIDM);
195 RegisterDumpCommand();
196 return;
197 }
198
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)199 void ScreenLockSystemAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
200 {
201 SCLOCK_HILOGI("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
202 if (systemAbilityId == DISPLAY_MANAGER_SERVICE_SA_ID) {
203 int times = 0;
204 if (displayPowerEventListener_ == nullptr) {
205 displayPowerEventListener_ = new ScreenLockSystemAbility::ScreenLockDisplayPowerEventListener();
206 }
207 RegisterDisplayPowerEventListener(times);
208 }
209 if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) {
210 InitUserId();
211 }
212 #ifndef IS_SO_CROP_H
213 if (systemAbilityId == SUBSYS_USERIAM_SYS_ABILITY_USERIDM) {
214 StrongAuthManger::GetInstance()->RegistUserAuthSuccessEventListener();
215 }
216 #endif // IS_SO_CROP_H
217 }
218
RegisterDisplayPowerEventListener(int32_t times)219 void ScreenLockSystemAbility::RegisterDisplayPowerEventListener(int32_t times)
220 {
221 times++;
222 systemReady_ =
223 (DisplayManager::GetInstance().RegisterDisplayPowerEventListener(displayPowerEventListener_) == DMError::DM_OK);
224 if (systemReady_ == false && times <= MAX_RETRY_TIMES) {
225 SCLOCK_HILOGW("RegisterDisplayPowerEventListener failed");
226 auto callback = [this, times]() { RegisterDisplayPowerEventListener(times); };
227 queue_->submit(callback, ffrt::task_attr().delay(DELAY_TIME));
228 } else if (systemReady_) {
229 state_ = ServiceRunningState::STATE_RUNNING;
230 SCLOCK_HILOGI("systemReady_ is true");
231 }
232 SCLOCK_HILOGI("RegisterDisplayPowerEventListener, times:%{public}d", times);
233 }
234
InitServiceHandler()235 void ScreenLockSystemAbility::InitServiceHandler()
236 {
237 if (queue_ != nullptr) {
238 SCLOCK_HILOGI("InitServiceHandler already init.");
239 return;
240 }
241 queue_ = std::make_shared<ffrt::queue>("ScreenLockSystemAbility");
242 SCLOCK_HILOGI("InitServiceHandler succeeded.");
243 }
244
InitUserId()245 void ScreenLockSystemAbility::InitUserId()
246 {
247 subscribeAcccount();
248 Singleton<CommeventMgr>::GetInstance().SubscribeEvent();
249
250 int userId = GetCurrentActiveOsAccountId();
251 auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
252 if (preferencesUtil == nullptr) {
253 SCLOCK_HILOGE("preferencesUtil is nullptr!");
254 return;
255 }
256 if (preferencesUtil->ObtainBool(std::to_string(userId), false)) {
257 return;
258 }
259 preferencesUtil->SaveBool(std::to_string(userId), false);
260 preferencesUtil->Refresh();
261 return;
262 }
263
OnStop()264 void ScreenLockSystemAbility::OnStop()
265 {
266 SCLOCK_HILOGI("OnStop started.");
267 if (state_ != ServiceRunningState::STATE_RUNNING) {
268 return;
269 }
270 queue_ = nullptr;
271 instance_ = nullptr;
272 state_ = ServiceRunningState::STATE_NOT_START;
273 DisplayManager::GetInstance().UnregisterDisplayPowerEventListener(displayPowerEventListener_);
274 #ifndef IS_SO_CROP_H
275 StrongAuthManger::GetInstance()->UnRegistUserAuthSuccessEventListener();
276 StrongAuthManger::GetInstance()->DestroyAllStrongAuthTimer();
277 #endif // IS_SO_CROP_H
278 int ret = OsAccountManager::UnsubscribeOsAccount(accountSubscriber_);
279 if (ret != SUCCESS) {
280 SCLOCK_HILOGE("unsubscribe os account failed, code=%{public}d", ret);
281 }
282
283 ret = OsAccountManager::UnsubscribeOsAccount(accountRemoveSubscriber_);
284 if (ret != SUCCESS) {
285 SCLOCK_HILOGE("unsubscribe remove account failed, code=%{public}d", ret);
286 }
287 SCLOCK_HILOGI("OnStop end.");
288 }
289
subscribeAcccount()290 void ScreenLockSystemAbility::subscribeAcccount()
291 {
292 std::unique_lock<std::mutex> lock(accountSubscriberMutex_);
293 OsAccountSubscribeInfo subscribeInfoActivate;
294 subscribeInfoActivate.SetOsAccountSubscribeType(OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVATED);
295 accountSubscriber_ = std::make_shared<AccountSubscriber>(subscribeInfoActivate);
296
297 int32_t ret = OsAccountManager::SubscribeOsAccount(accountSubscriber_);
298 if (ret != ERR_OK) {
299 SCLOCK_HILOGE("SubscribeOsAccount activate failed.[ret]:%{public}d", ret);
300 }
301 lock.unlock();
302
303 std::unique_lock<std::mutex> removeLock(accounRemovetSubscriberMutex_);
304 OsAccountSubscribeInfo subscribeInfoRemove;
305 subscribeInfoRemove.SetOsAccountSubscribeType(OS_ACCOUNT_SUBSCRIBE_TYPE::REMOVED);
306 accountRemoveSubscriber_ = std::make_shared<AccountRemoveSubscriber>(subscribeInfoRemove);
307
308 ret = OsAccountManager::SubscribeOsAccount(accountRemoveSubscriber_);
309 if (ret != ERR_OK) {
310 SCLOCK_HILOGE("SubscribeOsAccount remove failed.[ret]:%{public}d", ret);
311 }
312 removeLock.unlock();
313 }
314
OnDisplayPowerEvent(DisplayPowerEvent event,EventStatus status)315 void ScreenLockSystemAbility::ScreenLockDisplayPowerEventListener::OnDisplayPowerEvent(DisplayPowerEvent event,
316 EventStatus status)
317 {
318 SCLOCK_HILOGI("OnDisplayPowerEvent event=%{public}d,status= %{public}d", static_cast<int>(event),
319 static_cast<int>(status));
320 switch (event) {
321 case DisplayPowerEvent::WAKE_UP:
322 instance_->OnWakeUp(status);
323 break;
324 case DisplayPowerEvent::SLEEP:
325 instance_->OnSleep(status);
326 break;
327 case DisplayPowerEvent::DISPLAY_ON:
328 instance_->OnScreenOn(status);
329 break;
330 case DisplayPowerEvent::DISPLAY_OFF:
331 instance_->OnScreenOff(status);
332 break;
333 case DisplayPowerEvent::DESKTOP_READY:
334 instance_->OnExitAnimation();
335 break;
336 default:
337 break;
338 }
339 }
340
OnScreenOff(EventStatus status)341 void ScreenLockSystemAbility::OnScreenOff(EventStatus status)
342 {
343 SystemEvent systemEvent(BEGIN_SCREEN_OFF);
344 if (status == EventStatus::BEGIN) {
345 stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_BEGIN_OFF));
346 } else if (status == EventStatus::END) {
347 stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_END_OFF));
348 systemEvent.eventType_ = END_SCREEN_OFF;
349 }
350 SystemEventCallBack(systemEvent);
351 }
352
OnScreenOn(EventStatus status)353 void ScreenLockSystemAbility::OnScreenOn(EventStatus status)
354 {
355 SystemEvent systemEvent(BEGIN_SCREEN_ON);
356 if (status == EventStatus::BEGIN) {
357 stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_BEGIN_ON));
358 } else if (status == EventStatus::END) {
359 stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_END_ON));
360 systemEvent.eventType_ = END_SCREEN_ON;
361 }
362 SystemEventCallBack(systemEvent);
363 }
364
OnSystemReady()365 void ScreenLockSystemAbility::OnSystemReady()
366 {
367 SCLOCK_HILOGI("ScreenLockSystemAbility OnSystemReady started.");
368 bool isExitFlag = false;
369 int tryTime = 50;
370 int minTryTime = 0;
371 while (!isExitFlag && (tryTime > minTryTime)) {
372 if (systemEventListener_ != nullptr && systemReady_) {
373 SCLOCK_HILOGI("ScreenLockSystemAbility OnSystemReady started1.");
374 std::lock_guard<std::mutex> lck(listenerMutex_);
375 SystemEvent systemEvent(SYSTEM_READY);
376 systemEventListener_->OnCallBack(systemEvent);
377 isExitFlag = true;
378 } else {
379 SCLOCK_HILOGE("ScreenLockSystemAbility OnSystemReady type not found., tryTime = %{public}d", tryTime);
380 sleep(1);
381 }
382 --tryTime;
383 }
384 }
385
OnWakeUp(EventStatus status)386 void ScreenLockSystemAbility::OnWakeUp(EventStatus status)
387 {
388 SystemEvent systemEvent(BEGIN_WAKEUP);
389 if (status == EventStatus::BEGIN) {
390 stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_BEGIN_WAKEUP));
391 } else if (status == EventStatus::END) {
392 stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_END_WAKEUP));
393 systemEvent.eventType_ = END_WAKEUP;
394 }
395 SystemEventCallBack(systemEvent);
396 }
397
OnSleep(EventStatus status)398 void ScreenLockSystemAbility::OnSleep(EventStatus status)
399 {
400 SystemEvent systemEvent(BEGIN_SLEEP);
401 if (status == EventStatus::BEGIN) {
402 stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_BEGIN_SLEEP));
403 } else if (status == EventStatus::END) {
404 stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_END_SLEEP));
405 systemEvent.eventType_ = END_SLEEP;
406 }
407 SystemEventCallBack(systemEvent);
408 }
409
OnExitAnimation()410 void ScreenLockSystemAbility::OnExitAnimation()
411 {
412 SystemEvent systemEvent(EXIT_ANIMATION);
413 SystemEventCallBack(systemEvent);
414 }
415
StrongAuthChanged(int32_t userId,int32_t reasonFlag)416 void ScreenLockSystemAbility::StrongAuthChanged(int32_t userId, int32_t reasonFlag)
417 {
418 SystemEvent systemEvent(STRONG_AUTH_CHANGED);
419 systemEvent.userId_ = userId;
420 systemEvent.params_ = std::to_string(reasonFlag);
421 SystemEventCallBack(systemEvent);
422 SCLOCK_HILOGI("StrongAuthChanged: userId: %{public}d, reasonFlag:%{public}d", userId, reasonFlag);
423 }
424
UnlockScreen(const sptr<ScreenLockCallbackInterface> & listener)425 int32_t ScreenLockSystemAbility::UnlockScreen(const sptr<ScreenLockCallbackInterface> &listener)
426 {
427 StartAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen begin", HITRACE_UNLOCKSCREEN);
428 return UnlockInner(listener);
429 }
430
Unlock(const sptr<ScreenLockCallbackInterface> & listener)431 int32_t ScreenLockSystemAbility::Unlock(const sptr<ScreenLockCallbackInterface> &listener)
432 {
433 StartAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen begin", HITRACE_UNLOCKSCREEN);
434 if (!IsSystemApp()) {
435 FinishAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen end, Calling app is not system app", HITRACE_UNLOCKSCREEN);
436 SCLOCK_HILOGE("Calling app is not system app");
437 return E_SCREENLOCK_NOT_SYSTEM_APP;
438 }
439 return UnlockInner(listener);
440 }
441
UnlockInner(const sptr<ScreenLockCallbackInterface> & listener)442 int32_t ScreenLockSystemAbility::UnlockInner(const sptr<ScreenLockCallbackInterface> &listener)
443 {
444 if (state_ != ServiceRunningState::STATE_RUNNING) {
445 SCLOCK_HILOGI("UnlockScreen restart.");
446 }
447 AccessTokenID callerTokenId = IPCSkeleton::GetCallingTokenID();
448 // check whether the page of app request unlock is the focus page
449 bool hasPermission = CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK");
450 SCLOCK_HILOGE("hasPermission: {public}%d.", hasPermission);
451 if (AccessTokenKit::GetTokenTypeFlag(callerTokenId) != TOKEN_NATIVE &&
452 !IsAppInForeground(IPCSkeleton::GetCallingPid(), callerTokenId) && !hasPermission) {
453 FinishAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen end, Unfocused", HITRACE_UNLOCKSCREEN);
454 SCLOCK_HILOGE("UnlockScreen Unfocused.");
455 return E_SCREENLOCK_NOT_FOCUS_APP;
456 }
457 unlockListenerMutex_.lock();
458 unlockVecListeners_.push_back(listener);
459 unlockListenerMutex_.unlock();
460 SystemEvent systemEvent(UNLOCKSCREEN);
461 SystemEventCallBack(systemEvent, HITRACE_UNLOCKSCREEN);
462 FinishAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen end", HITRACE_UNLOCKSCREEN);
463 return E_SCREENLOCK_OK;
464 }
465
Lock(const sptr<ScreenLockCallbackInterface> & listener)466 int32_t ScreenLockSystemAbility::Lock(const sptr<ScreenLockCallbackInterface> &listener)
467 {
468 if (!IsSystemApp()) {
469 SCLOCK_HILOGE("Calling app is not system app");
470 return E_SCREENLOCK_NOT_SYSTEM_APP;
471 }
472 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
473 return E_SCREENLOCK_NO_PERMISSION;
474 }
475 if (IsScreenLocked()) {
476 SCLOCK_HILOGI("Currently in a locked screen state");
477 }
478 lockListenerMutex_.lock();
479 lockVecListeners_.push_back(listener);
480 lockListenerMutex_.unlock();
481
482 SystemEvent systemEvent(LOCKSCREEN);
483 SystemEventCallBack(systemEvent, HITRACE_LOCKSCREEN);
484 return E_SCREENLOCK_OK;
485 }
486
Lock(int32_t userId)487 int32_t ScreenLockSystemAbility::Lock(int32_t userId)
488 {
489 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
490 return E_SCREENLOCK_NO_PERMISSION;
491 }
492 if (IsScreenLocked()) {
493 SCLOCK_HILOGI("Currently in a locked screen state");
494 }
495 SystemEvent systemEvent(LOCKSCREEN);
496 SystemEventCallBack(systemEvent, HITRACE_LOCKSCREEN);
497 return E_SCREENLOCK_OK;
498 }
499
IsLocked(bool & isLocked)500 int32_t ScreenLockSystemAbility::IsLocked(bool &isLocked)
501 {
502 AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
503 auto tokenType = AccessTokenKit::GetTokenTypeFlag(callerToken);
504 if (tokenType == TOKEN_HAP && !IsSystemApp()) {
505 SCLOCK_HILOGE("Calling app is not system app");
506 return E_SCREENLOCK_NOT_SYSTEM_APP;
507 }
508 isLocked = IsScreenLocked();
509 return E_SCREENLOCK_OK;
510 }
511
IsScreenLocked()512 bool ScreenLockSystemAbility::IsScreenLocked()
513 {
514 if (state_ != ServiceRunningState::STATE_RUNNING) {
515 SCLOCK_HILOGI("IsScreenLocked restart.");
516 }
517
518 int32_t userId = GetUserIdFromCallingUid();
519 std::unique_lock<std::mutex> slm(screenLockMutex_);
520 auto iter = isScreenlockedMap_.find(userId);
521 if (iter != isScreenlockedMap_.end()) {
522 return iter->second;
523 } else {
524 SCLOCK_HILOGE("The IsScreenLocked is not set. userId=%{public}d, default screenLocked: true", userId);
525 return true;
526 }
527 }
528
IsLockedWithUserId(int32_t userId,bool & isLocked)529 int32_t ScreenLockSystemAbility::IsLockedWithUserId(int32_t userId, bool &isLocked)
530 {
531 if (!IsSystemApp()) {
532 SCLOCK_HILOGE("Calling app is not system app");
533 return E_SCREENLOCK_NOT_SYSTEM_APP;
534 }
535 std::unique_lock<std::mutex> slm(screenLockMutex_);
536 auto iter = isScreenlockedMap_.find(userId);
537 if (iter != isScreenlockedMap_.end()) {
538 isLocked = iter->second;
539 return E_SCREENLOCK_OK;
540 } else {
541 isLocked = true;
542 SCLOCK_HILOGE("IsLockedWithUserId userId is not set. userId=%{public}d, default screenLocked: true", userId);
543 return E_SCREENLOCK_USER_ID_INVALID;
544 }
545 }
546
GetSecure()547 bool ScreenLockSystemAbility::GetSecure()
548 {
549 if (state_ != ServiceRunningState::STATE_RUNNING) {
550 SCLOCK_HILOGI("ScreenLockSystemAbility GetSecure restart.");
551 }
552 SCLOCK_HILOGI("ScreenLockSystemAbility GetSecure started.");
553 int callingUid = IPCSkeleton::GetCallingUid();
554 SCLOCK_HILOGD("ScreenLockSystemAbility::GetSecure callingUid=%{public}d", callingUid);
555 int userId = 0;
556 AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId);
557 if (userId == 0) {
558 AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
559 }
560 SCLOCK_HILOGD("userId=%{public}d", userId);
561 auto getInfoCallback = std::make_shared<ScreenLockGetInfoCallback>();
562 int32_t result = UserIdmClient::GetInstance().GetCredentialInfo(userId, AuthType::PIN, getInfoCallback);
563 SCLOCK_HILOGI("GetCredentialInfo AuthType::PIN result = %{public}d", result);
564 if (result == static_cast<int32_t>(ResultCode::SUCCESS)) {
565 return true;
566 }
567 return false;
568 }
569
OnSystemEvent(const sptr<ScreenLockSystemAbilityInterface> & listener)570 int32_t ScreenLockSystemAbility::OnSystemEvent(const sptr<ScreenLockSystemAbilityInterface> &listener)
571 {
572 if (!IsSystemApp()) {
573 SCLOCK_HILOGE("Calling app is not system app");
574 return E_SCREENLOCK_NOT_SYSTEM_APP;
575 }
576 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
577 return E_SCREENLOCK_NO_PERMISSION;
578 }
579 std::lock_guard<std::mutex> lck(listenerMutex_);
580 systemEventListener_ = listener;
581 stateValue_.Reset();
582 auto callback = [this]() { OnSystemReady(); };
583 if (queue_ != nullptr) {
584 queue_->submit(callback);
585 }
586 int32_t userId = GetUserIdFromCallingUid();
587 stateValue_.SetCurrentUser(userId);
588 SCLOCK_HILOGI("ScreenLockSystemAbility::OnSystemEvent end.");
589 return E_SCREENLOCK_OK;
590 }
591
SendScreenLockEvent(const std::string & event,int param)592 int32_t ScreenLockSystemAbility::SendScreenLockEvent(const std::string &event, int param)
593 {
594 SCLOCK_HILOGI("SendScreenLockEvent event=%{public}s ,param=%{public}d", event.c_str(), param);
595 if (!IsSystemApp()) {
596 SCLOCK_HILOGE("Calling app is not system app");
597 return E_SCREENLOCK_NOT_SYSTEM_APP;
598 }
599 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
600 return E_SCREENLOCK_NO_PERMISSION;
601 }
602 int stateResult = param;
603 if (event == UNLOCK_SCREEN_RESULT) {
604 UnlockScreenEvent(stateResult);
605 } else if (event == SCREEN_DRAWDONE) {
606 NotifyDisplayEvent(DisplayEvent::KEYGUARD_DRAWN);
607 } else if (event == LOCK_SCREEN_RESULT) {
608 LockScreenEvent(stateResult);
609 }
610 return E_SCREENLOCK_OK;
611 }
612
IsScreenLockDisabled(int userId,bool & isDisabled)613 int32_t ScreenLockSystemAbility::IsScreenLockDisabled(int userId, bool &isDisabled)
614 {
615 SCLOCK_HILOGI("IsScreenLockDisabled userId=%{public}d", userId);
616 auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
617 if (preferencesUtil == nullptr) {
618 SCLOCK_HILOGE("preferencesUtil is nullptr!");
619 return E_SCREENLOCK_NULLPTR;
620 }
621 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK")) {
622 SCLOCK_HILOGE("no permission: userId=%{public}d", userId);
623 return E_SCREENLOCK_NO_PERMISSION;
624 }
625 isDisabled = preferencesUtil->ObtainBool(std::to_string(userId), false);
626 SCLOCK_HILOGI("IsScreenLockDisabled isDisabled=%{public}d", isDisabled);
627 return E_SCREENLOCK_OK;
628 }
629
SetScreenLockDisabled(bool disable,int userId)630 int32_t ScreenLockSystemAbility::SetScreenLockDisabled(bool disable, int userId)
631 {
632 SCLOCK_HILOGI("SetScreenLockDisabled disable=%{public}d ,param=%{public}d", disable, userId);
633 if (GetCurrentActiveOsAccountId() != userId) {
634 SCLOCK_HILOGE("it's not currentAccountId userId=%{public}d", userId);
635 return SCREEN_FAIL;
636 }
637 if (GetSecure() == true) {
638 SCLOCK_HILOGE("The screen lock password has been set.");
639 return SCREEN_FAIL;
640 }
641 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK")) {
642 SCLOCK_HILOGE("no permission: userId=%{public}d", userId);
643 return E_SCREENLOCK_NO_PERMISSION;
644 }
645 auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
646 if (preferencesUtil == nullptr) {
647 SCLOCK_HILOGE("preferencesUtil is nullptr!");
648 return E_SCREENLOCK_NULLPTR;
649 }
650 preferencesUtil->SaveBool(std::to_string(userId), disable);
651 preferencesUtil->Refresh();
652 return E_SCREENLOCK_OK;
653 }
654
SetScreenLockAuthState(int authState,int32_t userId,std::string & authToken)655 int32_t ScreenLockSystemAbility::SetScreenLockAuthState(int authState, int32_t userId, std::string &authToken)
656 {
657 SCLOCK_HILOGI("SetScreenLockAuthState authState=%{public}d ,userId=%{public}d", authState, userId);
658 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK")) {
659 SCLOCK_HILOGE("no permission: userId=%{public}d", userId);
660 return E_SCREENLOCK_NO_PERMISSION;
661 }
662 std::unique_lock<std::mutex> lock(authStateMutex_);
663 auto iter = authStateInfo.find(userId);
664 if (iter != authStateInfo.end()) {
665 bool nextState = getDeviceLockedStateByAuth(authState);
666 bool curState = getDeviceLockedStateByAuth(iter->second);
667 if (nextState != curState) {
668 InnerListenerManager::GetInstance()->OnDeviceLockStateChanged(userId, static_cast<int32_t>(nextState));
669 }
670 iter->second = authState;
671 return E_SCREENLOCK_OK;
672 }
673 authStateInfo.insert(std::make_pair(userId, authState));
674 return E_SCREENLOCK_OK;
675 }
676
GetScreenLockAuthState(int userId,int32_t & authState)677 int32_t ScreenLockSystemAbility::GetScreenLockAuthState(int userId, int32_t &authState)
678 {
679 SCLOCK_HILOGD("GetScreenLockAuthState userId=%{public}d", userId);
680 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK")) {
681 SCLOCK_HILOGE("no permission: userId=%{public}d", userId);
682 return E_SCREENLOCK_NO_PERMISSION;
683 }
684 std::unique_lock<std::mutex> lock(authStateMutex_);
685 auto iter = authStateInfo.find(userId);
686 if (iter != authStateInfo.end()) {
687 authState = iter->second;
688 return E_SCREENLOCK_OK;
689 }
690 authState = static_cast<int32_t>(AuthState::UNAUTH);
691 SCLOCK_HILOGI("The authentication status is not set. userId=%{public}d", userId);
692 return E_SCREENLOCK_OK;
693 }
694
RequestStrongAuth(int reasonFlag,int32_t userId)695 int32_t ScreenLockSystemAbility::RequestStrongAuth(int reasonFlag, int32_t userId)
696 {
697 #ifdef IS_SO_CROP_H
698 return E_SCREENLOCK_OK;
699 #else
700 SCLOCK_HILOGI("RequestStrongAuth reasonFlag=%{public}d ,userId=%{public}d", reasonFlag, userId);
701 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK")) {
702 SCLOCK_HILOGE("no permission: userId=%{public}d", userId);
703 return E_SCREENLOCK_NO_PERMISSION;
704 }
705 StrongAuthManger::GetInstance()->SetStrongAuthStat(userId, reasonFlag);
706 StrongAuthChanged(userId, reasonFlag);
707 InnerListenerManager::GetInstance()->OnStrongAuthChanged(userId, reasonFlag);
708 return E_SCREENLOCK_OK;
709 #endif // IS_SO_CROP_H
710 }
711
GetStrongAuth(int userId,int32_t & reasonFlag)712 int32_t ScreenLockSystemAbility::GetStrongAuth(int userId, int32_t &reasonFlag)
713 {
714 #ifdef IS_SO_CROP_H
715 reasonFlag = 0;
716 return E_SCREENLOCK_OK;
717 #else
718 reasonFlag = StrongAuthManger::GetInstance()->GetStrongAuthStat(userId);
719 SCLOCK_HILOGI("GetStrongAuth userId=%{public}d, reasonFlag=%{public}d", userId, reasonFlag);
720 return E_SCREENLOCK_OK;
721 #endif // IS_SO_CROP_H
722 }
723
RegisterInnerListener(const int32_t userId,const ListenType listenType,const sptr<InnerListenerIf> & listener)724 int32_t ScreenLockSystemAbility::RegisterInnerListener(const int32_t userId, const ListenType listenType,
725 const sptr<InnerListenerIf>& listener)
726 {
727 if (!IsSystemApp()) {
728 SCLOCK_HILOGE("Calling app is not system app");
729 return E_SCREENLOCK_NOT_SYSTEM_APP;
730 }
731
732 if (listenType == ListenType::STRONG_AUTH && !CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK")) {
733 return E_SCREENLOCK_NO_PERMISSION;
734 }
735
736 return InnerListenerManager::GetInstance()->RegisterInnerListener(userId, listenType, listener);
737 }
738
UnRegisterInnerListener(const int32_t userId,const ListenType listenType,const sptr<InnerListenerIf> & listener)739 int32_t ScreenLockSystemAbility::UnRegisterInnerListener(const int32_t userId, const ListenType listenType,
740 const sptr<InnerListenerIf>& listener)
741 {
742 if (!IsSystemApp()) {
743 SCLOCK_HILOGE("Calling app is not system app");
744 return E_SCREENLOCK_NOT_SYSTEM_APP;
745 }
746
747 if (listenType == ListenType::STRONG_AUTH && !CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK")) {
748 return E_SCREENLOCK_NO_PERMISSION;
749 }
750
751 return InnerListenerManager::GetInstance()->UnRegisterInnerListener(listenType, listener);
752 }
753
SetScreenlocked(bool isScreenlocked,const int32_t userId)754 void ScreenLockSystemAbility::SetScreenlocked(bool isScreenlocked, const int32_t userId)
755 {
756 SCLOCK_HILOGI("SetScreenlocked state:%{public}d, userId:%{public}d", isScreenlocked, userId);
757 std::unique_lock<std::mutex> slm(screenLockMutex_);
758 auto iter = isScreenlockedMap_.find(userId);
759 if (iter != isScreenlockedMap_.end()) {
760 iter->second = isScreenlocked;
761 } else {
762 isScreenlockedMap_.insert(std::make_pair(userId, isScreenlocked));
763 }
764 }
765
IsDeviceLocked(int userId,bool & isDeviceLocked)766 int32_t ScreenLockSystemAbility::IsDeviceLocked(int userId, bool &isDeviceLocked)
767 {
768 if (!IsSystemApp()) {
769 SCLOCK_HILOGE("Calling app is not system app");
770 return E_SCREENLOCK_NOT_SYSTEM_APP;
771 }
772
773 std::unique_lock<std::mutex> lock(authStateMutex_);
774 auto iter = authStateInfo.find(userId);
775 if (iter != authStateInfo.end()) {
776 int32_t authState = iter->second;
777 isDeviceLocked = getDeviceLockedStateByAuth(authState);
778 SCLOCK_HILOGI("IsDeviceLocked. userId=%{public}d, isDeviceLocked=%{public}d", userId, isDeviceLocked);
779 return E_SCREENLOCK_OK;
780 } else {
781 isDeviceLocked = true;
782 SCLOCK_HILOGI("user not set. userId=%{public}d, isDeviceLocked=%{public}d", userId, isDeviceLocked);
783 return E_SCREENLOCK_USER_ID_INVALID;
784 }
785 }
786
Reset()787 void StateValue::Reset()
788 {
789 screenlockEnabled_ = true;
790 currentUser_ = USER_NULL;
791 }
792
Dump(int fd,const std::vector<std::u16string> & args)793 int ScreenLockSystemAbility::Dump(int fd, const std::vector<std::u16string> &args)
794 {
795 #ifdef IS_SO_CROP_H
796 return ERR_OK;
797 #else
798 int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
799 const int maxUid = 10000;
800 if (uid > maxUid) {
801 return 0;
802 }
803
804 std::vector<std::string> argsStr;
805 for (auto item : args) {
806 argsStr.emplace_back(Str16ToStr8(item));
807 }
808
809 DumpHelper::GetInstance().Dispatch(fd, argsStr);
810 return ERR_OK;
811 #endif // IS_SO_CROP_H
812 }
813
RegisterDumpCommand()814 void ScreenLockSystemAbility::RegisterDumpCommand()
815 {
816 #ifdef IS_SO_CROP_H
817 return;
818 #else
819 auto cmd = std::make_shared<Command>(std::vector<std::string>{ "-all" }, "dump all screenlock information",
820 [this](const std::vector<std::string> &input, std::string &output) -> bool {
821 bool screenState = stateValue_.GetScreenState();
822 int32_t offReason = stateValue_.GetOffReason();
823 int32_t interactiveState = stateValue_.GetInteractiveState();
824 string temp_screenState = "";
825 screenState ? temp_screenState = "true" : temp_screenState = "false";
826 output.append("\n Screenlock system state\\tValue\\t\\tDescription\n")
827 .append(" * screenState \t\t" + temp_screenState + "\t\tscreen on / off status\n")
828 .append(" * offReason \t\t\t" + std::to_string(offReason) + "\t\tscreen failure reason\n")
829 .append(" * interactiveState \t\t" + std::to_string(interactiveState) +
830 "\t\tscreen interaction status\n");
831
832 std::unique_lock<std::mutex> authStateLock(authStateMutex_);
833 for (auto iter = authStateInfo.begin(); iter != authStateInfo.end(); iter++) {
834 int32_t userId = iter->first;
835 bool deviceLocked = getDeviceLockedStateByAuth(iter->second);
836 string temp_deviceLocked = "";
837 deviceLocked ? temp_deviceLocked = "true" : temp_deviceLocked = "false";
838 string temp_userId = std::to_string(static_cast<int>(userId));
839 string temp_authState = std::to_string(static_cast<int>(iter->second));
840 output.append(" * deviceLocked \t\t" + temp_deviceLocked + "\t\t" + temp_userId + "\n");
841 output.append(" * authState \t\t" + temp_authState + "\t\t" + temp_userId + "\n");
842 }
843 authStateLock.unlock();
844
845 std::unique_lock<std::mutex> screenLockedLock(screenLockMutex_);
846 for (auto iter = isScreenlockedMap_.begin(); iter != isScreenlockedMap_.end(); iter++) {
847 int32_t userId = iter->first;
848 bool isLocked = iter->second;
849 string temp_screenLocked = "";
850 isLocked ? temp_screenLocked = "true" : temp_screenLocked = "false";
851 string temp_userId = std::to_string(static_cast<int>(userId));
852 output.append(" * screenLocked \t\t" + temp_screenLocked + "\t\t" + temp_userId + "\n");
853 }
854 screenLockedLock.unlock();
855 return true;
856 });
857 DumpHelper::GetInstance().RegisterCommand(cmd);
858 #endif // IS_SO_CROP_H
859 }
860
PublishEvent(const std::string & eventAction,const int32_t userId)861 void ScreenLockSystemAbility::PublishEvent(const std::string &eventAction, const int32_t userId)
862 {
863 AAFwk::Want want;
864 want.SetAction(eventAction);
865 want.SetParam("userId", userId);
866 EventFwk::CommonEventData commonData(want);
867 bool ret = EventFwk::CommonEventManager::PublishCommonEvent(commonData);
868 SCLOCK_HILOGD("Publish event result is:%{public}d", ret);
869 }
870
LockScreenEvent(int stateResult)871 void ScreenLockSystemAbility::LockScreenEvent(int stateResult)
872 {
873 SCLOCK_HILOGD("ScreenLockSystemAbility LockScreenEvent stateResult:%{public}d", stateResult);
874 int32_t userId = 0;
875 if (stateResult == ScreenChange::SCREEN_SUCC) {
876 userId = GetUserIdFromCallingUid();
877 SetScreenlocked(true, userId);
878 }
879 std::lock_guard<std::mutex> autoLock(lockListenerMutex_);
880 if (lockVecListeners_.size()) {
881 auto callback = [this, stateResult]() {
882 std::lock_guard<std::mutex> guard(lockListenerMutex_);
883 for (size_t i = 0; i < lockVecListeners_.size(); i++) {
884 lockVecListeners_[i]->OnCallBack(stateResult);
885 }
886 lockVecListeners_.clear();
887 };
888 ffrt::submit(callback);
889 }
890 if (stateResult == ScreenChange::SCREEN_SUCC) {
891 PublishEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED, userId);
892 }
893 }
894
UnlockScreenEvent(int stateResult)895 void ScreenLockSystemAbility::UnlockScreenEvent(int stateResult)
896 {
897 SCLOCK_HILOGD("ScreenLockSystemAbility UnlockScreenEvent stateResult:%{public}d", stateResult);
898 if (stateResult == ScreenChange::SCREEN_SUCC) {
899 int32_t userId = GetUserIdFromCallingUid();
900 SetScreenlocked(false, userId);
901 NotifyDisplayEvent(DisplayEvent::UNLOCK);
902 PublishEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED, userId);
903 }
904
905 if (stateResult != ScreenChange::SCREEN_FAIL) {
906 NotifyUnlockListener(stateResult);
907 }
908 }
909
SystemEventCallBack(const SystemEvent & systemEvent,TraceTaskId traceTaskId)910 void ScreenLockSystemAbility::SystemEventCallBack(const SystemEvent &systemEvent, TraceTaskId traceTaskId)
911 {
912 SCLOCK_HILOGI("eventType is %{public}s, params is %{public}s", systemEvent.eventType_.c_str(),
913 systemEvent.params_.c_str());
914 {
915 std::lock_guard<std::mutex> lck(listenerMutex_);
916 if (systemEventListener_ == nullptr) {
917 SCLOCK_HILOGE("systemEventListener_ is nullptr.");
918 return;
919 }
920 }
921 auto callback = [this, systemEvent, traceTaskId]() {
922 if (traceTaskId != HITRACE_BUTT) {
923 StartAsyncTrace(HITRACE_TAG_MISC, "ScreenLockSystemAbility::" + systemEvent.eventType_ + "begin callback",
924 traceTaskId);
925 }
926 std::lock_guard<std::mutex> lck(listenerMutex_);
927 systemEventListener_->OnCallBack(systemEvent);
928 if (traceTaskId != HITRACE_BUTT) {
929 FinishAsyncTrace(HITRACE_TAG_MISC, "ScreenLockSystemAbility::" + systemEvent.eventType_ + "end callback",
930 traceTaskId);
931 }
932 };
933 if (queue_ != nullptr) {
934 queue_->submit(callback);
935 }
936 }
937
NotifyUnlockListener(const int32_t screenLockResult)938 void ScreenLockSystemAbility::NotifyUnlockListener(const int32_t screenLockResult)
939 {
940 std::lock_guard<std::mutex> autoLock(unlockListenerMutex_);
941 if (unlockVecListeners_.size()) {
942 auto callback = [this, screenLockResult]() {
943 std::lock_guard<std::mutex> guard(unlockListenerMutex_);
944 for (size_t i = 0; i < unlockVecListeners_.size(); i++) {
945 unlockVecListeners_[i]->OnCallBack(screenLockResult);
946 }
947 unlockVecListeners_.clear();
948 };
949 ffrt::submit(callback);
950 }
951 }
952
NotifyDisplayEvent(DisplayEvent event)953 void ScreenLockSystemAbility::NotifyDisplayEvent(DisplayEvent event)
954 {
955 if (queue_ == nullptr) {
956 SCLOCK_HILOGE("NotifyDisplayEvent queue_ is nullptr.");
957 return;
958 }
959 auto callback = [event]() { DisplayManager::GetInstance().NotifyDisplayEvent(event); };
960 queue_->submit(callback);
961 }
962
ResetFfrtQueue()963 void ScreenLockSystemAbility::ResetFfrtQueue()
964 {
965 queue_.reset();
966 }
967
IsAppInForeground(int32_t callingPid,uint32_t callingTokenId)968 bool ScreenLockSystemAbility::IsAppInForeground(int32_t callingPid, uint32_t callingTokenId)
969 {
970 #ifdef CONFIG_FACTORY_MODE
971 return true;
972 #endif
973 FocusChangeInfo focusInfo;
974 WindowManager::GetInstance().GetFocusWindowInfo(focusInfo);
975 if (callingPid == focusInfo.pid_) {
976 return true;
977 }
978 bool isFocused = false;
979 std::string identity = IPCSkeleton::ResetCallingIdentity();
980 auto ret = AAFwk::AbilityManagerClient::GetInstance()->CheckUIExtensionIsFocused(callingTokenId, isFocused);
981 IPCSkeleton::SetCallingIdentity(identity);
982 SCLOCK_HILOGI("tokenId:%{public}d check result:%{public}d, isFocused:%{public}d", callingTokenId, ret, isFocused);
983 return ret == ERR_OK && isFocused;
984 }
985
IsSystemApp()986 bool ScreenLockSystemAbility::IsSystemApp()
987 {
988 return TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID());
989 }
990
CheckPermission(const std::string & permissionName)991 bool ScreenLockSystemAbility::CheckPermission(const std::string &permissionName)
992 {
993 AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
994 int result = AccessTokenKit::VerifyAccessToken(callerToken, permissionName);
995 if (result != PERMISSION_GRANTED) {
996 SCLOCK_HILOGE("check permission failed.");
997 return false;
998 }
999 return true;
1000 }
1001
getDeviceLockedStateByAuth(int32_t authState)1002 bool ScreenLockSystemAbility::getDeviceLockedStateByAuth(int32_t authState)
1003 {
1004 int32_t authBoundary = static_cast<int32_t>(AuthState::AUTHED_BY_CREDENTIAL);
1005 if (authState >= authBoundary) {
1006 return false;
1007 }
1008 return true;
1009 }
1010
authStateInit(const int32_t userId)1011 void ScreenLockSystemAbility::authStateInit(const int32_t userId)
1012 {
1013 std::unique_lock<std::mutex> authLock(authStateMutex_);
1014 auto authIter = authStateInfo.find(userId);
1015 if (authIter == authStateInfo.end()) {
1016 authStateInfo.insert(std::make_pair(userId, static_cast<int32_t>(AuthState::UNAUTH)));
1017 }
1018 authLock.unlock();
1019
1020 std::unique_lock<std::mutex> screenStateLock(screenLockMutex_);
1021 auto lockIter = isScreenlockedMap_.find(userId);
1022 if (lockIter == isScreenlockedMap_.end()) {
1023 isScreenlockedMap_.insert(std::make_pair(userId, true));
1024 }
1025 screenStateLock.unlock();
1026 }
1027 } // namespace ScreenLock
1028 } // namespace OHOS