• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "screenlock_system_ability.h"
16 
17 #include <fcntl.h>
18 #include <sys/time.h>
19 #include <unistd.h>
20 
21 #include <cerrno>
22 #include <ctime>
23 #include <functional>
24 #include <iostream>
25 #include <string>
26 
27 #include "ability_manager_client.h"
28 #include "command.h"
29 #include "core_service_client.h"
30 #include "display_manager.h"
31 #include "dump_helper.h"
32 #include "hitrace_meter.h"
33 #include "ipc_skeleton.h"
34 #include "iservice_registry.h"
35 #include "os_account_manager.h"
36 #include "parameter.h"
37 #include "sclock_log.h"
38 #include "screenlock_appinfo.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 "user_idm_client.h"
44 
45 namespace OHOS {
46 namespace ScreenLock {
47 using namespace std;
48 using namespace OHOS::HiviewDFX;
49 using namespace OHOS::Rosen;
50 using namespace OHOS::UserIam::UserAuth;
51 using namespace OHOS::Telephony;
52 REGISTER_SYSTEM_ABILITY_BY_ID(ScreenLockSystemAbility, SCREENLOCK_SERVICE_ID, true);
53 const std::int64_t INIT_INTERVAL = 5000L;
54 const std::int64_t DELAY_TIME = 1000L;
55 const std::int64_t INTERVAL_ZERO = 0L;
56 std::mutex ScreenLockSystemAbility::instanceLock_;
57 sptr<ScreenLockSystemAbility> ScreenLockSystemAbility::instance_;
58 std::shared_ptr<AppExecFwk::EventHandler> ScreenLockSystemAbility::serviceHandler_;
59 constexpr const char *THEME_SCREENLOCK_WHITEAPP = "const.theme.screenlockWhiteApp";
60 constexpr const char *THEME_SCREENLOCK_APP = "const.theme.screenlockApp";
61 constexpr const char *CANCEL_UNLOCK_OPENATION = "The user canceled the unlock openation.";
62 static constexpr const int CONFIG_LEN = 128;
63 constexpr int32_t HANDLE_OK = 0;
64 constexpr int32_t MAX_RETRY_TIMES = 20;
65 
ScreenLockSystemAbility(int32_t systemAbilityId,bool runOnCreate)66 ScreenLockSystemAbility::ScreenLockSystemAbility(int32_t systemAbilityId, bool runOnCreate)
67     : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START)
68 {
69 }
70 
~ScreenLockSystemAbility()71 ScreenLockSystemAbility::~ScreenLockSystemAbility()
72 {
73     SCLOCK_HILOGI("~ScreenLockSystemAbility state_  is %{public}d.", static_cast<int>(state_));
74 }
75 
GetInstance()76 sptr<ScreenLockSystemAbility> ScreenLockSystemAbility::GetInstance()
77 {
78     if (instance_ == nullptr) {
79         std::lock_guard<std::mutex> autoLock(instanceLock_);
80         if (instance_ == nullptr) {
81             instance_ = new ScreenLockSystemAbility(SCREENLOCK_SERVICE_ID, true);
82             SCLOCK_HILOGE("ScreenLockSystemAbility create instance.");
83         }
84     }
85     return instance_;
86 }
87 
Init()88 int32_t ScreenLockSystemAbility::Init()
89 {
90     bool ret = Publish(ScreenLockSystemAbility::GetInstance());
91     if (!ret) {
92         SCLOCK_HILOGE("Publish ScreenLockSystemAbility failed.");
93         return E_SCREENLOCK_PUBLISH_FAIL;
94     }
95     SCLOCK_HILOGD("state_ is %{public}d.", static_cast<int>(state_));
96     stateValue_.Reset();
97     SCLOCK_HILOGI("Init ScreenLockSystemAbility success.");
98     return ERR_OK;
99 }
100 
OnStart()101 void ScreenLockSystemAbility::OnStart()
102 {
103     SCLOCK_HILOGI("ScreenLockSystemAbility::Enter OnStart.");
104     if (instance_ == nullptr) {
105         instance_ = this;
106     }
107     if (state_ == ServiceRunningState::STATE_RUNNING) {
108         SCLOCK_HILOGI("ScreenLockSystemAbility is already running.");
109         return;
110     }
111     InitServiceHandler();
112     if (Init() != ERR_OK) {
113         auto callback = [=]() { Init(); };
114         serviceHandler_->PostTask(callback, INIT_INTERVAL);
115         SCLOCK_HILOGE("ScreenLockSystemAbility Init failed. Try again 5s later");
116         return;
117     }
118     AddSystemAbilityListener(DISPLAY_MANAGER_SERVICE_SA_ID);
119     RegisterDumpCommand();
120     return;
121 }
122 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)123 void ScreenLockSystemAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
124 {
125     SCLOCK_HILOGI("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
126     if (systemAbilityId == DISPLAY_MANAGER_SERVICE_SA_ID) {
127         int times = 0;
128         if (displayPowerEventListener_ == nullptr) {
129             displayPowerEventListener_ = new ScreenLockSystemAbility::ScreenLockDisplayPowerEventListener();
130         }
131         RegisterDisplayPowerEventListener(times);
132         if (flag_) {
133             state_ = ServiceRunningState::STATE_RUNNING;
134             auto callback = [=]() { OnSystemReady(); };
135             serviceHandler_->PostTask(callback, INTERVAL_ZERO);
136         }
137     }
138 }
139 
RegisterDisplayPowerEventListener(int32_t times)140 void ScreenLockSystemAbility::RegisterDisplayPowerEventListener(int32_t times)
141 {
142     times++;
143     flag_ = DisplayManager::GetInstance().RegisterDisplayPowerEventListener(displayPowerEventListener_);
144     if (flag_ == false && times <= MAX_RETRY_TIMES) {
145         SCLOCK_HILOGE("ScreenLockSystemAbility RegisterDisplayPowerEventListener failed");
146         auto callback = [this, times]() { RegisterDisplayPowerEventListener(times); };
147         serviceHandler_->PostTask(callback, DELAY_TIME);
148     }
149     SCLOCK_HILOGI("ScreenLockSystemAbility RegisterDisplayPowerEventListener end, flag_:%{public}d, times:%{public}d",
150         flag_, times);
151 }
152 
InitServiceHandler()153 void ScreenLockSystemAbility::InitServiceHandler()
154 {
155     SCLOCK_HILOGI("InitServiceHandler started.");
156     if (serviceHandler_ != nullptr) {
157         SCLOCK_HILOGI("InitServiceHandler already init.");
158         return;
159     }
160     std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create("ScreenLockSystemAbility");
161     serviceHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
162     SCLOCK_HILOGI("InitServiceHandler succeeded.");
163 }
164 
OnStop()165 void ScreenLockSystemAbility::OnStop()
166 {
167     SCLOCK_HILOGI("OnStop started.");
168     if (state_ != ServiceRunningState::STATE_RUNNING) {
169         return;
170     }
171     serviceHandler_ = nullptr;
172     instance_ = nullptr;
173     state_ = ServiceRunningState::STATE_NOT_START;
174     DisplayManager::GetInstance().UnregisterDisplayPowerEventListener(displayPowerEventListener_);
175     SCLOCK_HILOGI("OnStop end.");
176 }
177 
OnDisplayPowerEvent(DisplayPowerEvent event,EventStatus status)178 void ScreenLockSystemAbility::ScreenLockDisplayPowerEventListener::OnDisplayPowerEvent(
179     DisplayPowerEvent event, EventStatus status)
180 {
181     SCLOCK_HILOGI("OnDisplayPowerEvent event=%{public}d", static_cast<int>(event));
182     SCLOCK_HILOGI("OnDisplayPowerEvent status= %{public}d", static_cast<int>(status));
183     if (status == EventStatus::BEGIN) {
184         if (event == DisplayPowerEvent::WAKE_UP) {
185             instance_->OnBeginWakeUp();
186         } else if (event == DisplayPowerEvent::SLEEP) {
187             instance_->OnBeginSleep(0);
188         } else if (event == DisplayPowerEvent::DISPLAY_ON) {
189             instance_->OnBeginScreenOn();
190         } else if (event == DisplayPowerEvent::DISPLAY_OFF) {
191             instance_->OnBeginScreenOff();
192         } else if (event == DisplayPowerEvent::DESKTOP_READY) {
193             instance_->OnExitAnimation();
194         }
195     } else if (status == EventStatus::END) {
196         if (event == DisplayPowerEvent::WAKE_UP) {
197             instance_->OnEndWakeUp();
198         } else if (event == DisplayPowerEvent::SLEEP) {
199             instance_->OnEndSleep(0, 0);
200         } else if (event == DisplayPowerEvent::DISPLAY_ON) {
201             instance_->OnEndScreenOn();
202         } else if (event == DisplayPowerEvent::DISPLAY_OFF) {
203             instance_->OnEndScreenOff();
204         }
205     }
206 }
207 
OnBeginScreenOff()208 void ScreenLockSystemAbility::OnBeginScreenOff()
209 {
210     SCLOCK_HILOGI("ScreenLockSystemAbility OnBeginScreenOff started.");
211     stateValue_.SetScreenState(static_cast<int>(ScreenState::SCREEN_STATE_BEGIN_OFF));
212     SystemEvent systemEvent(BEGIN_SCREEN_OFF);
213     SystemEventCallBack(systemEvent);
214 }
215 
OnEndScreenOff()216 void ScreenLockSystemAbility::OnEndScreenOff()
217 {
218     SCLOCK_HILOGI("ScreenLockSystemAbility OnEndScreenOff started.");
219     stateValue_.SetScreenState(static_cast<int>(ScreenState::SCREEN_STATE_END_OFF));
220     SystemEvent systemEvent(END_SCREEN_OFF);
221     SystemEventCallBack(systemEvent);
222 }
223 
OnBeginScreenOn()224 void ScreenLockSystemAbility::OnBeginScreenOn()
225 {
226     SCLOCK_HILOGI("ScreenLockSystemAbility OnBeginScreenOn started.");
227     stateValue_.SetScreenState(static_cast<int>(ScreenState::SCREEN_STATE_BEGIN_ON));
228     SystemEvent systemEvent(BEGIN_SCREEN_ON);
229     SystemEventCallBack(systemEvent);
230 }
231 
OnSystemReady()232 void ScreenLockSystemAbility::OnSystemReady()
233 {
234     SCLOCK_HILOGI("ScreenLockSystemAbility OnSystemReady started.");
235     bool isExitFlag = false;
236     int tryTime = 20;
237     int minTryTime = 0;
238     while (!isExitFlag && (tryTime > minTryTime)) {
239         if (systemEventListener_ != nullptr) {
240             SCLOCK_HILOGI("ScreenLockSystemAbility OnSystemReady started1.");
241             std::lock_guard<std::mutex> lck(listenerMutex_);
242             SystemEvent systemEvent(SYSTEM_READY);
243             systemEventListener_->OnCallBack(systemEvent);
244             isExitFlag = true;
245         } else {
246             SCLOCK_HILOGE("ScreenLockSystemAbility OnSystemReady type not found., flag_ = %{public}d", flag_);
247             sleep(1);
248         }
249         --tryTime;
250     }
251 }
252 
OnEndScreenOn()253 void ScreenLockSystemAbility::OnEndScreenOn()
254 {
255     SCLOCK_HILOGI("ScreenLockSystemAbility OnEndScreenOn started.");
256     stateValue_.SetScreenState(static_cast<int>(ScreenState::SCREEN_STATE_END_ON));
257     SystemEvent systemEvent(END_SCREEN_ON);
258     SystemEventCallBack(systemEvent);
259 }
260 
OnBeginWakeUp()261 void ScreenLockSystemAbility::OnBeginWakeUp()
262 {
263     SCLOCK_HILOGI("ScreenLockSystemAbility OnBeginWakeUp started.");
264     stateValue_.SetInteractiveState(static_cast<int>(InteractiveState::INTERACTIVE_STATE_BEGIN_WAKEUP));
265     SystemEvent systemEvent(BEGIN_WAKEUP);
266     SystemEventCallBack(systemEvent);
267 }
268 
OnEndWakeUp()269 void ScreenLockSystemAbility::OnEndWakeUp()
270 {
271     SCLOCK_HILOGI("ScreenLockSystemAbility OnEndWakeUp started.");
272     stateValue_.SetInteractiveState(static_cast<int>(InteractiveState::INTERACTIVE_STATE_END_WAKEUP));
273     SystemEvent systemEvent(END_WAKEUP);
274     SystemEventCallBack(systemEvent);
275 }
276 
OnBeginSleep(const int why)277 void ScreenLockSystemAbility::OnBeginSleep(const int why)
278 {
279     SCLOCK_HILOGI("ScreenLockSystemAbility OnBeginSleep started.");
280     stateValue_.SetOffReason(why);
281     stateValue_.SetInteractiveState(static_cast<int>(InteractiveState::INTERACTIVE_STATE_BEGIN_SLEEP));
282     SystemEvent systemEvent(BEGIN_SLEEP, std::to_string(why));
283     SystemEventCallBack(systemEvent);
284 }
285 
OnEndSleep(const int why,const int isTriggered)286 void ScreenLockSystemAbility::OnEndSleep(const int why, const int isTriggered)
287 {
288     SCLOCK_HILOGI("ScreenLockSystemAbility OnEndSleep started.");
289     stateValue_.SetInteractiveState(static_cast<int>(InteractiveState::INTERACTIVE_STATE_END_SLEEP));
290     SystemEvent systemEvent(END_SLEEP, std::to_string(why));
291     SystemEventCallBack(systemEvent);
292 }
293 
OnChangeUser(const int newUserId)294 void ScreenLockSystemAbility::OnChangeUser(const int newUserId)
295 {
296     SCLOCK_HILOGI("ScreenLockSystemAbility OnChangeUser started. newUserId %{public}d", newUserId);
297     const int minUserId = 0;
298     const int maxUserID = 999999999;
299     if (newUserId < minUserId || newUserId >= maxUserID) {
300         SCLOCK_HILOGI("ScreenLockSystemAbility newUserId invalid.");
301         return;
302     }
303     stateValue_.SetCurrentUser(newUserId);
304     SystemEvent systemEvent(CHANGE_USER, std::to_string(newUserId));
305     SystemEventCallBack(systemEvent);
306 }
307 
OnScreenlockEnabled(bool enabled)308 void ScreenLockSystemAbility::OnScreenlockEnabled(bool enabled)
309 {
310     SCLOCK_HILOGI("ScreenLockSystemAbility OnScreenlockEnabled started.");
311     stateValue_.SetScreenlockEnabled(enabled);
312     SystemEvent systemEvent(SCREENLOCK_ENABLED, std::to_string(enabled));
313     SystemEventCallBack(systemEvent);
314 }
315 
OnExitAnimation()316 void ScreenLockSystemAbility::OnExitAnimation()
317 {
318     SCLOCK_HILOGI("ScreenLockSystemAbility OnExitAnimation started.");
319     SystemEvent systemEvent(EXIT_ANIMATION);
320     SystemEventCallBack(systemEvent);
321 }
322 
RequestUnlock(const sptr<ScreenLockSystemAbilityInterface> & listener)323 int32_t ScreenLockSystemAbility::RequestUnlock(const sptr<ScreenLockSystemAbilityInterface> &listener)
324 {
325     StartAsyncTrace(HITRACE_TAG_MISC, "ScreenLockSystemAbility::RequestUnlock begin", HITRACE_UNLOCKSCREEN);
326     if (state_ != ServiceRunningState::STATE_RUNNING) {
327         SCLOCK_HILOGI("ScreenLockSystemAbility RequestUnlock restart.");
328         OnStart();
329     }
330     SCLOCK_HILOGI("ScreenLockSystemAbility RequestUnlock started.");
331     // check whether the page of app request unlock is the focus page
332     std::lock_guard<std::mutex> guard(lock_);
333     if (!IsAppInForeground(IPCSkeleton::GetCallingTokenID())) {
334         FinishAsyncTrace(
335             HITRACE_TAG_MISC, "ScreenLockSystemAbility::RequestUnlock finish by foucus", HITRACE_UNLOCKSCREEN);
336         SCLOCK_HILOGI("ScreenLockSystemAbility RequestUnlock  Unfocused.");
337         return E_SCREENLOCK_NO_PERMISSION;
338     }
339     unlockVecListeners_.push_back(listener);
340     SystemEvent systemEvent(UNLOCKSCREEN);
341     SystemEventCallBack(systemEvent, HITRACE_UNLOCKSCREEN);
342     return E_SCREENLOCK_OK;
343 }
344 
RequestLock(const sptr<ScreenLockSystemAbilityInterface> & listener)345 int32_t ScreenLockSystemAbility::RequestLock(const sptr<ScreenLockSystemAbilityInterface> &listener)
346 {
347     SCLOCK_HILOGI("ScreenLockSystemAbility RequestLock started.");
348     if (!IsAppInForeground(IPCSkeleton::GetCallingTokenID())) {
349         SCLOCK_HILOGE("Calling app is not Unfocused.");
350         return E_SCREENLOCK_NO_PERMISSION;
351     }
352     if (!IsWhiteListApp(IPCSkeleton::GetCallingTokenID(), THEME_SCREENLOCK_WHITEAPP)) {
353         SCLOCK_HILOGE("Calling app is not whitelist app");
354         return E_SCREENLOCK_NO_PERMISSION;
355     }
356     if (IsScreenLocked()) {
357         return E_SCREENLOCK_NO_PERMISSION;
358     }
359     lock_.lock();
360     lockVecListeners_.push_back(listener);
361     lock_.unlock();
362 
363     SystemEvent systemEvent(LOCKSCREEN);
364     SystemEventCallBack(systemEvent, HITRACE_LOCKSCREEN);
365     return E_SCREENLOCK_OK;
366 }
367 
IsScreenLocked()368 bool ScreenLockSystemAbility::IsScreenLocked()
369 {
370     if (state_ != ServiceRunningState::STATE_RUNNING) {
371         SCLOCK_HILOGI("ScreenLockSystemAbility IsScreenLocked restart.");
372         OnStart();
373     }
374     SCLOCK_HILOGI("ScreenLockSystemAbility IsScreenLocked started.");
375     std::lock_guard<std::mutex> guard(lock_);
376     bool screnLockState = stateValue_.GetScreenlockedState();
377     SCLOCK_HILOGI("IsScreenLocked screnLockState = %{public}d", screnLockState);
378     return screnLockState;
379 }
380 
GetSecure()381 bool ScreenLockSystemAbility::GetSecure()
382 {
383     if (state_ != ServiceRunningState::STATE_RUNNING) {
384         SCLOCK_HILOGI("ScreenLockSystemAbility GetSecure restart.");
385         OnStart();
386     }
387     SCLOCK_HILOGI("ScreenLockSystemAbility GetSecure started.");
388     int callingUid = IPCSkeleton::GetCallingUid();
389     SCLOCK_HILOGD("ScreenLockSystemAbility::GetSecure callingUid=%{public}d", callingUid);
390     int userId = 0;
391     AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId);
392     SCLOCK_HILOGD("userId=%{public}d", userId);
393     auto getInfoCallback = std::make_shared<ScreenLockGetInfoCallback>();
394     int32_t result = UserIdmClient::GetInstance().GetCredentialInfo(userId, AuthType::PIN, getInfoCallback);
395     SCLOCK_HILOGI("GetCredentialInfo AuthType::PIN result = %{public}d", result);
396     if (result == static_cast<int32_t>(ResultCode::SUCCESS) && getInfoCallback->IsSecure()) {
397         return true;
398     }
399     result = UserIdmClient::GetInstance().GetCredentialInfo(userId, AuthType::FACE, getInfoCallback);
400     SCLOCK_HILOGI("GetCredentialInfo AuthType::FACE result = %{public}d", result);
401     if (result == static_cast<int32_t>(ResultCode::SUCCESS) && getInfoCallback->IsSecure()) {
402         return true;
403     }
404     return false;
405 }
406 
OnSystemEvent(const sptr<ScreenLockSystemAbilityInterface> & listener)407 int32_t ScreenLockSystemAbility::OnSystemEvent(const sptr<ScreenLockSystemAbilityInterface> &listener)
408 {
409     SCLOCK_HILOGI("ScreenLockSystemAbility::OnSystemEvent started.");
410     if (!IsWhiteListApp(IPCSkeleton::GetCallingTokenID(), THEME_SCREENLOCK_APP)) {
411         SCLOCK_HILOGE("Calling app is not whitelist app");
412         return E_SCREENLOCK_NO_PERMISSION;
413     }
414 
415     std::lock_guard<std::mutex> lck(listenerMutex_);
416     systemEventListener_ = listener;
417     SCLOCK_HILOGI("ScreenLockSystemAbility::OnSystemEvent end.");
418     return E_SCREENLOCK_OK;
419 }
420 
SendScreenLockEvent(const std::string & event,int param)421 int32_t ScreenLockSystemAbility::SendScreenLockEvent(const std::string &event, int param)
422 {
423     SCLOCK_HILOGI("ScreenLockSystemAbility SendScreenLockEvent started.");
424     if (!IsWhiteListApp(IPCSkeleton::GetCallingTokenID(), THEME_SCREENLOCK_APP)) {
425         SCLOCK_HILOGE("Calling app is not whitelist app");
426         return E_SCREENLOCK_NO_PERMISSION;
427     }
428     SCLOCK_HILOGD("event=%{public}s ,param=%{public}d", event.c_str(), param);
429     int stateResult = param;
430     if (event == UNLOCK_SCREEN_RESULT) {
431         UnlockScreenEvent(stateResult);
432     } else if (event == SCREEN_DRAWDONE) {
433         SetScreenlocked(true);
434         DisplayManager::GetInstance().NotifyDisplayEvent(DisplayEvent::KEYGUARD_DRAWN);
435     } else if (event == LOCK_SCREEN_RESULT) {
436         LockScreenEvent(stateResult);
437     }
438     return E_SCREENLOCK_OK;
439 }
440 
SetScreenlocked(bool isScreenlocked)441 void ScreenLockSystemAbility::SetScreenlocked(bool isScreenlocked)
442 {
443     SCLOCK_HILOGI("ScreenLockSystemAbility SetScreenlocked started.");
444     std::lock_guard<std::mutex> guard(lock_);
445     stateValue_.SetScreenlocked(isScreenlocked);
446 }
447 
Reset()448 void StateValue::Reset()
449 {
450     isScreenlocked_ = true;
451     screenlockEnabled_ = true;
452     currentUser_ = USER_NULL;
453 }
454 
OnDump()455 void ScreenLockSystemAbility::OnDump()
456 {
457     std::lock_guard<std::mutex> guard(lock_);
458     struct tm *timeNow = nullptr;
459     time_t second = time(0);
460     if (second > 0) {
461         timeNow = localtime(&second);
462         if (timeNow != nullptr) {
463             SCLOCK_HILOGI(
464                 "ScreenLockSystemAbility dump time:%{public}d-%{public}d-%{public}d %{public}d:%{public}d:%{public}d",
465                 timeNow->tm_year + startTime_, timeNow->tm_mon + extraMonth_, timeNow->tm_mday, timeNow->tm_hour,
466                 timeNow->tm_min, timeNow->tm_sec);
467         }
468     } else {
469         SCLOCK_HILOGI("ScreenLockSystemAbility dump, time(0) is nullptr");
470     }
471 }
472 
Dump(int fd,const std::vector<std::u16string> & args)473 int ScreenLockSystemAbility::Dump(int fd, const std::vector<std::u16string> &args)
474 {
475     int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
476     const int maxUid = 10000;
477     if (uid > maxUid) {
478         return 0;
479     }
480 
481     std::vector<std::string> argsStr;
482     for (auto item : args) {
483         argsStr.emplace_back(Str16ToStr8(item));
484     }
485 
486     DumpHelper::GetInstance().Dispatch(fd, argsStr);
487     return ERR_OK;
488 }
489 
RegisterDumpCommand()490 void ScreenLockSystemAbility::RegisterDumpCommand()
491 {
492     auto cmd = std::make_shared<Command>(std::vector<std::string>{ "-all" }, "dump all screenlock information",
493         [this](const std::vector<std::string> &input, std::string &output) -> bool {
494             bool screenLocked = stateValue_.GetScreenlockedState();
495             bool screenState = stateValue_.GetScreenState();
496             int32_t offReason = stateValue_.GetOffReason();
497             int32_t interactiveState = stateValue_.GetInteractiveState();
498             string temp_screenLocked = "";
499             screenLocked ? temp_screenLocked = "true" : temp_screenLocked = "false";
500             string temp_screenState = "";
501             screenState ? temp_screenState = "true" : temp_screenState = "false";
502             output.append("\n Screenlock system state\\tValue\\t\\tDescription\n")
503                 .append(" * screenLocked  \t\t" + temp_screenLocked + "\t\twhether there is lock screen status\n")
504                 .append(" * screenState  \t\t" + temp_screenState + "\t\tscreen on / off status\n")
505                 .append(" * offReason  \t\t\t" + std::to_string(offReason) + "\t\tscreen failure reason\n")
506                 .append(" * interactiveState \t\t" + std::to_string(interactiveState) +
507                         "\t\tscreen interaction status\n");
508             return true;
509         });
510     DumpHelper::GetInstance().RegisterCommand(cmd);
511 }
512 
513 #ifdef OHOS_TEST_FLAG
IsAppInForeground(uint32_t tokenId)514 bool ScreenLockSystemAbility::IsAppInForeground(uint32_t tokenId)
515 {
516     return true;
517 }
518 #else
IsAppInForeground(uint32_t tokenId)519 bool ScreenLockSystemAbility::IsAppInForeground(uint32_t tokenId)
520 {
521     using namespace OHOS::AAFwk;
522     AppInfo appInfo;
523     auto ret = ScreenLockAppInfo::GetAppInfoByToken(tokenId, appInfo);
524     if (!ret || appInfo.bundleName.empty()) {
525         SCLOCK_HILOGI("get bundle name by token failed");
526         return false;
527     }
528     auto elementName = AbilityManagerClient::GetInstance()->GetTopAbility();
529     SCLOCK_HILOGD(" TopelementName:%{public}s, elementName.GetBundleName:%{public}s",
530         elementName.GetBundleName().c_str(),  appInfo.bundleName.c_str());
531     return elementName.GetBundleName() ==  appInfo.bundleName;
532 }
533 #endif
534 
LockScreenEvent(int stateResult)535 void ScreenLockSystemAbility::LockScreenEvent(int stateResult)
536 {
537     SCLOCK_HILOGD("ScreenLockSystemAbility LockScreenEvent stateResult:%{public}d", stateResult);
538     if (stateResult == ScreenChange::SCREEN_SUCC) {
539         SetScreenlocked(true);
540         DisplayManager::GetInstance().NotifyDisplayEvent(DisplayEvent::KEYGUARD_DRAWN);
541     } else if (stateResult == ScreenChange::SCREEN_FAIL || stateResult == ScreenChange::SCREEN_CANCEL) {
542         SetScreenlocked(false);
543     }
544     lock_.lock();
545     if (lockVecListeners_.size()) {
546         auto callback = [=]() {
547             for (size_t i = 0; i < lockVecListeners_.size(); i++) {
548                 SystemEvent systemEvent("", std::to_string(stateResult));
549                 lockVecListeners_[i]->OnCallBack(systemEvent);
550             }
551             lockVecListeners_.clear();
552         };
553         serviceHandler_->PostTask(callback, INTERVAL_ZERO);
554     }
555     lock_.unlock();
556 }
557 
UnlockScreenEvent(int stateResult)558 void ScreenLockSystemAbility::UnlockScreenEvent(int stateResult)
559 {
560     SCLOCK_HILOGD("ScreenLockSystemAbility UnlockScreenEvent stateResult:%{public}d", stateResult);
561     if (stateResult == SCREEN_SUCC) {
562         SetScreenlocked(false);
563         DisplayManager::GetInstance().NotifyDisplayEvent(DisplayEvent::UNLOCK);
564     } else if (stateResult == SCREEN_FAIL || stateResult == SCREEN_CANCEL) {
565         SetScreenlocked(true);
566     }
567     std::lock_guard<std::mutex> autoLock(lock_);
568     if (unlockVecListeners_.size()) {
569         auto callback = [=]() {
570             for (size_t i = 0; i < unlockVecListeners_.size(); i++) {
571                 if (stateResult == SCREEN_CANCEL) {
572                     ErrorInfo errorInfo(JsErrorCode::ERR_CANCEL_UNLOCK, CANCEL_UNLOCK_OPENATION);
573                     unlockVecListeners_[i]->SetErrorInfo(errorInfo);
574                 }
575                 SystemEvent systemEvent("", std::to_string(stateResult));
576                 unlockVecListeners_[i]->OnCallBack(systemEvent);
577             }
578             unlockVecListeners_.clear();
579         };
580         serviceHandler_->PostTask(callback, INTERVAL_ZERO);
581     }
582 }
583 
GetScreenlockParameter(const std::string & key) const584 std::string ScreenLockSystemAbility::GetScreenlockParameter(const std::string &key) const
585 {
586     char value[CONFIG_LEN] = { 0 };
587     auto errNo = GetParameter(key.c_str(), "", value, CONFIG_LEN);
588     if (errNo > HANDLE_OK) {
589         SCLOCK_HILOGD("GetParameter success, value = %{public}.5s.", value);
590         return value;
591     }
592     SCLOCK_HILOGE("GetParameter failed, errNo = %{public}d.", errNo);
593     return "";
594 }
595 
596 #ifdef OHOS_TEST_FLAG
IsWhiteListApp(uint32_t callingTokenId,const std::string & key)597 bool ScreenLockSystemAbility::IsWhiteListApp(uint32_t callingTokenId, const std::string &key)
598 {
599     return true;
600 }
601 #else
IsWhiteListApp(uint32_t callingTokenId,const std::string & key)602 bool ScreenLockSystemAbility::IsWhiteListApp(uint32_t callingTokenId, const std::string &key)
603 {
604     std::string whiteListAppId = GetScreenlockParameter(key);
605     if (whiteListAppId.empty()) {
606         SCLOCK_HILOGE("ScreenLockSystemAbility::GetLockScreenWhiteApp  is null");
607         return false;
608     }
609     AppInfo appInfo;
610     if (!ScreenLockAppInfo::GetAppInfoByToken(callingTokenId, appInfo)) {
611         SCLOCK_HILOGE("ScreenLockSystemAbility::IsWhiteListApp GetAppInfoByToken is failed");
612         return false;
613     }
614     if (appInfo.appId.empty()) {
615         SCLOCK_HILOGE("ScreenLockSystemAbility::IsWhiteListApp appInfo.appId is null");
616         return false;
617     }
618     if (whiteListAppId != appInfo.appId) {
619         SCLOCK_HILOGE("ScreenLockSystemAbility::IsWhiteListApp calling app is not Screenlock APP");
620         return false;
621     }
622     SCLOCK_HILOGI("ScreenLockSystemAbility::IsWhiteListApp callingAppid=%{public}.5s, whiteListAppId=%{public}.5s",
623         appInfo.appId.c_str(), whiteListAppId.c_str());
624     return true;
625 }
626 #endif
627 
SystemEventCallBack(const SystemEvent & systemEvent,TraceTaskId traceTaskId)628 void ScreenLockSystemAbility::SystemEventCallBack(const SystemEvent &systemEvent, TraceTaskId traceTaskId)
629 {
630     SCLOCK_HILOGI("OnCallBack eventType is %{public}s, params is %{public}s", systemEvent.eventType_.c_str(),
631         systemEvent.params_.c_str());
632     if (systemEventListener_ == nullptr) {
633         SCLOCK_HILOGE("systemEventListener_ is nullptr.");
634         return;
635     }
636     auto callback = [=]() {
637         if (traceTaskId != HITRACE_BUTT) {
638             StartAsyncTrace(
639                 HITRACE_TAG_MISC, "ScreenLockSystemAbility::" + systemEvent.eventType_ + "begin callback", traceTaskId);
640         }
641         std::lock_guard<std::mutex> lck(listenerMutex_);
642         systemEventListener_->OnCallBack(systemEvent);
643         if (traceTaskId != HITRACE_BUTT) {
644             FinishAsyncTrace(
645                 HITRACE_TAG_MISC, "ScreenLockSystemAbility::" + systemEvent.eventType_ + "end callback", traceTaskId);
646         }
647     };
648     if (serviceHandler_ != nullptr) {
649         serviceHandler_->PostTask(callback, INTERVAL_ZERO);
650     }
651 }
652 } // namespace ScreenLock
653 } // namespace OHOS
654