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 "command.h"
32 #include "common_event_manager.h"
33 #include "display_manager.h"
34 #include "dump_helper.h"
35 #include "hitrace_meter.h"
36 #include "ipc_skeleton.h"
37 #include "iservice_registry.h"
38 #include "os_account_manager.h"
39 #include "parameter.h"
40 #include "sclock_log.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 std::lock_guard<std::mutex> lock(accountSubscriberMutex_);
209 OsAccountSubscribeInfo subscribeInfo;
210 subscribeInfo.SetOsAccountSubscribeType(OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVED);
211 accountSubscriber_ = std::make_shared<AccountSubscriber>(subscribeInfo);
212
213 int32_t ret = OsAccountManager::SubscribeOsAccount(accountSubscriber_);
214 if (ret != ERR_OK) {
215 SCLOCK_HILOGE("SubscribeOsAccount failed.[ret]:%{public}d", ret);
216 }
217 Singleton<CommeventMgr>::GetInstance().SubscribeEvent();
218
219 int userId = GetCurrentActiveOsAccountId();
220 auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
221 if (preferencesUtil == nullptr) {
222 SCLOCK_HILOGE("preferencesUtil is nullptr!");
223 return;
224 }
225 if (preferencesUtil->ObtainBool(std::to_string(userId), false)) {
226 return;
227 }
228 preferencesUtil->SaveBool(std::to_string(userId), false);
229 preferencesUtil->Refresh();
230 return;
231 }
232
OnStop()233 void ScreenLockSystemAbility::OnStop()
234 {
235 SCLOCK_HILOGI("OnStop started.");
236 if (state_ != ServiceRunningState::STATE_RUNNING) {
237 return;
238 }
239 queue_ = nullptr;
240 instance_ = nullptr;
241 state_ = ServiceRunningState::STATE_NOT_START;
242 DisplayManager::GetInstance().UnregisterDisplayPowerEventListener(displayPowerEventListener_);
243 StrongAuthManger::GetInstance()->UnRegistUserAuthSuccessEventListener();
244 StrongAuthManger::GetInstance()->DestroyAllStrongAuthTimer();
245 int ret = OsAccountManager::UnsubscribeOsAccount(accountSubscriber_);
246 if (ret != SUCCESS) {
247 SCLOCK_HILOGE("unsubscribe os account failed, code=%{public}d", ret);
248 }
249 SCLOCK_HILOGI("OnStop end.");
250 }
251
OnDisplayPowerEvent(DisplayPowerEvent event, EventStatus status)252 void ScreenLockSystemAbility::ScreenLockDisplayPowerEventListener::OnDisplayPowerEvent(DisplayPowerEvent event,
253 EventStatus status)
254 {
255 SCLOCK_HILOGI("OnDisplayPowerEvent event=%{public}d,status= %{public}d", static_cast<int>(event),
256 static_cast<int>(status));
257 switch (event) {
258 case DisplayPowerEvent::WAKE_UP:
259 instance_->OnWakeUp(status);
260 break;
261 case DisplayPowerEvent::SLEEP:
262 instance_->OnSleep(status);
263 break;
264 case DisplayPowerEvent::DISPLAY_ON:
265 instance_->OnScreenOn(status);
266 break;
267 case DisplayPowerEvent::DISPLAY_OFF:
268 instance_->OnScreenOff(status);
269 break;
270 case DisplayPowerEvent::DESKTOP_READY:
271 instance_->OnExitAnimation();
272 break;
273 default:
274 break;
275 }
276 }
277
OnScreenOff(EventStatus status)278 void ScreenLockSystemAbility::OnScreenOff(EventStatus status)
279 {
280 SystemEvent systemEvent(BEGIN_SCREEN_OFF);
281 if (status == EventStatus::BEGIN) {
282 stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_BEGIN_OFF));
283 } else if (status == EventStatus::END) {
284 stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_END_OFF));
285 systemEvent.eventType_ = END_SCREEN_OFF;
286 }
287 SystemEventCallBack(systemEvent);
288 }
289
OnScreenOn(EventStatus status)290 void ScreenLockSystemAbility::OnScreenOn(EventStatus status)
291 {
292 SystemEvent systemEvent(BEGIN_SCREEN_ON);
293 if (status == EventStatus::BEGIN) {
294 stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_BEGIN_ON));
295 } else if (status == EventStatus::END) {
296 stateValue_.SetScreenState(static_cast<int32_t>(ScreenState::SCREEN_STATE_END_ON));
297 systemEvent.eventType_ = END_SCREEN_ON;
298 }
299 SystemEventCallBack(systemEvent);
300 }
301
OnSystemReady()302 void ScreenLockSystemAbility::OnSystemReady()
303 {
304 SCLOCK_HILOGI("ScreenLockSystemAbility OnSystemReady started.");
305 bool isExitFlag = false;
306 int tryTime = 50;
307 int minTryTime = 0;
308 while (!isExitFlag && (tryTime > minTryTime)) {
309 if (systemEventListener_ != nullptr && systemReady_) {
310 SCLOCK_HILOGI("ScreenLockSystemAbility OnSystemReady started1.");
311 std::lock_guard<std::mutex> lck(listenerMutex_);
312 SystemEvent systemEvent(SYSTEM_READY);
313 systemEventListener_->OnCallBack(systemEvent);
314 isExitFlag = true;
315 } else {
316 SCLOCK_HILOGE("ScreenLockSystemAbility OnSystemReady type not found., tryTime = %{public}d", tryTime);
317 sleep(1);
318 }
319 --tryTime;
320 }
321 }
322
OnWakeUp(EventStatus status)323 void ScreenLockSystemAbility::OnWakeUp(EventStatus status)
324 {
325 SystemEvent systemEvent(BEGIN_WAKEUP);
326 if (status == EventStatus::BEGIN) {
327 stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_BEGIN_WAKEUP));
328 } else if (status == EventStatus::END) {
329 stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_END_WAKEUP));
330 systemEvent.eventType_ = END_WAKEUP;
331 }
332 SystemEventCallBack(systemEvent);
333 }
334
OnSleep(EventStatus status)335 void ScreenLockSystemAbility::OnSleep(EventStatus status)
336 {
337 SystemEvent systemEvent(BEGIN_SLEEP);
338 if (status == EventStatus::BEGIN) {
339 stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_BEGIN_SLEEP));
340 } else if (status == EventStatus::END) {
341 stateValue_.SetInteractiveState(static_cast<int32_t>(InteractiveState::INTERACTIVE_STATE_END_SLEEP));
342 systemEvent.eventType_ = END_SLEEP;
343 }
344 SystemEventCallBack(systemEvent);
345 }
346
OnExitAnimation()347 void ScreenLockSystemAbility::OnExitAnimation()
348 {
349 SystemEvent systemEvent(EXIT_ANIMATION);
350 SystemEventCallBack(systemEvent);
351 }
352
StrongAuthChanged(int32_t userId, int32_t reasonFlag)353 void ScreenLockSystemAbility::StrongAuthChanged(int32_t userId, int32_t reasonFlag)
354 {
355 SystemEvent systemEvent(STRONG_AUTH_CHANGED);
356 systemEvent.userId_ = userId;
357 systemEvent.params_ = std::to_string(reasonFlag);
358 SystemEventCallBack(systemEvent);
359 SCLOCK_HILOGI("StrongAuthChanged: userId: %{public}d, reasonFlag:%{public}d", userId, reasonFlag);
360 }
361
UnlockScreen(const sptr<ScreenLockCallbackInterface> &listener)362 int32_t ScreenLockSystemAbility::UnlockScreen(const sptr<ScreenLockCallbackInterface> &listener)
363 {
364 StartAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen begin", HITRACE_UNLOCKSCREEN);
365 return UnlockInner(listener);
366 }
367
Unlock(const sptr<ScreenLockCallbackInterface> &listener)368 int32_t ScreenLockSystemAbility::Unlock(const sptr<ScreenLockCallbackInterface> &listener)
369 {
370 StartAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen begin", HITRACE_UNLOCKSCREEN);
371 if (!IsSystemApp()) {
372 FinishAsyncTrace(HITRACE_TAG_MISC, "UnlockScreen end, Calling app is not system app", HITRACE_UNLOCKSCREEN);
373 SCLOCK_HILOGE("Calling app is not system app");
374 return E_SCREENLOCK_NOT_SYSTEM_APP;
375 }
376 return UnlockInner(listener);
377 }
378
UnlockInner(const sptr<ScreenLockCallbackInterface> &listener)379 int32_t ScreenLockSystemAbility::UnlockInner(const sptr<ScreenLockCallbackInterface> &listener)
380 {
381 if (state_ != ServiceRunningState::STATE_RUNNING) {
382 SCLOCK_HILOGI("UnlockScreen restart.");
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_HILOGI("IsScreenLocked restart.");
453 }
454 return stateValue_.GetScreenlockedState();
455 }
456
GetSecure()457 bool ScreenLockSystemAbility::GetSecure()
458 {
459 if (state_ != ServiceRunningState::STATE_RUNNING) {
460 SCLOCK_HILOGI("ScreenLockSystemAbility GetSecure restart.");
461 }
462 SCLOCK_HILOGI("ScreenLockSystemAbility GetSecure started.");
463 int callingUid = IPCSkeleton::GetCallingUid();
464 SCLOCK_HILOGD("ScreenLockSystemAbility::GetSecure callingUid=%{public}d", callingUid);
465 int userId = 0;
466 AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId);
467 if (userId == 0) {
468 AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
469 }
470 SCLOCK_HILOGD("userId=%{public}d", userId);
471 auto getInfoCallback = std::make_shared<ScreenLockGetInfoCallback>();
472 int32_t result = UserIdmClient::GetInstance().GetCredentialInfo(userId, AuthType::PIN, getInfoCallback);
473 SCLOCK_HILOGI("GetCredentialInfo AuthType::PIN result = %{public}d", result);
474 if (result == static_cast<int32_t>(ResultCode::SUCCESS)) {
475 return true;
476 }
477 return false;
478 }
479
OnSystemEvent(const sptr<ScreenLockSystemAbilityInterface> &listener)480 int32_t ScreenLockSystemAbility::OnSystemEvent(const sptr<ScreenLockSystemAbilityInterface> &listener)
481 {
482 if (!IsSystemApp()) {
483 SCLOCK_HILOGE("Calling app is not system app");
484 return E_SCREENLOCK_NOT_SYSTEM_APP;
485 }
486 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK_INNER")) {
487 return E_SCREENLOCK_NO_PERMISSION;
488 }
489 std::lock_guard<std::mutex> lck(listenerMutex_);
490 systemEventListener_ = listener;
491 stateValue_.Reset();
492 auto callback = [this]() { OnSystemReady(); };
493 if (queue_ != nullptr) {
494 queue_->submit(callback);
495 }
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 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK")) {
530 SCLOCK_HILOGE("no permission: userId=%{public}d", userId);
531 return E_SCREENLOCK_NO_PERMISSION;
532 }
533 isDisabled = preferencesUtil->ObtainBool(std::to_string(userId), false);
534 SCLOCK_HILOGI("IsScreenLockDisabled isDisabled=%{public}d", isDisabled);
535 return E_SCREENLOCK_OK;
536 }
537
SetScreenLockDisabled(bool disable, int userId)538 int32_t ScreenLockSystemAbility::SetScreenLockDisabled(bool disable, int userId)
539 {
540 SCLOCK_HILOGI("SetScreenLockDisabled disable=%{public}d ,param=%{public}d", disable, userId);
541 if (GetCurrentActiveOsAccountId() != userId) {
542 SCLOCK_HILOGE("it's not currentAccountId userId=%{public}d", userId);
543 return SCREEN_FAIL;
544 }
545 if (GetSecure() == true) {
546 SCLOCK_HILOGE("The screen lock password has been set.");
547 return SCREEN_FAIL;
548 }
549 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK")) {
550 SCLOCK_HILOGE("no permission: userId=%{public}d", userId);
551 return E_SCREENLOCK_NO_PERMISSION;
552 }
553 auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
554 if (preferencesUtil == nullptr) {
555 SCLOCK_HILOGE("preferencesUtil is nullptr!");
556 return E_SCREENLOCK_NULLPTR;
557 }
558 preferencesUtil->SaveBool(std::to_string(userId), disable);
559 preferencesUtil->Refresh();
560 return E_SCREENLOCK_OK;
561 }
562
SetScreenLockAuthState(int authState, int32_t userId, std::string &authToken)563 int32_t ScreenLockSystemAbility::SetScreenLockAuthState(int authState, int32_t userId, std::string &authToken)
564 {
565 SCLOCK_HILOGI("SetScreenLockAuthState authState=%{public}d ,userId=%{public}d", authState, userId);
566 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK")) {
567 SCLOCK_HILOGE("no permission: userId=%{public}d", userId);
568 return E_SCREENLOCK_NO_PERMISSION;
569 }
570 std::lock_guard<std::mutex> lock(authStateMutex_);
571 auto iter = authStateInfo.find(userId);
572 if (iter != authStateInfo.end()) {
573 iter->second = authState;
574 return E_SCREENLOCK_OK;
575 }
576 authStateInfo.insert(std::make_pair(userId, authState));
577 return E_SCREENLOCK_OK;
578 }
579
GetScreenLockAuthState(int userId, int32_t &authState)580 int32_t ScreenLockSystemAbility::GetScreenLockAuthState(int userId, int32_t &authState)
581 {
582 SCLOCK_HILOGD("GetScreenLockAuthState userId=%{public}d", userId);
583 std::lock_guard<std::mutex> lock(authStateMutex_);
584 auto iter = authStateInfo.find(userId);
585 if (iter != authStateInfo.end()) {
586 authState = iter->second;
587 return E_SCREENLOCK_OK;
588 }
589 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK")) {
590 SCLOCK_HILOGE("no permission: userId=%{public}d", userId);
591 return E_SCREENLOCK_NO_PERMISSION;
592 }
593 authState = static_cast<int32_t>(AuthState::UNAUTH);
594 SCLOCK_HILOGI("The authentication status is not set. userId=%{public}d", userId);
595 return E_SCREENLOCK_OK;
596 }
597
RequestStrongAuth(int reasonFlag, int32_t userId)598 int32_t ScreenLockSystemAbility::RequestStrongAuth(int reasonFlag, int32_t userId)
599 {
600 SCLOCK_HILOGI("RequestStrongAuth reasonFlag=%{public}d ,userId=%{public}d", reasonFlag, userId);
601 if (!CheckPermission("ohos.permission.ACCESS_SCREEN_LOCK")) {
602 SCLOCK_HILOGE("no permission: userId=%{public}d", userId);
603 return E_SCREENLOCK_NO_PERMISSION;
604 }
605 StrongAuthManger::GetInstance()->SetStrongAuthStat(userId, reasonFlag);
606 StrongAuthChanged(userId, reasonFlag);
607 return E_SCREENLOCK_OK;
608 }
609
GetStrongAuth(int userId, int32_t &reasonFlag)610 int32_t ScreenLockSystemAbility::GetStrongAuth(int userId, int32_t &reasonFlag)
611 {
612 reasonFlag = StrongAuthManger::GetInstance()->GetStrongAuthStat(userId);
613 SCLOCK_HILOGI("GetStrongAuth userId=%{public}d, reasonFlag=%{public}d", userId, reasonFlag);
614 return E_SCREENLOCK_OK;
615 }
616
SetScreenlocked(bool isScreenlocked)617 void ScreenLockSystemAbility::SetScreenlocked(bool isScreenlocked)
618 {
619 SCLOCK_HILOGI("ScreenLockSystemAbility SetScreenlocked state:%{public}d.", isScreenlocked);
620 stateValue_.SetScreenlocked(isScreenlocked);
621 }
622
Reset()623 void StateValue::Reset()
624 {
625 isScreenlocked_ = false;
626 screenlockEnabled_ = true;
627 currentUser_ = USER_NULL;
628 }
629
Dump(int fd, const std::vector<std::u16string> &args)630 int ScreenLockSystemAbility::Dump(int fd, const std::vector<std::u16string> &args)
631 {
632 int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
633 const int maxUid = 10000;
634 if (uid > maxUid) {
635 return 0;
636 }
637
638 std::vector<std::string> argsStr;
639 for (auto item : args) {
640 argsStr.emplace_back(Str16ToStr8(item));
641 }
642
643 DumpHelper::GetInstance().Dispatch(fd, argsStr);
644 return ERR_OK;
645 }
646
RegisterDumpCommand()647 void ScreenLockSystemAbility::RegisterDumpCommand()
648 {
649 auto cmd = std::make_shared<Command>(std::vector<std::string>{ "-all" }, "dump all screenlock information",
650 [this](const std::vector<std::string> &input, std::string &output) -> bool {
651 bool screenLocked = stateValue_.GetScreenlockedState();
652 bool screenState = stateValue_.GetScreenState();
653 int32_t offReason = stateValue_.GetOffReason();
654 int32_t interactiveState = stateValue_.GetInteractiveState();
655 string temp_screenLocked = "";
656 screenLocked ? temp_screenLocked = "true" : temp_screenLocked = "false";
657 string temp_screenState = "";
658 screenState ? temp_screenState = "true" : temp_screenState = "false";
659 output.append("\n Screenlock system state\\tValue\\t\\tDescription\n")
660 .append(" * screenLocked \t\t" + temp_screenLocked + "\t\twhether there is lock screen status\n")
661 .append(" * screenState \t\t" + temp_screenState + "\t\tscreen on / off status\n")
662 .append(" * offReason \t\t\t" + std::to_string(offReason) + "\t\tscreen failure reason\n")
663 .append(" * interactiveState \t\t" + std::to_string(interactiveState) +
664 "\t\tscreen interaction status\n");
665 return true;
666 });
667 DumpHelper::GetInstance().RegisterCommand(cmd);
668 }
669
PublishEvent(const std::string &eventAction)670 void ScreenLockSystemAbility::PublishEvent(const std::string &eventAction)
671 {
672 AAFwk::Want want;
673 want.SetAction(eventAction);
674 EventFwk::CommonEventData commonData(want);
675 bool ret = EventFwk::CommonEventManager::PublishCommonEvent(commonData);
676 SCLOCK_HILOGD("Publish event result is:%{public}d", ret);
677 }
678
LockScreenEvent(int stateResult)679 void ScreenLockSystemAbility::LockScreenEvent(int stateResult)
680 {
681 SCLOCK_HILOGD("ScreenLockSystemAbility LockScreenEvent stateResult:%{public}d", stateResult);
682 if (stateResult == ScreenChange::SCREEN_SUCC) {
683 SetScreenlocked(true);
684 }
685 std::lock_guard<std::mutex> autoLock(lockListenerMutex_);
686 if (lockVecListeners_.size()) {
687 auto callback = [this, stateResult]() {
688 std::lock_guard<std::mutex> guard(lockListenerMutex_);
689 for (size_t i = 0; i < lockVecListeners_.size(); i++) {
690 lockVecListeners_[i]->OnCallBack(stateResult);
691 }
692 lockVecListeners_.clear();
693 };
694 ffrt::submit(callback);
695 }
696 if (stateResult == ScreenChange::SCREEN_SUCC) {
697 PublishEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED);
698 }
699 }
700
UnlockScreenEvent(int stateResult)701 void ScreenLockSystemAbility::UnlockScreenEvent(int stateResult)
702 {
703 SCLOCK_HILOGD("ScreenLockSystemAbility UnlockScreenEvent stateResult:%{public}d", stateResult);
704 if (stateResult == ScreenChange::SCREEN_SUCC) {
705 SetScreenlocked(false);
706 NotifyDisplayEvent(DisplayEvent::UNLOCK);
707 PublishEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
708 }
709
710 if (stateResult != ScreenChange::SCREEN_FAIL) {
711 NotifyUnlockListener(stateResult);
712 }
713 }
714
SystemEventCallBack(const SystemEvent &systemEvent, TraceTaskId traceTaskId)715 void ScreenLockSystemAbility::SystemEventCallBack(const SystemEvent &systemEvent, TraceTaskId traceTaskId)
716 {
717 SCLOCK_HILOGI("eventType is %{public}s, params is %{public}s", systemEvent.eventType_.c_str(),
718 systemEvent.params_.c_str());
719 {
720 std::lock_guard<std::mutex> lck(listenerMutex_);
721 if (systemEventListener_ == nullptr) {
722 SCLOCK_HILOGE("systemEventListener_ is nullptr.");
723 return;
724 }
725 }
726 auto callback = [this, systemEvent, traceTaskId]() {
727 if (traceTaskId != HITRACE_BUTT) {
728 StartAsyncTrace(HITRACE_TAG_MISC, "ScreenLockSystemAbility::" + systemEvent.eventType_ + "begin callback",
729 traceTaskId);
730 }
731 std::lock_guard<std::mutex> lck(listenerMutex_);
732 systemEventListener_->OnCallBack(systemEvent);
733 if (traceTaskId != HITRACE_BUTT) {
734 FinishAsyncTrace(HITRACE_TAG_MISC, "ScreenLockSystemAbility::" + systemEvent.eventType_ + "end callback",
735 traceTaskId);
736 }
737 };
738 if (queue_ != nullptr) {
739 queue_->submit(callback);
740 }
741 }
742
NotifyUnlockListener(const int32_t screenLockResult)743 void ScreenLockSystemAbility::NotifyUnlockListener(const int32_t screenLockResult)
744 {
745 std::lock_guard<std::mutex> autoLock(unlockListenerMutex_);
746 if (unlockVecListeners_.size()) {
747 auto callback = [this, screenLockResult]() {
748 std::lock_guard<std::mutex> guard(unlockListenerMutex_);
749 for (size_t i = 0; i < unlockVecListeners_.size(); i++) {
750 unlockVecListeners_[i]->OnCallBack(screenLockResult);
751 }
752 unlockVecListeners_.clear();
753 };
754 ffrt::submit(callback);
755 }
756 }
757
NotifyDisplayEvent(DisplayEvent event)758 void ScreenLockSystemAbility::NotifyDisplayEvent(DisplayEvent event)
759 {
760 if (queue_ == nullptr) {
761 SCLOCK_HILOGE("NotifyDisplayEvent queue_ is nullptr.");
762 return;
763 }
764 auto callback = [event]() { DisplayManager::GetInstance().NotifyDisplayEvent(event); };
765 queue_->submit(callback);
766 }
767
ResetFfrtQueue()768 void ScreenLockSystemAbility::ResetFfrtQueue()
769 {
770 queue_.reset();
771 }
772
IsAppInForeground(int32_t callingPid, uint32_t callingTokenId)773 bool ScreenLockSystemAbility::IsAppInForeground(int32_t callingPid, uint32_t callingTokenId)
774 {
775 #ifdef CONFIG_FACTORY_MODE
776 return true;
777 #endif
778 FocusChangeInfo focusInfo;
779 WindowManager::GetInstance().GetFocusWindowInfo(focusInfo);
780 if (callingPid == focusInfo.pid_) {
781 return true;
782 }
783 bool isFocused = false;
784 std::string identity = IPCSkeleton::ResetCallingIdentity();
785 auto ret = AAFwk::AbilityManagerClient::GetInstance()->CheckUIExtensionIsFocused(callingTokenId, isFocused);
786 IPCSkeleton::SetCallingIdentity(identity);
787 SCLOCK_HILOGI("tokenId:%{public}d check result:%{public}d, isFocused:%{public}d", callingTokenId, ret, isFocused);
788 return ret == ERR_OK && isFocused;
789 }
790
IsSystemApp()791 bool ScreenLockSystemAbility::IsSystemApp()
792 {
793 return TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID());
794 }
795
CheckPermission(const std::string &permissionName)796 bool ScreenLockSystemAbility::CheckPermission(const std::string &permissionName)
797 {
798 AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
799 int result = AccessTokenKit::VerifyAccessToken(callerToken, permissionName);
800 if (result != PERMISSION_GRANTED) {
801 SCLOCK_HILOGE("check permission failed.");
802 return false;
803 }
804 return true;
805 }
806 } // namespace ScreenLock
807 } // namespace OHOS