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