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 #include "commeventsubscriber.h"
51 #include "user_auth_client_callback.h"
52 #include "user_auth_client_impl.h"
53 #include "strongauthmanager.h"
54
55 using namespace OHOS;
56 using namespace OHOS::ScreenLock;
57
58 namespace OHOS {
59 namespace ScreenLock {
60 using namespace std;
61 using namespace OHOS::HiviewDFX;
62 using namespace OHOS::Rosen;
63 using namespace OHOS::UserIam::UserAuth;
64 using namespace OHOS::Security::AccessToken;
65 using namespace OHOS::AccountSA;
66 REGISTER_SYSTEM_ABILITY_BY_ID(ScreenLockSystemAbility, SCREENLOCK_SERVICE_ID, true);
67 const std::int64_t TIME_OUT_MILLISECONDS = 10000L;
68 const std::int64_t INIT_INTERVAL = 5000000L;
69 const std::int64_t DELAY_TIME = 1000000L;
70 std::mutex ScreenLockSystemAbility::instanceLock_;
71 sptr<ScreenLockSystemAbility> ScreenLockSystemAbility::instance_;
72 constexpr int32_t MAX_RETRY_TIMES = 20;
73 std::shared_ptr<ffrt::queue> ScreenLockSystemAbility::queue_;
ScreenLockSystemAbility(int32_t systemAbilityId,bool runOnCreate)74 ScreenLockSystemAbility::ScreenLockSystemAbility(int32_t systemAbilityId, bool runOnCreate)
75 : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START)
76 {}
77
~ScreenLockSystemAbility()78 ScreenLockSystemAbility::~ScreenLockSystemAbility() {}
79
GetInstance()80 sptr<ScreenLockSystemAbility> ScreenLockSystemAbility::GetInstance()
81 {
82 if (instance_ == nullptr) {
83 std::lock_guard<std::mutex> autoLock(instanceLock_);
84 if (instance_ == nullptr) {
85 SCLOCK_HILOGI("ScreenLockSystemAbility create instance.");
86 instance_ = new ScreenLockSystemAbility(SCREENLOCK_SERVICE_ID, true);
87 }
88 }
89 return instance_;
90 }
91
GetCurrentActiveOsAccountId()92 static int32_t GetCurrentActiveOsAccountId()
93 {
94 std::vector<int> activatedOsAccountIds;
95 OHOS::ErrCode res = OsAccountManager::QueryActiveOsAccountIds(activatedOsAccountIds);
96 if (res != OHOS::ERR_OK || (activatedOsAccountIds.size() <= 0)) {
97 SCLOCK_HILOGE("QueryActiveOsAccountIds fail. [Res]: %{public}d", res);
98 return SCREEN_FAIL;
99 }
100 int osAccountId = activatedOsAccountIds[0];
101 SCLOCK_HILOGI("GetCurrentActiveOsAccountId.[osAccountId]:%{public}d", osAccountId);
102 return osAccountId;
103 }
104
AccountSubscriber(const OsAccountSubscribeInfo & subscribeInfo)105 ScreenLockSystemAbility::AccountSubscriber::AccountSubscriber(const OsAccountSubscribeInfo &subscribeInfo)
106 : OsAccountSubscriber(subscribeInfo)
107 {}
108
OnAccountsChanged(const int & id)109 void ScreenLockSystemAbility::AccountSubscriber::OnAccountsChanged(const int &id)
110 {
111 SCLOCK_HILOGI("OnAccountsChanged.[osAccountId]:%{public}d, [lastId]:%{public}d", id, userId_);
112 StrongAuthManger::GetInstance()->StartStrongAuthTimer(id);
113 userId_ = id;
114 auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
115 if (preferencesUtil == nullptr) {
116 SCLOCK_HILOGE("preferencesUtil is nullptr!");
117 return;
118 }
119 if (preferencesUtil->ObtainBool(std::to_string(id), false)) {
120 return;
121 }
122 preferencesUtil->SaveBool(std::to_string(id), false);
123 preferencesUtil->Refresh();
124 return;
125 }
126
Init()127 int32_t ScreenLockSystemAbility::Init()
128 {
129 bool ret = Publish(ScreenLockSystemAbility::GetInstance());
130 if (!ret) {
131 SCLOCK_HILOGE("Publish ScreenLockSystemAbility failed.");
132 return E_SCREENLOCK_PUBLISH_FAIL;
133 }
134 stateValue_.Reset();
135 SCLOCK_HILOGI("Init ScreenLockSystemAbility success.");
136 return ERR_OK;
137 }
138
OnStart()139 void ScreenLockSystemAbility::OnStart()
140 {
141 SCLOCK_HILOGI("ScreenLockSystemAbility::Enter OnStart.");
142 if (instance_ == nullptr) {
143 instance_ = this;
144 }
145 if (state_ == ServiceRunningState::STATE_RUNNING) {
146 SCLOCK_HILOGW("ScreenLockSystemAbility is already running.");
147 return;
148 }
149 InitServiceHandler();
150 if (Init() != ERR_OK) {
151 auto callback = [=]() { Init(); };
152 queue_->submit(callback, ffrt::task_attr().delay(INIT_INTERVAL));
153 SCLOCK_HILOGW("ScreenLockSystemAbility Init failed. Try again 5s later");
154 }
155 AddSystemAbilityListener(DISPLAY_MANAGER_SERVICE_SA_ID);
156 AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN);
157 AddSystemAbilityListener(SUBSYS_USERIAM_SYS_ABILITY_USERIDM);
158 RegisterDumpCommand();
159 return;
160 }
161
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)162 void ScreenLockSystemAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
163 {
164 SCLOCK_HILOGI("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
165 if (systemAbilityId == DISPLAY_MANAGER_SERVICE_SA_ID) {
166 int times = 0;
167 if (displayPowerEventListener_ == nullptr) {
168 displayPowerEventListener_ = new ScreenLockSystemAbility::ScreenLockDisplayPowerEventListener();
169 }
170 RegisterDisplayPowerEventListener(times);
171 }
172 if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) {
173 InitUserId();
174 }
175 if (systemAbilityId == SUBSYS_USERIAM_SYS_ABILITY_USERIDM) {
176 StrongAuthManger::GetInstance()->RegistUserAuthSuccessEventListener();
177 }
178 }
179
RegisterDisplayPowerEventListener(int32_t times)180 void ScreenLockSystemAbility::RegisterDisplayPowerEventListener(int32_t times)
181 {
182 times++;
183 systemReady_ =
184 (DisplayManager::GetInstance().RegisterDisplayPowerEventListener(displayPowerEventListener_) == DMError::DM_OK);
185 if (systemReady_ == false && times <= MAX_RETRY_TIMES) {
186 SCLOCK_HILOGW("RegisterDisplayPowerEventListener failed");
187 auto callback = [this, times]() { RegisterDisplayPowerEventListener(times); };
188 queue_->submit(callback, ffrt::task_attr().delay(DELAY_TIME));
189 } else if (systemReady_) {
190 state_ = ServiceRunningState::STATE_RUNNING;
191 SCLOCK_HILOGI("systemReady_ is true");
192 }
193 SCLOCK_HILOGI("RegisterDisplayPowerEventListener, times:%{public}d", times);
194 }
195
InitServiceHandler()196 void ScreenLockSystemAbility::InitServiceHandler()
197 {
198 if (queue_ != nullptr) {
199 SCLOCK_HILOGI("InitServiceHandler already init.");
200 return;
201 }
202 queue_ = std::make_shared<ffrt::queue>("ScreenLockSystemAbility");
203 SCLOCK_HILOGI("InitServiceHandler succeeded.");
204 }
205
InitUserId()206 void ScreenLockSystemAbility::InitUserId()
207 {
208 OsAccountSubscribeInfo subscribeInfo;
209 subscribeInfo.SetOsAccountSubscribeType(OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVED);
210 accountSubscriber_ = std::make_shared<AccountSubscriber>(subscribeInfo);
211
212 int32_t ret = OsAccountManager::SubscribeOsAccount(accountSubscriber_);
213 if (ret != ERR_OK) {
214 SCLOCK_HILOGE("SubscribeOsAccount failed.[ret]:%{public}d", ret);
215 }
216 Singleton<CommeventMgr>::GetInstance().SubscribeEvent();
217
218 int userId = GetCurrentActiveOsAccountId();
219 auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
220 if (preferencesUtil == nullptr) {
221 SCLOCK_HILOGE("preferencesUtil is nullptr!");
222 return;
223 }
224 if (preferencesUtil->ObtainBool(std::to_string(userId), false)) {
225 return;
226 }
227 preferencesUtil->SaveBool(std::to_string(userId), false);
228 preferencesUtil->Refresh();
229 return;
230 }
231
OnStop()232 void ScreenLockSystemAbility::OnStop()
233 {
234 SCLOCK_HILOGI("OnStop started.");
235 if (state_ != ServiceRunningState::STATE_RUNNING) {
236 return;
237 }
238 queue_ = nullptr;
239 instance_ = nullptr;
240 state_ = ServiceRunningState::STATE_NOT_START;
241 DisplayManager::GetInstance().UnregisterDisplayPowerEventListener(displayPowerEventListener_);
242 StrongAuthManger::GetInstance()->UnRegistUserAuthSuccessEventListener();
243 StrongAuthManger::GetInstance()->DestroyAllStrongAuthTimer();
244 int ret = OsAccountManager::UnsubscribeOsAccount(accountSubscriber_);
245 if (ret != SUCCESS) {
246 SCLOCK_HILOGE("unsubscribe os account failed, code=%{public}d", ret);
247 }
248 SCLOCK_HILOGI("OnStop end.");
249 }
250
OnDisplayPowerEvent(DisplayPowerEvent event,EventStatus status)251 void ScreenLockSystemAbility::ScreenLockDisplayPowerEventListener::OnDisplayPowerEvent(DisplayPowerEvent event,
252 EventStatus status)
253 {
254 SCLOCK_HILOGI("OnDisplayPowerEvent event=%{public}d,status= %{public}d", static_cast<int>(event),
255 static_cast<int>(status));
256 switch (event) {
257 case DisplayPowerEvent::WAKE_UP:
258 instance_->OnWakeUp(status);
259 break;
260 case DisplayPowerEvent::SLEEP:
261 instance_->OnSleep(status);
262 break;
263 case DisplayPowerEvent::DISPLAY_ON:
264 instance_->OnScreenOn(status);
265 break;
266 case DisplayPowerEvent::DISPLAY_OFF:
267 instance_->OnScreenOff(status);
268 break;
269 case DisplayPowerEvent::DESKTOP_READY:
270 instance_->OnExitAnimation();
271 break;
272 default:
273 break;
274 }
275 }
276
OnScreenOff(EventStatus status)277 void ScreenLockSystemAbility::OnScreenOff(EventStatus status)
278 {
279 SystemEvent systemEvent(BEGIN_SCREEN_OFF);
280 if (status == EventStatus::BEGIN) {
281 stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_BEGIN_OFF));
282 } else if (status == EventStatus::END) {
283 stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_END_OFF));
284 systemEvent.eventType_ = END_SCREEN_OFF;
285 }
286 SystemEventCallBack(systemEvent);
287 }
288
OnScreenOn(EventStatus status)289 void ScreenLockSystemAbility::OnScreenOn(EventStatus status)
290 {
291 SystemEvent systemEvent(BEGIN_SCREEN_ON);
292 if (status == EventStatus::BEGIN) {
293 stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_BEGIN_ON));
294 } else if (status == EventStatus::END) {
295 stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_END_ON));
296 systemEvent.eventType_ = END_SCREEN_ON;
297 }
298 SystemEventCallBack(systemEvent);
299 }
300
OnSystemReady()301 void ScreenLockSystemAbility::OnSystemReady()
302 {
303 SCLOCK_HILOGI("ScreenLockSystemAbility OnSystemReady started.");
304 bool isExitFlag = false;
305 int tryTime = 50;
306 int minTryTime = 0;
307 while (!isExitFlag && (tryTime > minTryTime)) {
308 if (systemEventListener_ != nullptr && systemReady_) {
309 SCLOCK_HILOGI("ScreenLockSystemAbility OnSystemReady started1.");
310 std::lock_guard<std::mutex> lck(listenerMutex_);
311 SystemEvent systemEvent(SYSTEM_READY);
312 systemEventListener_->OnCallBack(systemEvent);
313 isExitFlag = true;
314 } else {
315 SCLOCK_HILOGE("ScreenLockSystemAbility OnSystemReady type not found., tryTime = %{public}d", tryTime);
316 sleep(1);
317 }
318 --tryTime;
319 }
320 }
321
OnWakeUp(EventStatus status)322 void ScreenLockSystemAbility::OnWakeUp(EventStatus status)
323 {
324 SystemEvent systemEvent(BEGIN_WAKEUP);
325 if (status == EventStatus::BEGIN) {
326 stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_BEGIN_WAKEUP));
327 } else if (status == EventStatus::END) {
328 stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_END_WAKEUP));
329 systemEvent.eventType_ = END_WAKEUP;
330 }
331 SystemEventCallBack(systemEvent);
332 }
333
OnSleep(EventStatus status)334 void ScreenLockSystemAbility::OnSleep(EventStatus status)
335 {
336 SystemEvent systemEvent(BEGIN_SLEEP);
337 if (status == EventStatus::BEGIN) {
338 stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_BEGIN_SLEEP));
339 } else if (status == EventStatus::END) {
340 stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_END_SLEEP));
341 systemEvent.eventType_ = END_SLEEP;
342 }
343 SystemEventCallBack(systemEvent);
344 }
345
OnExitAnimation()346 void ScreenLockSystemAbility::OnExitAnimation()
347 {
348 SystemEvent systemEvent(EXIT_ANIMATION);
349 SystemEventCallBack(systemEvent);
350 }
351
StrongAuthChanged(int32_t userId,int32_t reasonFlag)352 void ScreenLockSystemAbility::StrongAuthChanged(int32_t userId, int32_t reasonFlag)
353 {
354 SystemEvent systemEvent(STRONG_AUTH_CHANGED);
355 systemEvent.userId_ = userId;
356 systemEvent.params_ = std::to_string(reasonFlag);
357 SystemEventCallBack(systemEvent);
358 SCLOCK_HILOGI("StrongAuthChanged: userId: %{public}d, reasonFlag:%{public}d", userId, reasonFlag);
359 }
360
UnlockScreen(const sptr<ScreenLockCallbackInterface> & listener)361 int32_t ScreenLockSystemAbility::UnlockScreen(const sptr<ScreenLockCallbackInterface> &listener)
362 {
363 StartAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen begin", HITRACE_UNLOCKSCREEN);
364 return UnlockInner(listener);
365 }
366
Unlock(const sptr<ScreenLockCallbackInterface> & listener)367 int32_t ScreenLockSystemAbility::Unlock(const sptr<ScreenLockCallbackInterface> &listener)
368 {
369 StartAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen begin", HITRACE_UNLOCKSCREEN);
370 if (!IsSystemApp()) {
371 FinishAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen end, Calling app is not system app", HITRACE_UNLOCKSCREEN);
372 SCLOCK_HILOGE("Calling app is not system app");
373 return E_SCREENLOCK_NOT_SYSTEM_APP;
374 }
375 return UnlockInner(listener);
376 }
377
UnlockInner(const sptr<ScreenLockCallbackInterface> & listener)378 int32_t ScreenLockSystemAbility::UnlockInner(const sptr<ScreenLockCallbackInterface> &listener)
379 {
380 if (state_ != ServiceRunningState::STATE_RUNNING) {
381 SCLOCK_HILOGW("UnlockScreen restart.");
382 OnStart();
383 }
384 AccessTokenID callerTokenId = IPCSkeleton::GetCallingTokenID();
385 // check whether the page of app request unlock is the focus page
386 bool hasPermission = CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK");
387 SCLOCK_HILOGE("hasPermission: {public}%d.", hasPermission);
388 if (AccessTokenKit::GetTokenTypeFlag(callerTokenId) != TOKEN_NATIVE &&
389 !IsAppInForeground(IPCSkeleton::GetCallingPid(), callerTokenId) && !hasPermission) {
390 FinishAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen end, Unfocused", HITRACE_UNLOCKSCREEN);
391 SCLOCK_HILOGE("UnlockScreen Unfocused.");
392 return E_SCREENLOCK_NOT_FOCUS_APP;
393 }
394 unlockListenerMutex_.lock();
395 unlockVecListeners_.push_back(listener);
396 unlockListenerMutex_.unlock();
397 SystemEvent systemEvent(UNLOCKSCREEN);
398 SystemEventCallBack(systemEvent, HITRACE_UNLOCKSCREEN);
399 FinishAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen end", HITRACE_UNLOCKSCREEN);
400 return E_SCREENLOCK_OK;
401 }
402
Lock(const sptr<ScreenLockCallbackInterface> & listener)403 int32_t ScreenLockSystemAbility::Lock(const sptr<ScreenLockCallbackInterface> &listener)
404 {
405 if (!IsSystemApp()) {
406 SCLOCK_HILOGE("Calling app is not system app");
407 return E_SCREENLOCK_NOT_SYSTEM_APP;
408 }
409 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
410 return E_SCREENLOCK_NO_PERMISSION;
411 }
412 if (stateValue_.GetScreenlockedState()) {
413 SCLOCK_HILOGI("Currently in a locked screen state");
414 }
415 lockListenerMutex_.lock();
416 lockVecListeners_.push_back(listener);
417 lockListenerMutex_.unlock();
418
419 SystemEvent systemEvent(LOCKSCREEN);
420 SystemEventCallBack(systemEvent, HITRACE_LOCKSCREEN);
421 return E_SCREENLOCK_OK;
422 }
423
Lock(int32_t userId)424 int32_t ScreenLockSystemAbility::Lock(int32_t userId)
425 {
426 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
427 return E_SCREENLOCK_NO_PERMISSION;
428 }
429 if (stateValue_.GetScreenlockedState()) {
430 SCLOCK_HILOGI("Currently in a locked screen state");
431 }
432 SystemEvent systemEvent(LOCKSCREEN);
433 SystemEventCallBack(systemEvent, HITRACE_LOCKSCREEN);
434 return E_SCREENLOCK_OK;
435 }
436
IsLocked(bool & isLocked)437 int32_t ScreenLockSystemAbility::IsLocked(bool &isLocked)
438 {
439 AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
440 auto tokenType = AccessTokenKit::GetTokenTypeFlag(callerToken);
441 if (tokenType == TOKEN_HAP && !IsSystemApp()) {
442 SCLOCK_HILOGE("Calling app is not system app");
443 return E_SCREENLOCK_NOT_SYSTEM_APP;
444 }
445 isLocked = IsScreenLocked();
446 return E_SCREENLOCK_OK;
447 }
448
IsScreenLocked()449 bool ScreenLockSystemAbility::IsScreenLocked()
450 {
451 if (state_ != ServiceRunningState::STATE_RUNNING) {
452 SCLOCK_HILOGW("IsScreenLocked restart.");
453 OnStart();
454 }
455 return stateValue_.GetScreenlockedState();
456 }
457
GetSecure()458 bool ScreenLockSystemAbility::GetSecure()
459 {
460 if (state_ != ServiceRunningState::STATE_RUNNING) {
461 SCLOCK_HILOGW("ScreenLockSystemAbility GetSecure restart.");
462 OnStart();
463 }
464 SCLOCK_HILOGI("ScreenLockSystemAbility GetSecure started.");
465 int callingUid = IPCSkeleton::GetCallingUid();
466 SCLOCK_HILOGD("ScreenLockSystemAbility::GetSecure callingUid=%{public}d", callingUid);
467 int userId = 0;
468 AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId);
469 if (userId == 0) {
470 AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
471 }
472 SCLOCK_HILOGD("userId=%{public}d", userId);
473 auto getInfoCallback = std::make_shared<ScreenLockGetInfoCallback>();
474 int32_t result = UserIdmClient::GetInstance().GetCredentialInfo(userId, AuthType::PIN, getInfoCallback);
475 SCLOCK_HILOGI("GetCredentialInfo AuthType::PIN result = %{public}d", result);
476 if (result == static_cast<int32_t>(ResultCode::SUCCESS)) {
477 return true;
478 }
479 return false;
480 }
481
OnSystemEvent(const sptr<ScreenLockSystemAbilityInterface> & listener)482 int32_t ScreenLockSystemAbility::OnSystemEvent(const sptr<ScreenLockSystemAbilityInterface> &listener)
483 {
484 if (!IsSystemApp()) {
485 SCLOCK_HILOGE("Calling app is not system app");
486 return E_SCREENLOCK_NOT_SYSTEM_APP;
487 }
488 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
489 return E_SCREENLOCK_NO_PERMISSION;
490 }
491 std::lock_guard<std::mutex> lck(listenerMutex_);
492 systemEventListener_ = listener;
493 stateValue_.Reset();
494 auto callback = [this]() { OnSystemReady(); };
495 queue_->submit(callback);
496 SCLOCK_HILOGI("ScreenLockSystemAbility::OnSystemEvent end.");
497 return E_SCREENLOCK_OK;
498 }
499
SendScreenLockEvent(const std::string & event,int param)500 int32_t ScreenLockSystemAbility::SendScreenLockEvent(const std::string &event, int param)
501 {
502 SCLOCK_HILOGI("SendScreenLockEvent event=%{public}s ,param=%{public}d", event.c_str(), param);
503 if (!IsSystemApp()) {
504 SCLOCK_HILOGE("Calling app is not system app");
505 return E_SCREENLOCK_NOT_SYSTEM_APP;
506 }
507 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
508 return E_SCREENLOCK_NO_PERMISSION;
509 }
510 int stateResult = param;
511 if (event == UNLOCK_SCREEN_RESULT) {
512 UnlockScreenEvent(stateResult);
513 } else if (event == SCREEN_DRAWDONE) {
514 NotifyDisplayEvent(DisplayEvent::KEYGUARD_DRAWN);
515 } else if (event == LOCK_SCREEN_RESULT) {
516 LockScreenEvent(stateResult);
517 }
518 return E_SCREENLOCK_OK;
519 }
520
IsScreenLockDisabled(int userId,bool & isDisabled)521 int32_t ScreenLockSystemAbility::IsScreenLockDisabled(int userId, bool &isDisabled)
522 {
523 SCLOCK_HILOGI("IsScreenLockDisabled userId=%{public}d", userId);
524 auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
525 if (preferencesUtil == nullptr) {
526 SCLOCK_HILOGE("preferencesUtil is nullptr!");
527 return E_SCREENLOCK_NULLPTR;
528 }
529 isDisabled = preferencesUtil->ObtainBool(std::to_string(userId), false);
530 SCLOCK_HILOGI("IsScreenLockDisabled isDisabled=%{public}d", isDisabled);
531 return E_SCREENLOCK_OK;
532 }
533
SetScreenLockDisabled(bool disable,int userId)534 int32_t ScreenLockSystemAbility::SetScreenLockDisabled(bool disable, int userId)
535 {
536 SCLOCK_HILOGI("SetScreenLockDisabled disable=%{public}d ,param=%{public}d", disable, userId);
537 if (GetCurrentActiveOsAccountId() != userId) {
538 SCLOCK_HILOGE("it's not currentAccountId userId=%{public}d", userId);
539 return SCREEN_FAIL;
540 }
541 if (GetSecure() == true) {
542 SCLOCK_HILOGE("The screen lock password has been set.");
543 return SCREEN_FAIL;
544 }
545 auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
546 if (preferencesUtil == nullptr) {
547 SCLOCK_HILOGE("preferencesUtil is nullptr!");
548 return E_SCREENLOCK_NULLPTR;
549 }
550 preferencesUtil->SaveBool(std::to_string(userId), disable);
551 preferencesUtil->Refresh();
552 return E_SCREENLOCK_OK;
553 }
554
SetScreenLockAuthState(int authState,int32_t userId,std::string & authToken)555 int32_t ScreenLockSystemAbility::SetScreenLockAuthState(int authState, int32_t userId, std::string &authToken)
556 {
557 SCLOCK_HILOGI("SetScreenLockAuthState authState=%{public}d ,userId=%{public}d", authState, userId);
558 auto iter = authStateInfo.find(userId);
559 if (iter != authStateInfo.end()) {
560 iter->second = authState;
561 return E_SCREENLOCK_OK;
562 }
563 authStateInfo.insert(std::make_pair(userId, authState));
564 return E_SCREENLOCK_OK;
565 }
566
GetScreenLockAuthState(int userId,int32_t & authState)567 int32_t ScreenLockSystemAbility::GetScreenLockAuthState(int userId, int32_t &authState)
568 {
569 SCLOCK_HILOGD("GetScreenLockAuthState userId=%{public}d", userId);
570 auto iter = authStateInfo.find(userId);
571 if (iter != authStateInfo.end()) {
572 authState = iter->second;
573 return E_SCREENLOCK_OK;
574 }
575 authState = static_cast<int32_t>(AuthState::UNAUTH);
576 SCLOCK_HILOGI("The authentication status is not set. userId=%{public}d", userId);
577 return E_SCREENLOCK_OK;
578 }
579
RequestStrongAuth(int reasonFlag,int32_t userId)580 int32_t ScreenLockSystemAbility::RequestStrongAuth(int reasonFlag, int32_t userId)
581 {
582 SCLOCK_HILOGI("RequestStrongAuth reasonFlag=%{public}d ,userId=%{public}d", reasonFlag, userId);
583 StrongAuthManger::GetInstance()->SetStrongAuthStat(userId, reasonFlag);
584 StrongAuthChanged(userId, reasonFlag);
585 return E_SCREENLOCK_OK;
586 }
587
GetStrongAuth(int userId,int32_t & reasonFlag)588 int32_t ScreenLockSystemAbility::GetStrongAuth(int userId, int32_t &reasonFlag)
589 {
590 reasonFlag = StrongAuthManger::GetInstance()->GetStrongAuthStat(userId);
591 SCLOCK_HILOGI("GetStrongAuth userId=%{public}d, reasonFlag=%{public}d", userId, reasonFlag);
592 return E_SCREENLOCK_OK;
593 }
594
SetScreenlocked(bool isScreenlocked)595 void ScreenLockSystemAbility::SetScreenlocked(bool isScreenlocked)
596 {
597 SCLOCK_HILOGI("ScreenLockSystemAbility SetScreenlocked state:%{public}d.", isScreenlocked);
598 stateValue_.SetScreenlocked(isScreenlocked);
599 }
600
Reset()601 void StateValue::Reset()
602 {
603 isScreenlocked_ = false;
604 screenlockEnabled_ = true;
605 currentUser_ = USER_NULL;
606 }
607
Dump(int fd,const std::vector<std::u16string> & args)608 int ScreenLockSystemAbility::Dump(int fd, const std::vector<std::u16string> &args)
609 {
610 int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
611 const int maxUid = 10000;
612 if (uid > maxUid) {
613 return 0;
614 }
615
616 std::vector<std::string> argsStr;
617 for (auto item : args) {
618 argsStr.emplace_back(Str16ToStr8(item));
619 }
620
621 DumpHelper::GetInstance().Dispatch(fd, argsStr);
622 return ERR_OK;
623 }
624
RegisterDumpCommand()625 void ScreenLockSystemAbility::RegisterDumpCommand()
626 {
627 auto cmd = std::make_shared<Command>(std::vector<std::string>{ "-all" }, "dump all screenlock information",
628 [this](const std::vector<std::string> &input, std::string &output) -> bool {
629 bool screenLocked = stateValue_.GetScreenlockedState();
630 bool screenState = stateValue_.GetScreenState();
631 int32_t offReason = stateValue_.GetOffReason();
632 int32_t interactiveState = stateValue_.GetInteractiveState();
633 string temp_screenLocked = "";
634 screenLocked ? temp_screenLocked = "true" : temp_screenLocked = "false";
635 string temp_screenState = "";
636 screenState ? temp_screenState = "true" : temp_screenState = "false";
637 output.append("\n Screenlock system state\\tValue\\t\\tDescription\n")
638 .append(" * screenLocked \t\t" + temp_screenLocked + "\t\twhether there is lock screen status\n")
639 .append(" * screenState \t\t" + temp_screenState + "\t\tscreen on / off status\n")
640 .append(" * offReason \t\t\t" + std::to_string(offReason) + "\t\tscreen failure reason\n")
641 .append(" * interactiveState \t\t" + std::to_string(interactiveState) +
642 "\t\tscreen interaction status\n");
643 return true;
644 });
645 DumpHelper::GetInstance().RegisterCommand(cmd);
646 }
647
PublishEvent(const std::string & eventAction)648 void ScreenLockSystemAbility::PublishEvent(const std::string &eventAction)
649 {
650 AAFwk::Want want;
651 want.SetAction(eventAction);
652 EventFwk::CommonEventData commonData(want);
653 bool ret = EventFwk::CommonEventManager::PublishCommonEvent(commonData);
654 SCLOCK_HILOGD("Publish event result is:%{public}d", ret);
655 }
656
LockScreenEvent(int stateResult)657 void ScreenLockSystemAbility::LockScreenEvent(int stateResult)
658 {
659 SCLOCK_HILOGD("ScreenLockSystemAbility LockScreenEvent stateResult:%{public}d", stateResult);
660 if (stateResult == ScreenChange::SCREEN_SUCC) {
661 SetScreenlocked(true);
662 }
663 std::lock_guard<std::mutex> autoLock(lockListenerMutex_);
664 if (lockVecListeners_.size()) {
665 auto callback = [this, stateResult]() {
666 std::lock_guard<std::mutex> guard(lockListenerMutex_);
667 for (size_t i = 0; i < lockVecListeners_.size(); i++) {
668 lockVecListeners_[i]->OnCallBack(stateResult);
669 }
670 lockVecListeners_.clear();
671 };
672 ffrt::submit(callback);
673 }
674 if (stateResult == ScreenChange::SCREEN_SUCC) {
675 PublishEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED);
676 }
677 }
678
UnlockScreenEvent(int stateResult)679 void ScreenLockSystemAbility::UnlockScreenEvent(int stateResult)
680 {
681 SCLOCK_HILOGD("ScreenLockSystemAbility UnlockScreenEvent stateResult:%{public}d", stateResult);
682 if (stateResult == ScreenChange::SCREEN_SUCC) {
683 SetScreenlocked(false);
684 NotifyDisplayEvent(DisplayEvent::UNLOCK);
685 PublishEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
686 }
687
688 if (stateResult != ScreenChange::SCREEN_FAIL) {
689 NotifyUnlockListener(stateResult);
690 }
691 }
692
SystemEventCallBack(const SystemEvent & systemEvent,TraceTaskId traceTaskId)693 void ScreenLockSystemAbility::SystemEventCallBack(const SystemEvent &systemEvent, TraceTaskId traceTaskId)
694 {
695 SCLOCK_HILOGI("eventType is %{public}s, params is %{public}s", systemEvent.eventType_.c_str(),
696 systemEvent.params_.c_str());
697 if (systemEventListener_ == nullptr) {
698 SCLOCK_HILOGE("systemEventListener_ is nullptr.");
699 return;
700 }
701 auto callback = [this, systemEvent, traceTaskId]() {
702 if (traceTaskId != HITRACE_BUTT) {
703 StartAsyncTrace(HITRACE_TAG_MISC, "ScreenLockSystemAbility::" + systemEvent.eventType_ + "begin callback",
704 traceTaskId);
705 }
706 std::lock_guard<std::mutex> lck(listenerMutex_);
707 systemEventListener_->OnCallBack(systemEvent);
708 if (traceTaskId != HITRACE_BUTT) {
709 FinishAsyncTrace(HITRACE_TAG_MISC, "ScreenLockSystemAbility::" + systemEvent.eventType_ + "end callback",
710 traceTaskId);
711 }
712 };
713 if (queue_ != nullptr) {
714 queue_->submit(callback);
715 }
716 }
717
NotifyUnlockListener(const int32_t screenLockResult)718 void ScreenLockSystemAbility::NotifyUnlockListener(const int32_t screenLockResult)
719 {
720 std::lock_guard<std::mutex> autoLock(unlockListenerMutex_);
721 if (unlockVecListeners_.size()) {
722 auto callback = [this, screenLockResult]() {
723 std::lock_guard<std::mutex> guard(unlockListenerMutex_);
724 for (size_t i = 0; i < unlockVecListeners_.size(); i++) {
725 unlockVecListeners_[i]->OnCallBack(screenLockResult);
726 }
727 unlockVecListeners_.clear();
728 };
729 ffrt::submit(callback);
730 }
731 }
732
NotifyDisplayEvent(DisplayEvent event)733 void ScreenLockSystemAbility::NotifyDisplayEvent(DisplayEvent event)
734 {
735 if (queue_ == nullptr) {
736 SCLOCK_HILOGE("NotifyDisplayEvent queue_ is nullptr.");
737 return;
738 }
739 auto callback = [event]() { DisplayManager::GetInstance().NotifyDisplayEvent(event); };
740 queue_->submit(callback);
741 }
742
ResetFfrtQueue()743 void ScreenLockSystemAbility::ResetFfrtQueue()
744 {
745 queue_.reset();
746 }
747
IsAppInForeground(int32_t callingPid,uint32_t callingTokenId)748 bool ScreenLockSystemAbility::IsAppInForeground(int32_t callingPid, uint32_t callingTokenId)
749 {
750 #ifdef CONFIG_FACTORY_MODE
751 return true;
752 #endif
753 FocusChangeInfo focusInfo;
754 WindowManager::GetInstance().GetFocusWindowInfo(focusInfo);
755 if (callingPid == focusInfo.pid_) {
756 return true;
757 }
758 bool isFocused = false;
759 std::string identity = IPCSkeleton::ResetCallingIdentity();
760 auto ret = AAFwk::AbilityManagerClient::GetInstance()->CheckUIExtensionIsFocused(callingTokenId, isFocused);
761 IPCSkeleton::SetCallingIdentity(identity);
762 SCLOCK_HILOGI("tokenId:%{public}d check result:%{public}d, isFocused:%{public}d", callingTokenId, ret, isFocused);
763 return ret == ERR_OK && isFocused;
764 }
765
IsSystemApp()766 bool ScreenLockSystemAbility::IsSystemApp()
767 {
768 return TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID());
769 }
770
CheckPermission(const std::string & permissionName)771 bool ScreenLockSystemAbility::CheckPermission(const std::string &permissionName)
772 {
773 AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
774 int result = AccessTokenKit::VerifyAccessToken(callerToken, permissionName);
775 if (result != PERMISSION_GRANTED) {
776 SCLOCK_HILOGE("check permission failed.");
777 return false;
778 }
779 return true;
780 }
781 } // namespace ScreenLock
782 } // namespace OHOS