1 /*
2  * Copyright (c) 2021-2024 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 
16 #include "user_controller.h"
17 
18 #include "ability_manager_service.h"
19 #include "hilog_tag_wrapper.h"
20 #include "mock_session_manager_service.h"
21 #include "os_account_manager_wrapper.h"
22 #include "scene_board_judgement.h"
23 
24 namespace OHOS {
25 namespace AAFwk {
26 using namespace OHOS::AppExecFwk;
27 namespace {
28 const int64_t USER_SWITCH_TIMEOUT = 3 * 1000; // 3s
29 }
30 
UserItem(int32_t id)31 UserItem::UserItem(int32_t id) : userId_(id)
32 {}
33 
~UserItem()34 UserItem::~UserItem() {}
35 
GetUserId()36 int32_t UserItem::GetUserId()
37 {
38     return userId_;
39 }
40 
SetState(const UserState & state)41 void UserItem::SetState(const UserState &state)
42 {
43     if (curState_ == state) {
44         return;
45     }
46     lastState_ = curState_;
47     curState_ = state;
48 }
49 
GetState()50 UserState UserItem::GetState()
51 {
52     return curState_;
53 }
54 
UserController()55 UserController::UserController()
56 {
57 }
58 
~UserController()59 UserController::~UserController()
60 {
61 }
62 
Init()63 void UserController::Init()
64 {
65     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
66     if (!handler) {
67         return;
68     }
69 
70     if (eventHandler_) {
71         return;
72     }
73     eventHandler_ = std::make_shared<UserEventHandler>(handler, shared_from_this());
74 }
75 
ClearAbilityUserItems(int32_t userId)76 void UserController::ClearAbilityUserItems(int32_t userId)
77 {
78     std::lock_guard<ffrt::mutex> guard(userLock_);
79     if (userItems_.count(userId)) {
80         userItems_.erase(userId);
81     }
82 }
83 
StartUser(int32_t userId,sptr<IUserCallback> callback)84 void UserController::StartUser(int32_t userId, sptr<IUserCallback> callback)
85 {
86     if (userId < 0 || userId == USER_ID_NO_HEAD) {
87         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUser userId is invalid:%{public}d", userId);
88         callback->OnStartUserDone(userId, INVALID_USERID_VALUE);
89         return;
90     }
91 
92     if (IsCurrentUser(userId)) {
93         TAG_LOGW(AAFwkTag::ABILITYMGR, "StartUser user is already current:%{public}d", userId);
94         callback->OnStartUserDone(userId, ERR_OK);
95         return;
96     }
97 
98     auto appScheduler = DelayedSingleton<AppScheduler>::GetInstance();
99     if (!appScheduler) {
100         TAG_LOGE(AAFwkTag::ABILITYMGR, "null appScheduler");
101         return;
102     }
103     appScheduler->SetEnableStartProcessFlagByUserId(userId, true);
104 
105     if (!IsExistOsAccount(userId)) {
106         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUser not exist such account:%{public}d", userId);
107         callback->OnStartUserDone(userId, INVALID_USERID_VALUE);
108         return;
109     }
110 
111     if (GetCurrentUserId() != USER_ID_NO_HEAD && !Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
112         // start freezing screen
113         SetFreezingNewUserId(userId);
114         DelayedSingleton<AbilityManagerService>::GetInstance()->StartFreezingScreen();
115     }
116 
117     auto oldUserId = GetCurrentUserId();
118     auto userItem = GetOrCreateUserItem(userId);
119     auto state = userItem->GetState();
120     if (state == STATE_STOPPING || state == STATE_SHUTDOWN) {
121         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUser user is stop now, userId:%{public}d", userId);
122         callback->OnStartUserDone(userId, ERR_DEAD_OBJECT);
123         return;
124     }
125 
126     SetCurrentUserId(userId);
127     // notify wms switching now
128 
129     bool needStart = false;
130     if (state == STATE_BOOTING) {
131         needStart = true;
132         // send user start msg.
133         SendSystemUserStart(userId);
134     }
135 
136     SendSystemUserCurrent(oldUserId, userId);
137     SendReportUserSwitch(oldUserId, userId, userItem);
138     SendUserSwitchTimeout(oldUserId, userId, userItem);
139 
140     if (needStart) {
141         BroadcastUserStarted(userId);
142     }
143 
144     UserBootDone(userItem);
145     MoveUserToForeground(oldUserId, userId, callback);
146 }
147 
StopUser(int32_t userId)148 int32_t UserController::StopUser(int32_t userId)
149 {
150     if (userId < 0 || userId == USER_ID_NO_HEAD || userId == USER_ID_DEFAULT) {
151         TAG_LOGE(AAFwkTag::ABILITYMGR, "userId is invalid:%{public}d", userId);
152         return -1;
153     }
154 
155     if (IsCurrentUser(userId)) {
156         TAG_LOGW(AAFwkTag::ABILITYMGR, "user is already current:%{public}d", userId);
157         return 0;
158     }
159 
160     if (!IsExistOsAccount(userId)) {
161         TAG_LOGE(AAFwkTag::ABILITYMGR, "not exist such account:%{public}d", userId);
162         return -1;
163     }
164 
165     BroadcastUserStopping(userId);
166 
167     auto appScheduler = DelayedSingleton<AppScheduler>::GetInstance();
168     if (!appScheduler) {
169         TAG_LOGE(AAFwkTag::ABILITYMGR, "appScheduler is null");
170         return -1;
171     }
172     appScheduler->KillProcessesByUserId(userId);
173 
174     auto abilityManagerService = DelayedSingleton<AbilityManagerService>::GetInstance();
175     if (!abilityManagerService) {
176         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityManagerService is null");
177         return -1;
178     }
179 
180     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
181         auto missionListWrap = abilityManagerService->GetMissionListWrap();
182         if (!missionListWrap) {
183             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListWrap is null");
184             return -1;
185         }
186         missionListWrap->RemoveUserDir(userId);
187     }
188 
189     abilityManagerService->ClearUserData(userId);
190 
191     BroadcastUserStopped(userId);
192     return 0;
193 }
194 
LogoutUser(int32_t userId)195 int32_t UserController::LogoutUser(int32_t userId)
196 {
197     if (userId < 0 || userId == USER_ID_NO_HEAD) {
198         TAG_LOGE(AAFwkTag::ABILITYMGR, "userId is invalid:%{public}d", userId);
199         return INVALID_USERID_VALUE;
200     }
201     if (!IsExistOsAccount(userId)) {
202         TAG_LOGE(AAFwkTag::ABILITYMGR, "not exist such account:%{public}d", userId);
203         return INVALID_USERID_VALUE;
204     }
205     auto abilityManagerService = DelayedSingleton<AbilityManagerService>::GetInstance();
206     if (!abilityManagerService) {
207         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityManagerService is null");
208         return -1;
209     }
210     abilityManagerService->RemoveLauncherDeathRecipient(userId);
211     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
212         TAG_LOGI(AAFwkTag::ABILITYMGR, "SceneBoard exit normally.");
213         Rosen::MockSessionManagerService::GetInstance().NotifyNotKillService();
214     }
215     auto appScheduler = DelayedSingleton<AppScheduler>::GetInstance();
216     if (!appScheduler) {
217         TAG_LOGE(AAFwkTag::ABILITYMGR, "appScheduler is null");
218         return INVALID_USERID_VALUE;
219     }
220     abilityManagerService->ClearUserData(userId);
221     appScheduler->SetEnableStartProcessFlagByUserId(userId, false);
222     if (IsCurrentUser(userId)) {
223         SetCurrentUserId(0);
224     }
225     appScheduler->KillProcessesByUserId(userId);
226     ClearAbilityUserItems(userId);
227     return 0;
228 }
229 
GetCurrentUserId()230 int32_t UserController::GetCurrentUserId()
231 {
232     std::lock_guard<ffrt::mutex> guard(userLock_);
233     return currentUserId_;
234 }
235 
GetUserItem(int32_t userId)236 std::shared_ptr<UserItem> UserController::GetUserItem(int32_t userId)
237 {
238     std::lock_guard<ffrt::mutex> guard(userLock_);
239     auto it = userItems_.find(userId);
240     if (it != userItems_.end()) {
241         return it->second;
242     }
243 
244     return nullptr;
245 }
246 
IsCurrentUser(int32_t userId)247 bool UserController::IsCurrentUser(int32_t userId)
248 {
249     int32_t oldUserId = GetCurrentUserId();
250     if (oldUserId == userId) {
251         auto userItem = GetUserItem(userId);
252         if (userItem) {
253             TAG_LOGW(AAFwkTag::ABILITYMGR, "IsCurrentUser userId is already current:%{public}d", userId);
254             return true;
255         }
256     }
257     return false;
258 }
259 
IsExistOsAccount(int32_t userId)260 bool UserController::IsExistOsAccount(int32_t userId)
261 {
262     bool isExist = false;
263     auto errCode = DelayedSingleton<OsAccountManagerWrapper>::GetInstance()->IsOsAccountExists(userId, isExist);
264     return (errCode == 0) && isExist;
265 }
266 
GetOrCreateUserItem(int32_t userId)267 std::shared_ptr<UserItem> UserController::GetOrCreateUserItem(int32_t userId)
268 {
269     std::lock_guard<ffrt::mutex> guard(userLock_);
270     auto it = userItems_.find(userId);
271     if (it != userItems_.end()) {
272         return it->second;
273     }
274 
275     auto userItem = std::make_shared<UserItem>(userId);
276     userItems_.emplace(userId, userItem);
277     return userItem;
278 }
279 
SetCurrentUserId(int32_t userId)280 void UserController::SetCurrentUserId(int32_t userId)
281 {
282     std::lock_guard<ffrt::mutex> guard(userLock_);
283     currentUserId_ = userId;
284     TAG_LOGD(AAFwkTag::ABILITYMGR, "set current userId: %{public}d", userId);
285     DelayedSingleton<AppScheduler>::GetInstance()->SetCurrentUserId(userId);
286 }
287 
MoveUserToForeground(int32_t oldUserId,int32_t newUserId,sptr<IUserCallback> callback)288 void UserController::MoveUserToForeground(int32_t oldUserId, int32_t newUserId, sptr<IUserCallback> callback)
289 {
290     auto manager = DelayedSingleton<AbilityManagerService>::GetInstance();
291     if (!manager) {
292         return;
293     }
294     manager->SwitchToUser(oldUserId, newUserId, callback);
295     BroadcastUserBackground(oldUserId);
296     BroadcastUserForeground(newUserId);
297 }
298 
UserBootDone(std::shared_ptr<UserItem> & item)299 void UserController::UserBootDone(std::shared_ptr<UserItem> &item)
300 {
301     if (!item) {
302         return;
303     }
304     int32_t userId = item->GetUserId();
305 
306     std::lock_guard<ffrt::mutex> guard(userLock_);
307     auto it = userItems_.find(userId);
308     if (it != userItems_.end()) {
309         return;
310     }
311 
312     if (item != it->second) {
313         return;
314     }
315     item->SetState(UserState::STATE_STARTED);
316     auto manager = DelayedSingleton<AbilityManagerService>::GetInstance();
317     if (!manager) {
318         return;
319     }
320     manager->UserStarted(userId);
321 }
322 
BroadcastUserStarted(int32_t userId)323 void UserController::BroadcastUserStarted(int32_t userId)
324 {
325     // broadcast event user start.
326 }
327 
BroadcastUserBackground(int32_t userId)328 void UserController::BroadcastUserBackground(int32_t userId)
329 {
330     // broadcast event user switch to bg.
331 }
332 
BroadcastUserForeground(int32_t userId)333 void UserController::BroadcastUserForeground(int32_t userId)
334 {
335     // broadcast event user switch to fg.
336 }
337 
BroadcastUserStopping(int32_t userId)338 void UserController::BroadcastUserStopping(int32_t userId)
339 {
340 }
341 
BroadcastUserStopped(int32_t userId)342 void UserController::BroadcastUserStopped(int32_t userId)
343 {
344 }
345 
SendSystemUserStart(int32_t userId)346 void UserController::SendSystemUserStart(int32_t userId)
347 {
348     auto handler = eventHandler_;
349     if (!handler) {
350         return;
351     }
352 
353     auto eventData = std::make_shared<UserEvent>();
354     eventData->newUserId = userId;
355     handler->SendEvent(EventWrap(UserEventHandler::EVENT_SYSTEM_USER_START, eventData));
356 }
357 
ProcessEvent(const EventWrap & event)358 void UserController::ProcessEvent(const EventWrap &event)
359 {
360     auto eventId = event.GetEventId();
361     auto eventData = static_cast<UserEvent*>(event.GetEventData().get());
362     if (!eventData) {
363         TAG_LOGD(AAFwkTag::ABILITYMGR, "no event data, event id: %{public}u.", eventId);
364         return;
365     }
366 
367     TAG_LOGD(AAFwkTag::ABILITYMGR, "Event id obtained: %{public}u.", eventId);
368     switch (eventId) {
369         case UserEventHandler::EVENT_SYSTEM_USER_START: {
370             HandleSystemUserStart(eventData->newUserId);
371             break;
372         }
373         case UserEventHandler::EVENT_SYSTEM_USER_CURRENT: {
374             HandleSystemUserCurrent(eventData->oldUserId, eventData->newUserId);
375             break;
376         }
377         case UserEventHandler::EVENT_REPORT_USER_SWITCH: {
378             HandleReportUserSwitch(eventData->oldUserId, eventData->newUserId, eventData->userItem);
379             break;
380         }
381         case UserEventHandler::EVENT_CONTINUE_USER_SWITCH: {
382             HandleContinueUserSwitch(eventData->oldUserId, eventData->newUserId, eventData->userItem);
383             break;
384         }
385         case UserEventHandler::EVENT_USER_SWITCH_TIMEOUT: {
386             HandleUserSwitchTimeout(eventData->oldUserId, eventData->newUserId, eventData->userItem);
387             break;
388         }
389         case UserEventHandler::EVENT_REPORT_USER_SWITCH_DONE: {
390             HandleUserSwitchDone(eventData->newUserId);
391             break;
392         }
393         default: {
394             TAG_LOGW(AAFwkTag::ABILITYMGR, "Unsupported  event.");
395             break;
396         }
397     }
398 }
399 
SendSystemUserCurrent(int32_t oldUserId,int32_t newUserId)400 void UserController::SendSystemUserCurrent(int32_t oldUserId, int32_t newUserId)
401 {
402     auto handler = eventHandler_;
403     if (!handler) {
404         return;
405     }
406 
407     auto eventData = std::make_shared<UserEvent>();
408     eventData->oldUserId = oldUserId;
409     eventData->newUserId = newUserId;
410     handler->SendEvent(EventWrap(UserEventHandler::EVENT_SYSTEM_USER_CURRENT, eventData));
411 }
412 
SendReportUserSwitch(int32_t oldUserId,int32_t newUserId,std::shared_ptr<UserItem> & usrItem)413 void UserController::SendReportUserSwitch(int32_t oldUserId, int32_t newUserId,
414     std::shared_ptr<UserItem> &usrItem)
415 {
416     auto handler = eventHandler_;
417     if (!handler) {
418         return;
419     }
420 
421     auto eventData = std::make_shared<UserEvent>();
422     eventData->oldUserId = oldUserId;
423     eventData->newUserId = newUserId;
424     eventData->userItem = usrItem;
425     handler->SendEvent(EventWrap(UserEventHandler::EVENT_REPORT_USER_SWITCH, eventData));
426 }
427 
SendUserSwitchTimeout(int32_t oldUserId,int32_t newUserId,std::shared_ptr<UserItem> & usrItem)428 void UserController::SendUserSwitchTimeout(int32_t oldUserId, int32_t newUserId,
429     std::shared_ptr<UserItem> &usrItem)
430 {
431     auto handler = eventHandler_;
432     if (!handler) {
433         return;
434     }
435 
436     auto eventData = std::make_shared<UserEvent>();
437     eventData->oldUserId = oldUserId;
438     eventData->newUserId = newUserId;
439     eventData->userItem = usrItem;
440     handler->SendEvent(EventWrap(UserEventHandler::EVENT_USER_SWITCH_TIMEOUT,
441         eventData), USER_SWITCH_TIMEOUT);
442 }
443 
SendContinueUserSwitch(int32_t oldUserId,int32_t newUserId,std::shared_ptr<UserItem> & usrItem)444 void UserController::SendContinueUserSwitch(int32_t oldUserId, int32_t newUserId,
445     std::shared_ptr<UserItem> &usrItem)
446 {
447     auto handler = eventHandler_;
448     if (!handler) {
449         return;
450     }
451 
452     auto eventData = std::make_shared<UserEvent>();
453     eventData->oldUserId = oldUserId;
454     eventData->newUserId = newUserId;
455     eventData->userItem = usrItem;
456     handler->SendEvent(EventWrap(UserEventHandler::EVENT_CONTINUE_USER_SWITCH, eventData));
457 }
458 
SendUserSwitchDone(int32_t userId)459 void UserController::SendUserSwitchDone(int32_t userId)
460 {
461     auto handler = eventHandler_;
462     if (!handler) {
463         return;
464     }
465 
466     auto eventData = std::make_shared<UserEvent>();
467     eventData->newUserId = userId;
468     handler->SendEvent(EventWrap(UserEventHandler::EVENT_REPORT_USER_SWITCH_DONE,
469         eventData));
470 }
471 
HandleSystemUserStart(int32_t userId)472 void UserController::HandleSystemUserStart(int32_t userId)
473 {
474     // notify system mgr user start.
475 }
476 
HandleSystemUserCurrent(int32_t oldUserId,int32_t newUserId)477 void UserController::HandleSystemUserCurrent(int32_t oldUserId, int32_t newUserId)
478 {
479     // notify system mgr user switch to new.
480 }
481 
HandleReportUserSwitch(int32_t oldUserId,int32_t newUserId,std::shared_ptr<UserItem> & usrItem)482 void UserController::HandleReportUserSwitch(int32_t oldUserId, int32_t newUserId,
483     std::shared_ptr<UserItem> &usrItem)
484 {
485     // notify user switch observers, not support yet.
486 }
487 
HandleUserSwitchTimeout(int32_t oldUserId,int32_t newUserId,std::shared_ptr<UserItem> & usrItem)488 void UserController::HandleUserSwitchTimeout(int32_t oldUserId, int32_t newUserId,
489     std::shared_ptr<UserItem> &usrItem)
490 {
491     // other observers
492     SendContinueUserSwitch(oldUserId, newUserId, usrItem);
493 }
494 
HandleContinueUserSwitch(int32_t oldUserId,int32_t newUserId,std::shared_ptr<UserItem> & usrItem)495 void UserController::HandleContinueUserSwitch(int32_t oldUserId, int32_t newUserId,
496     std::shared_ptr<UserItem> &usrItem)
497 {
498     auto manager = DelayedSingleton<AbilityManagerService>::GetInstance();
499     if (manager && !Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
500         manager->StopFreezingScreen();
501     }
502     SendUserSwitchDone(newUserId);
503 }
504 
HandleUserSwitchDone(int32_t userId)505 void UserController::HandleUserSwitchDone(int32_t userId)
506 {
507     // notify wms switching done.
508     // notify user switch observers.
509 }
510 
GetFreezingNewUserId() const511 int32_t UserController::GetFreezingNewUserId() const
512 {
513     return freezingNewUserId_;
514 }
515 
SetFreezingNewUserId(int32_t userId)516 void UserController::SetFreezingNewUserId(int32_t userId)
517 {
518     freezingNewUserId_ = userId;
519 }
520 }
521 }
522