• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 
16 #include "form_mgr_service.h"
17 
18 #include "common_event_manager.h"
19 #include "common_event_support.h"
20 #include "form_ams_helper.h"
21 #include "form_bms_helper.h"
22 #include "form_constants.h"
23 #include "form_db_cache.h"
24 #include "form_event_handler.h"
25 #include "form_info_mgr.h"
26 #include "form_mgr_adapter.h"
27 #include "form_mgr_errors.h"
28 #include "form_share_mgr.h"
29 #include "form_task_mgr.h"
30 #include "form_timer_mgr.h"
31 #include "form_util.h"
32 #include "hilog_wrapper.h"
33 #include "in_process_call_wrapper.h"
34 #include "ipc_skeleton.h"
35 #include "iservice_registry.h"
36 #include "permission_verification.h"
37 #include "system_ability_definition.h"
38 #include "event_report.h"
39 #include "hisysevent.h"
40 #include "xcollie/watchdog.h"
41 
42 namespace OHOS {
43 namespace AppExecFwk {
44 namespace {
45 const int32_t MAIN_USER_ID = 100;
46 }
47 using namespace std::chrono;
48 
49 const bool REGISTER_RESULT =
50     SystemAbility::MakeAndRegisterAbility(DelayedSingleton<FormMgrService>::GetInstance().get());
51 
52 const std::string NAME_FORM_MGR_SERVICE = "FormMgrService";
53 
54 constexpr int32_t FORM_DUMP_ARGC_MAX = 2;
55 
56 const std::string FORM_DUMP_HELP = "options list:\n"
57     "  -h, --help                               list available commands\n"
58     "  -s, --storage                            query form storage info\n"
59     "  -n  <bundle-name>                        query form info by a bundle name\n"
60     "  -i  <form-id>                            query form info by a form ID\n";
61 
62 const std::map<std::string, FormMgrService::DumpKey> FormMgrService::dumpKeyMap_ = {
63     {"-h", FormMgrService::DumpKey::KEY_DUMP_HELP},
64     {"--help", FormMgrService::DumpKey::KEY_DUMP_HELP},
65     {"-s", FormMgrService::DumpKey::KEY_DUMP_STORAGE},
66     {"--storage", FormMgrService::DumpKey::KEY_DUMP_STORAGE},
67     {"-n", FormMgrService::DumpKey::KEY_DUMP_BY_BUNDLE_NAME},
68     {"-i", FormMgrService::DumpKey::KEY_DUMP_BY_FORM_ID},
69 };
70 
FormMgrService()71 FormMgrService::FormMgrService()
72     : SystemAbility(FORM_MGR_SERVICE_ID, true),
73       state_(ServiceRunningState::STATE_NOT_START),
74       runner_(nullptr),
75       handler_(nullptr)
76 {
77     DumpInit();
78 }
79 
~FormMgrService()80 FormMgrService::~FormMgrService()
81 {
82     if (formSysEventReceiver_ != nullptr) {
83         EventFwk::CommonEventManager::UnSubscribeCommonEvent(formSysEventReceiver_);
84         formSysEventReceiver_ = nullptr;
85         sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
86         if (iBundleMgr == nullptr) {
87             return;
88         }
89         if (!iBundleMgr->UnregisterBundleEventCallback(formBundleEventCallback_)) {
90             HILOG_ERROR("%{public}s fail, UnregisterBundleEventCallback failed", __func__);
91         }
92         formBundleEventCallback_ = nullptr;
93     }
94 }
95 
IsReady() const96 bool FormMgrService::IsReady() const
97 {
98     if (state_ != ServiceRunningState::STATE_RUNNING) {
99         return false;
100     }
101     if (!handler_) {
102         HILOG_ERROR("%{public}s fail, handler is null", __func__);
103         return false;
104     }
105     int32_t userId = FormUtil::GetCurrentAccountId();
106     if (userId == Constants::ANY_USERID) {
107         HILOG_ERROR("%{public}s fail, account is empty", __func__);
108         return false;
109     }
110     return true;
111 }
112 
113 /**
114 * @brief Check form manager service ready.
115 * @return Return true if form manager service Ready; return false otherwise.
116 */
117 
CheckFMSReady()118 bool FormMgrService::CheckFMSReady()
119 {
120     return IsReady();
121 }
122 
123 /**
124  * @brief Add form with want, send want to form manager service.
125  * @param formId The Id of the forms to add.
126  * @param want The want of the form to add.
127  * @param callerToken Caller ability token.
128  * @param formInfo Form info.
129  * @return Returns ERR_OK on success, others on failure.
130  */
AddForm(const int64_t formId,const Want & want,const sptr<IRemoteObject> & callerToken,FormJsInfo & formInfo)131 int FormMgrService::AddForm(const int64_t formId, const Want &want,
132     const sptr<IRemoteObject> &callerToken, FormJsInfo &formInfo)
133 {
134     ErrCode ret = CheckFormPermission();
135     AAFwk::EventInfo eventInfo;
136     eventInfo.userId = formId;
137     eventInfo.bundleName = want.GetElement().GetBundleName();
138     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
139     eventInfo.abilityName = want.GetElement().GetAbilityName();
140     AAFwk::EventReport::SendFormEvent(AAFwk::EventName::ADD_FORM, HiSysEventType::BEHAVIOR, eventInfo);
141     if (ret != ERR_OK) {
142         HILOG_ERROR("%{public}s fail, add form permission denied", __func__);
143         return ret;
144     }
145     return FormMgrAdapter::GetInstance().AddForm(formId, want, callerToken, formInfo);
146 }
147 
148 /**
149  * @brief Delete forms with formIds, send formIds to form manager service.
150  * @param formId The Id of the forms to delete.
151  * @param callerToken Caller ability token.
152  * @return Returns ERR_OK on success, others on failure.
153  */
DeleteForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)154 int FormMgrService::DeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
155 {
156     ErrCode ret = CheckFormPermission();
157     if (ret != ERR_OK) {
158         HILOG_ERROR("%{public}s fail, delete form permission denied", __func__);
159         return ret;
160     }
161     AAFwk::EventInfo eventInfo;
162     eventInfo.userId = formId;
163     AAFwk::EventReport::SendFormEvent(AAFwk::EventName::DELETE_FORM, HiSysEventType::BEHAVIOR, eventInfo);
164 
165     return FormMgrAdapter::GetInstance().DeleteForm(formId, callerToken);
166 }
167 
168 /**
169  * @brief Stop rendering form.
170  * @param formId The Id of the forms to delete.
171  * @param compId The compId of the forms to delete.
172  * @return Returns ERR_OK on success, others on failure.
173  */
StopRenderingForm(const int64_t formId,const std::string & compId)174 int FormMgrService::StopRenderingForm(const int64_t formId, const std::string &compId)
175 {
176     ErrCode ret = CheckFormPermission();
177     if (ret != ERR_OK) {
178         HILOG_ERROR("%{public}s fail, delete form permission denied", __func__);
179         return ret;
180     }
181 
182     return FormMgrAdapter::GetInstance().StopRenderingForm(formId, compId);
183 }
184 
185 
186 
187 /**
188  * @brief Release forms with formIds, send formIds to form manager service.
189  * @param formId The Id of the forms to release.
190  * @param callerToken Caller ability token.
191  * @param delCache Delete Cache or not.
192  * @return Returns ERR_OK on success, others on failure.
193  */
ReleaseForm(const int64_t formId,const sptr<IRemoteObject> & callerToken,const bool delCache)194 int FormMgrService::ReleaseForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const bool delCache)
195 {
196     ErrCode ret = CheckFormPermission();
197     if (ret != ERR_OK) {
198         HILOG_ERROR("%{public}s fail, release form permission denied", __func__);
199         return ret;
200     }
201     AAFwk::EventInfo eventInfo;
202     eventInfo.userId = formId;
203     AAFwk::EventReport::SendFormEvent(AAFwk::EventName::RELEASE_FORM, HiSysEventType::BEHAVIOR, eventInfo);
204 
205     return FormMgrAdapter::GetInstance().ReleaseForm(formId, callerToken, delCache);
206 }
207 
208 /**
209  * @brief Update form with formId, send formId to form manager service.
210  * @param formId The Id of the form to update.
211  * @param formBindingData Form binding data.
212  * @return Returns ERR_OK on success, others on failure.
213  */
UpdateForm(const int64_t formId,const FormProviderData & formBindingData)214 int FormMgrService::UpdateForm(const int64_t formId, const FormProviderData &formBindingData)
215 {
216     std::string callerBundleName;
217     auto ret = FormBmsHelper::GetInstance().GetCallerBundleName(callerBundleName);
218     if (ret != ERR_OK) {
219         HILOG_ERROR("%{public}s fail, get caller bundle name failed", __func__);
220         return ret;
221     }
222     return FormMgrAdapter::GetInstance().UpdateForm(formId, callerBundleName, formBindingData);
223 }
224 
225 /**
226  * @brief Request form with formId and want, send formId and want to form manager service.
227  * @param formId The Id of the form to update.
228  * @param callerToken Caller ability token.
229  * @param want The want of the form to add.
230  * @return Returns ERR_OK on success, others on failure.
231  */
RequestForm(const int64_t formId,const sptr<IRemoteObject> & callerToken,const Want & want)232 int FormMgrService::RequestForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const Want &want)
233 {
234     HILOG_INFO("%{public}s called.", __func__);
235 
236     ErrCode ret = CheckFormPermission();
237     if (ret != ERR_OK) {
238         HILOG_ERROR("%{public}s fail, request form permission denied", __func__);
239         return ret;
240     }
241     AAFwk::EventInfo eventInfo;
242     eventInfo.userId = formId;
243     eventInfo.bundleName = want.GetElement().GetBundleName();
244     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
245     eventInfo.abilityName = want.GetElement().GetAbilityName();
246     AAFwk::EventReport::SendFormEvent(AAFwk::EventName::REQUEST_FORM, HiSysEventType::BEHAVIOR, eventInfo);
247 
248     return FormMgrAdapter::GetInstance().RequestForm(formId, callerToken, want);
249 }
250 
251 /**
252  * @brief set next refresh time.
253  * @param formId The id of the form.
254  * @param nextTime next refresh time.
255  * @return Returns ERR_OK on success, others on failure.
256  */
SetNextRefreshTime(const int64_t formId,const int64_t nextTime)257 int FormMgrService::SetNextRefreshTime(const int64_t formId, const int64_t nextTime)
258 {
259     HILOG_INFO("%{public}s called.", __func__);
260     AAFwk::EventInfo eventInfo;
261     eventInfo.userId = formId;
262     AAFwk::EventReport::SendFormEvent(
263         AAFwk::EventName::SET_NEXT_REFRESH_TIME_FORM, HiSysEventType::BEHAVIOR, eventInfo);
264 
265     return FormMgrAdapter::GetInstance().SetNextRefreshTime(formId, nextTime);
266 }
267 
RequestPublishForm(Want & want,bool withFormBindingData,std::unique_ptr<FormProviderData> & formBindingData,int64_t & formId)268 ErrCode FormMgrService::RequestPublishForm(Want &want, bool withFormBindingData,
269     std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId)
270 {
271     HILOG_INFO("%{public}s called.", __func__);
272 
273     return FormMgrAdapter::GetInstance().RequestPublishForm(want, withFormBindingData, formBindingData, formId);
274 }
275 
276 /**
277  * @brief Form visible/invisible notify, send formIds to form manager service.
278  * @param formIds The Id list of the forms to notify.
279  * @param callerToken Caller ability token.
280  * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE.
281  * @return Returns ERR_OK on success, others on failure.
282  */
NotifyWhetherVisibleForms(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,const int32_t formVisibleType)283 int FormMgrService::NotifyWhetherVisibleForms(const std::vector<int64_t> &formIds,
284     const sptr<IRemoteObject> &callerToken, const int32_t formVisibleType)
285 {
286     ErrCode ret = CheckFormPermission();
287     if (ret != ERR_OK) {
288         HILOG_ERROR("%{public}s fail, event notify visible permission denied", __func__);
289         return ret;
290     }
291 
292     return FormMgrAdapter::GetInstance().NotifyWhetherVisibleForms(formIds, callerToken, formVisibleType);
293 }
294 
295 /**
296  * @brief temp form to normal form.
297  * @param formId The Id of the form.
298  * @param callerToken Caller ability token.
299  * @return Returns ERR_OK on success, others on failure.
300  */
CastTempForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)301 int FormMgrService::CastTempForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
302 {
303     ErrCode ret = CheckFormPermission();
304     if (ret != ERR_OK) {
305         HILOG_ERROR("%{public}s fail, cast temp form permission denied", __func__);
306         return ret;
307     }
308     AAFwk::EventInfo eventInfo;
309     eventInfo.userId = formId;
310     AAFwk::EventReport::SendFormEvent(AAFwk::EventName::CASTTEMP_FORM, HiSysEventType::BEHAVIOR, eventInfo);
311 
312     return FormMgrAdapter::GetInstance().CastTempForm(formId, callerToken);
313 }
314 
315 /**
316  * @brief lifecycle update.
317  * @param formIds formIds of host client.
318  * @param callerToken Caller ability token.
319  * @param updateType update type,enable or disable.
320  * @return Returns true on success, false on failure.
321  */
LifecycleUpdate(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,bool updateType)322 int FormMgrService::LifecycleUpdate(const std::vector<int64_t> &formIds,
323     const sptr<IRemoteObject> &callerToken, bool updateType)
324 {
325     HILOG_INFO("lifecycleUpdate.");
326 
327     ErrCode ret = CheckFormPermission();
328     if (ret != ERR_OK) {
329         HILOG_ERROR("%{public}s fail, delete form permission denied", __func__);
330         return ret;
331     }
332 
333     if (updateType) {
334         return FormMgrAdapter::GetInstance().EnableUpdateForm(formIds, callerToken);
335     } else {
336         return FormMgrAdapter::GetInstance().DisableUpdateForm(formIds, callerToken);
337     }
338 }
339 /**
340  * @brief Dump all of form storage infos.
341  * @param formInfos All of form storage infos.
342  * @return Returns ERR_OK on success, others on failure.
343  */
DumpStorageFormInfos(std::string & formInfos)344 int FormMgrService::DumpStorageFormInfos(std::string &formInfos)
345 {
346     return FormMgrAdapter::GetInstance().DumpStorageFormInfos(formInfos);
347 }
348 /**
349  * @brief Dump form info by a bundle name.
350  * @param bundleName The bundle name of form provider.
351  * @param formInfos Form infos.
352  * @return Returns ERR_OK on success, others on failure.
353  */
DumpFormInfoByBundleName(const std::string & bundleName,std::string & formInfos)354 int FormMgrService::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos)
355 {
356     return FormMgrAdapter::GetInstance().DumpFormInfoByBundleName(bundleName, formInfos);
357 }
358 /**
359  * @brief Dump form info by a bundle name.
360  * @param formId The id of the form.
361  * @param formInfo Form info.
362  * @return Returns ERR_OK on success, others on failure.
363  */
DumpFormInfoByFormId(const std::int64_t formId,std::string & formInfo)364 int FormMgrService::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo)
365 {
366     return FormMgrAdapter::GetInstance().DumpFormInfoByFormId(formId, formInfo);
367 }
368 /**
369  * @brief Dump form timer by form id.
370  * @param formId The id of the form.
371  * @param formInfo Form info.
372  * @return Returns ERR_OK on success, others on failure.
373  */
DumpFormTimerByFormId(const std::int64_t formId,std::string & isTimingService)374 int FormMgrService::DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService)
375 {
376     return FormMgrAdapter::GetInstance().DumpFormTimerByFormId(formId, isTimingService);
377 }
378 /**
379  * @brief Process js message event.
380  * @param formId Indicates the unique id of form.
381  * @param want information passed to supplier.
382  * @param callerToken Caller ability token.
383  * @return Returns true if execute success, false otherwise.
384  */
MessageEvent(const int64_t formId,const Want & want,const sptr<IRemoteObject> & callerToken)385 int FormMgrService::MessageEvent(const int64_t formId, const Want &want, const sptr<IRemoteObject> &callerToken)
386 {
387     HILOG_INFO("%{public}s called.", __func__);
388     ErrCode ret = CheckFormPermission();
389     if (ret != ERR_OK) {
390         HILOG_ERROR("%{public}s fail, request form permission denied", __func__);
391         return ret;
392     }
393     AAFwk::EventInfo eventInfo;
394     eventInfo.bundleName = want.GetElement().GetBundleName();
395     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
396     eventInfo.abilityName = want.GetElement().GetAbilityName();
397     AAFwk::EventReport::SendFormEvent(AAFwk::EventName::MESSAGE_EVENT_FORM, HiSysEventType::BEHAVIOR, eventInfo);
398     return FormMgrAdapter::GetInstance().MessageEvent(formId, want, callerToken);
399 }
400 
401 /**
402  * @brief Process js router event.
403  * @param formId Indicates the unique id of form.
404  * @param want the want of the ability to start.
405  * @param callerToken Caller ability token.
406  * @return Returns true if execute success, false otherwise.
407  */
RouterEvent(const int64_t formId,Want & want,const sptr<IRemoteObject> & callerToken)408 int FormMgrService::RouterEvent(const int64_t formId, Want &want, const sptr<IRemoteObject> &callerToken)
409 {
410     HILOG_INFO("%{public}s called.", __func__);
411     ErrCode ret = CheckFormPermission();
412     if (ret != ERR_OK) {
413         HILOG_ERROR("%{public}s fail, request form permission denied", __func__);
414         return ret;
415     }
416     AAFwk::EventInfo eventInfo;
417     eventInfo.userId = formId;
418     eventInfo.bundleName = want.GetElement().GetBundleName();
419     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
420     eventInfo.abilityName = want.GetElement().GetAbilityName();
421     AAFwk::EventReport::SendFormEvent(AAFwk::EventName::ROUTE_EVENT_FORM, HiSysEventType::BEHAVIOR, eventInfo);
422     return FormMgrAdapter::GetInstance().RouterEvent(formId, want, callerToken);
423 }
424 
425 /**
426  * @brief Process Background event.
427  * @param formId Indicates the unique id of form.
428  * @param want the want of the ability to start.
429  * @param callerToken Caller ability token.
430  * @return Returns true if execute success, false otherwise.
431  */
BackgroundEvent(const int64_t formId,Want & want,const sptr<IRemoteObject> & callerToken)432 int FormMgrService::BackgroundEvent(const int64_t formId, Want &want, const sptr<IRemoteObject> &callerToken)
433 {
434     HILOG_INFO("%{public}s called.", __func__);
435     ErrCode ret = CheckFormPermission();
436     if (ret != ERR_OK) {
437         HILOG_ERROR("%{public}s fail, request form permission denied", __func__);
438         return ret;
439     }
440     AAFwk::EventInfo eventInfo;
441     eventInfo.userId = formId;
442     eventInfo.bundleName = want.GetElement().GetBundleName();
443     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
444     eventInfo.abilityName = want.GetElement().GetAbilityName();
445     AAFwk::EventReport::SendFormEvent(AAFwk::EventName::BACKGROUND_EVENT_FORM, HiSysEventType::BEHAVIOR, eventInfo);
446     return FormMgrAdapter::GetInstance().BackgroundEvent(formId, want, callerToken);
447 }
448 
449 /**
450  * @brief Start event for the form manager service.
451  */
OnStart()452 void FormMgrService::OnStart()
453 {
454     if (state_ == ServiceRunningState::STATE_RUNNING) {
455         HILOG_WARN("%{public}s fail, Failed to start service since it's already running", __func__);
456         return;
457     }
458 
459     HILOG_INFO("Form Mgr Service start...");
460     ErrCode errCode = Init();
461     if (errCode != ERR_OK) {
462         HILOG_ERROR("%{public}s fail, Failed to init, errCode: %{public}08x", __func__, errCode);
463         return;
464     }
465 
466     state_ = ServiceRunningState::STATE_RUNNING;
467     HILOG_INFO("Form Mgr Service start success.");
468 }
469 /**
470  * @brief Stop event for the form manager service.
471  */
OnStop()472 void FormMgrService::OnStop()
473 {
474     HILOG_INFO("stop service");
475 
476     state_ = ServiceRunningState::STATE_NOT_START;
477 
478     if (handler_) {
479         handler_.reset();
480     }
481 
482     if (runner_) {
483         runner_.reset();
484     }
485 }
486 /**
487  * @brief initialization of form manager service.
488  */
Init()489 ErrCode FormMgrService::Init()
490 {
491     HILOG_INFO("FormMgrService Init start");
492     runner_ = EventRunner::Create(NAME_FORM_MGR_SERVICE);
493     if (runner_ == nullptr) {
494         HILOG_ERROR("%{public}s fail, Failed to init due to create runner error", __func__);
495         return ERR_INVALID_OPERATION;
496     }
497     handler_ = std::make_shared<FormEventHandler>(runner_);
498     if (handler_ == nullptr) {
499         HILOG_ERROR("%{public}s fail, Failed to init due to create handler error", __func__);
500         return ERR_INVALID_OPERATION;
501     }
502     FormTaskMgr::GetInstance().SetEventHandler(handler_);
503     FormAmsHelper::GetInstance().SetEventHandler(handler_);
504     /* Publish service maybe failed, so we need call this function at the last,
505      * so it can't affect the TDD test program */
506     bool ret = Publish(DelayedSingleton<FormMgrService>::GetInstance().get());
507     if (!ret) {
508         HILOG_ERROR("%{public}s fail, FormMgrService::Init Publish failed!", __func__);
509         return ERR_INVALID_OPERATION;
510     }
511 
512     std::string threadName = NAME_FORM_MGR_SERVICE + "(" + std::to_string(runner_->GetThreadId()) + ")";
513     if (HiviewDFX::Watchdog::GetInstance().AddThread(threadName, handler_) != 0) {
514         HILOG_ERROR("HiviewDFX::Watchdog::GetInstance AddThread Fail");
515     }
516 
517     if (formSysEventReceiver_ == nullptr) {
518         EventFwk::MatchingSkills matchingSkills;
519         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_UPDATED);
520         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED);
521         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED);
522         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BUNDLE_SCAN_FINISHED);
523         // init TimerReceiver
524         EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
525         formSysEventReceiver_ = std::make_shared<FormSysEventReceiver>(subscribeInfo);
526         formSysEventReceiver_->SetEventHandler(handler_);
527         EventFwk::CommonEventManager::SubscribeCommonEvent(formSysEventReceiver_);
528     }
529     FormInfoMgr::GetInstance().Start();
530     FormInfoMgr::GetInstance().ReloadFormInfos(MAIN_USER_ID);
531     FormDbCache::GetInstance().Start();
532     FormTimerMgr::GetInstance(); // Init FormTimerMgr
533     // Register formbundleEventCallback to receive hap updates
534     formBundleEventCallback_ = new (std::nothrow) FormBundleEventCallback(handler_);
535     if (formBundleEventCallback_ == nullptr) {
536         HILOG_ERROR("%{public}s fail, allocate formBundleEventCallback_ failed!", __func__);
537         return ERR_APPEXECFWK_FORM_COMMON_CODE;
538     }
539     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
540     if (iBundleMgr == nullptr) {
541         return ERR_APPEXECFWK_FORM_COMMON_CODE;
542     }
543     bool re = iBundleMgr->RegisterBundleEventCallback(formBundleEventCallback_);
544     if (!re) {
545         HILOG_ERROR("%{public}s fail, RegisterBundleEventCallback failed!", __func__);
546         return ERR_APPEXECFWK_FORM_COMMON_CODE;
547     }
548     HILOG_INFO("init success");
549     return ERR_OK;
550 }
551 
CheckFormPermission()552 ErrCode FormMgrService::CheckFormPermission()
553 {
554     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
555     if (isSaCall) {
556         return ERR_OK;
557     }
558 
559     // get IBundleMgr
560     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
561     if (iBundleMgr == nullptr) {
562         HILOG_ERROR("%{public}s error, failed to get IBundleMgr.", __func__);
563         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
564     }
565 
566     // check if system app
567     auto isSystemApp = iBundleMgr->CheckIsSystemAppByUid(IPCSkeleton::GetCallingUid());
568     if (!isSystemApp) {
569         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
570     }
571 
572     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
573         AppExecFwk::Constants::PERMISSION_REQUIRE_FORM);
574     if (!isCallingPerm) {
575         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
576     }
577     HILOG_ERROR("Permission verification ok!");
578     return ERR_OK;
579 }
580 
581 /**
582  * @brief Delete the invalid forms.
583  * @param formIds Indicates the ID of the valid forms.
584  * @param callerToken Caller ability token.
585  * @param numFormsDeleted Returns the number of the deleted forms.
586  * @return Returns ERR_OK on success, others on failure.
587  */
DeleteInvalidForms(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,int32_t & numFormsDeleted)588 int FormMgrService::DeleteInvalidForms(const std::vector<int64_t> &formIds,
589     const sptr<IRemoteObject> &callerToken, int32_t &numFormsDeleted)
590 {
591     HILOG_INFO("%{public}s called.", __func__);
592     ErrCode ret = CheckFormPermission();
593     if (ret != ERR_OK) {
594         HILOG_ERROR("%{public}s fail, delete form permission denied", __func__);
595         return ret;
596     }
597     AAFwk::EventInfo eventInfo;
598     AAFwk::EventReport::SendFormEvent(AAFwk::EventName::DELETE_INVALID_FORM, HiSysEventType::BEHAVIOR, eventInfo);
599     return FormMgrAdapter::GetInstance().DeleteInvalidForms(formIds, callerToken, numFormsDeleted);
600 }
601 
602 /**
603   * @brief Acquire form state info by passing a set of parameters (using Want) to the form provider.
604   * @param want Indicates a set of parameters to be transparently passed to the form provider.
605   * @param callerToken Caller ability token.
606   * @param stateInfo Returns the form's state info of the specify.
607   * @return Returns ERR_OK on success, others on failure.
608   */
AcquireFormState(const Want & want,const sptr<IRemoteObject> & callerToken,FormStateInfo & stateInfo)609 int FormMgrService::AcquireFormState(const Want &want,
610     const sptr<IRemoteObject> &callerToken, FormStateInfo &stateInfo)
611 {
612     HILOG_INFO("%{public}s called.", __func__);
613     ErrCode ret = CheckFormPermission();
614     if (ret != ERR_OK) {
615         HILOG_ERROR("%{public}s fail, acquire form state permission denied", __func__);
616         return ret;
617     }
618     AAFwk::EventInfo eventInfo;
619     eventInfo.bundleName = want.GetElement().GetBundleName();
620     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
621     eventInfo.abilityName = want.GetElement().GetAbilityName();
622     AAFwk::EventReport::SendFormEvent(AAFwk::EventName::ACQUIREFORMSTATE_FORM, HiSysEventType::BEHAVIOR, eventInfo);
623     return FormMgrAdapter::GetInstance().AcquireFormState(want, callerToken, stateInfo);
624 }
625 
626 /**
627  * @brief Notify the form is visible or not.
628  * @param formIds Indicates the ID of the forms.
629  * @param isVisible Visible or not.
630  * @param callerToken Host client.
631  * @return Returns ERR_OK on success, others on failure.
632  */
NotifyFormsVisible(const std::vector<int64_t> & formIds,bool isVisible,const sptr<IRemoteObject> & callerToken)633 int FormMgrService::NotifyFormsVisible(const std::vector<int64_t> &formIds,
634     bool isVisible, const sptr<IRemoteObject> &callerToken)
635 {
636     HILOG_INFO("%{public}s called.", __func__);
637     ErrCode ret = CheckFormPermission();
638     if (ret != ERR_OK) {
639         HILOG_ERROR("%{public}s fail, notify form visible permission denied", __func__);
640         return ret;
641     }
642     return FormMgrAdapter::GetInstance().NotifyFormsVisible(formIds, isVisible, callerToken);
643 }
644 
NotifyFormsPrivacyProtected(const std::vector<int64_t> & formIds,bool isProtected,const sptr<IRemoteObject> & callerToken)645 int FormMgrService::NotifyFormsPrivacyProtected(const std::vector<int64_t> &formIds, bool isProtected,
646     const sptr<IRemoteObject> &callerToken)
647 {
648     HILOG_INFO("%{public}s called.", __func__);
649     ErrCode ret = CheckFormPermission();
650     if (ret != ERR_OK) {
651         HILOG_ERROR("%{public}s fail, notify form is privacy protected permission denied", __func__);
652         return ret;
653     }
654     return ERR_APPEXECFWK_FORM_COMMON_CODE;
655 }
656 
657 /**
658  * @brief Notify the form is enable to be updated or not.
659  * @param formIds Indicates the ID of the forms.
660  * @param isEnableUpdate enable update or not.
661  * @param callerToken Host client.
662  * @return Returns ERR_OK on success, others on failure.
663  */
NotifyFormsEnableUpdate(const std::vector<int64_t> & formIds,bool isEnableUpdate,const sptr<IRemoteObject> & callerToken)664 int FormMgrService::NotifyFormsEnableUpdate(const std::vector<int64_t> &formIds,
665     bool isEnableUpdate, const sptr<IRemoteObject> &callerToken)
666 {
667     HILOG_INFO("%{public}s called.", __func__);
668     ErrCode ret = CheckFormPermission();
669     if (ret != ERR_OK) {
670         HILOG_ERROR("%{public}s fail, notify form enable update permission denied", __func__);
671         return ret;
672     }
673     return FormMgrAdapter::GetInstance().NotifyFormsEnableUpdate(formIds, isEnableUpdate, callerToken);
674 }
675 
676 /**
677  * @brief Get All FormsInfo.
678  * @param formInfos Return the form information of all forms provided.
679  * @return Returns ERR_OK on success, others on failure.
680  */
GetAllFormsInfo(std::vector<FormInfo> & formInfos)681 int FormMgrService::GetAllFormsInfo(std::vector<FormInfo> &formInfos)
682 {
683     HILOG_INFO("%{public}s called.", __func__);
684     return FormMgrAdapter::GetInstance().GetAllFormsInfo(formInfos);
685 }
686 
687 /**
688  * @brief Get forms info by bundle name.
689  * @param bundleName Application name.
690  * @param formInfos Return the form information of the specify application name.
691  * @return Returns ERR_OK on success, others on failure.
692  */
GetFormsInfoByApp(std::string & bundleName,std::vector<FormInfo> & formInfos)693 int FormMgrService::GetFormsInfoByApp(std::string &bundleName, std::vector<FormInfo> &formInfos)
694 {
695     HILOG_INFO("%{public}s called.", __func__);
696     return FormMgrAdapter::GetInstance().GetFormsInfoByApp(bundleName, formInfos);
697 }
698 
699 /**
700  * @brief Get forms info by bundle name and module name.
701  * @param bundleName bundle name.
702  * @param moduleName Module name of hap.
703  * @param formInfos Return the forms information of the specify bundle name and module name.
704  * @return Returns ERR_OK on success, others on failure.
705  */
GetFormsInfoByModule(std::string & bundleName,std::string & moduleName,std::vector<FormInfo> & formInfos)706 int FormMgrService::GetFormsInfoByModule(std::string &bundleName, std::string &moduleName,
707                                          std::vector<FormInfo> &formInfos)
708 {
709     HILOG_INFO("%{public}s called.", __func__);
710     return FormMgrAdapter::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos);
711 }
712 
GetFormsInfo(const FormInfoFilter & filter,std::vector<FormInfo> & formInfos)713 int32_t FormMgrService::GetFormsInfo(const FormInfoFilter &filter, std::vector<FormInfo> &formInfos)
714 {
715     HILOG_INFO("%{public}s called.", __func__);
716     std::string callerBundleName;
717     auto ret = FormBmsHelper::GetInstance().GetCallerBundleName(callerBundleName);
718     if (ret != ERR_OK) {
719         HILOG_ERROR("%{public}s fail, get host bundle name failed", __func__);
720         return ret;
721     }
722     // retrieve moduleName from filter.
723     std::string moduleName = filter.moduleName;
724     if (moduleName.empty()) {
725         // fulfill formInfos, the process should be the same as GetFormsInfoByApp.
726         HILOG_INFO("GetFormsInfo flows to GetFormsInfoByAPP");
727         return FormMgrAdapter::GetInstance().GetFormsInfoByApp(callerBundleName, formInfos);
728     }
729     HILOG_INFO("GetFormsInfo flows to GetFormsInfoByModule");
730     return FormMgrAdapter::GetInstance().GetFormsInfoByModule(callerBundleName, moduleName, formInfos);
731 }
732 
IsRequestPublishFormSupported()733 bool FormMgrService::IsRequestPublishFormSupported()
734 {
735     HILOG_INFO("%{public}s called.", __func__);
736     // get IBundleMgr
737     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
738     if (iBundleMgr == nullptr) {
739         HILOG_ERROR("%{public}s error, failed to get IBundleMgr.", __func__);
740         return false;
741     }
742     // check if system app
743     auto isSystemApp = iBundleMgr->CheckIsSystemAppByUid(IPCSkeleton::GetCallingUid());
744     if (!isSystemApp) {
745         return false;
746     }
747     return FormMgrAdapter::GetInstance().IsRequestPublishFormSupported();
748 }
749 
StartAbility(const Want & want,const sptr<IRemoteObject> & callerToken)750 int32_t FormMgrService::StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken)
751 {
752     HILOG_INFO("%{public}s called.", __func__);
753     sptr<IBundleMgr> bundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
754     if (bundleMgr == nullptr) {
755         HILOG_ERROR("%{public}s error, failed to get bundleMgr.", __func__);
756         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
757     }
758     // check if system app
759     auto callingUid = IPCSkeleton::GetCallingUid();
760     auto isSystemApp = bundleMgr->CheckIsSystemAppByUid(callingUid);
761     if (!isSystemApp) {
762         HILOG_ERROR("%{public}s error, permission denied.", __func__);
763         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
764     }
765     // retrieve bundleName of the calling ability.
766     std::string callerBundleName;
767     if (!IN_PROCESS_CALL(bundleMgr->GetBundleNameForUid(callingUid, callerBundleName))) {
768         HILOG_ERROR("StartAbility, failed to get form config info.");
769         return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
770     }
771     // caller and callee should be in the same bundle.
772     if (want.GetElement().GetBundleName() != callerBundleName) {
773         return ERR_APPEXECFWK_FORM_INVALID_BUNDLENAME;
774     }
775     // check abilityName to void implicit want.
776     if (want.GetElement().GetAbilityName() == "") {
777         HILOG_ERROR("%{public}s error, AbilityName is empty", __func__);
778         return ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY;
779     }
780     sptr<AAFwk::IAbilityManager> ams = FormAmsHelper::GetInstance().GetAbilityManager();
781     if (ams == nullptr) {
782         HILOG_ERROR("%{public}s error, failed to get ams.", __func__);
783         return ERR_APPEXECFWK_FORM_COMMON_CODE;
784     }
785     return ams->StartAbility(want, callerToken, -1, -1);
786 }
787 
InitFormShareMgrEventHandler()788 void FormMgrService::InitFormShareMgrEventHandler()
789 {
790     DelayedSingleton<FormShareMgr>::GetInstance()->SetEventHandler(handler_);
791 }
792 
ShareForm(int64_t formId,const std::string & deviceId,const sptr<IRemoteObject> & callerToken,int64_t requestCode)793 int32_t FormMgrService::ShareForm(int64_t formId, const std::string &deviceId, const sptr<IRemoteObject> &callerToken,
794     int64_t requestCode)
795 {
796     HILOG_DEBUG("FormMgrService ShareForm called deviceId : %{public}s, formId: %{public}" PRId64 "",
797         deviceId.c_str(), formId);
798     if (formId <= 0) {
799         HILOG_ERROR("form formId  is invalid.");
800         return ERR_APPEXECFWK_FORM_COMMON_CODE;
801     }
802 
803     if (deviceId.empty()) {
804         HILOG_ERROR("form deviceId is empty.");
805         return ERR_APPEXECFWK_FORM_COMMON_CODE;
806     }
807 
808     if (callerToken == nullptr) {
809         HILOG_ERROR("callerToken is nullptr.");
810         return ERR_APPEXECFWK_FORM_COMMON_CODE;
811     }
812 
813     if (requestCode <= 0) {
814         HILOG_ERROR("form requestCode is invalid.");
815         return ERR_APPEXECFWK_FORM_COMMON_CODE;
816     }
817 
818     auto ret = CheckFormPermission();
819     if (ret != ERR_OK) {
820         HILOG_ERROR("share form permission denied.");
821         return ret;
822     }
823 
824     InitFormShareMgrEventHandler();
825 
826     return DelayedSingleton<FormShareMgr>::GetInstance()->ShareForm(formId, deviceId, callerToken, requestCode);
827 }
828 
RecvFormShareInfoFromRemote(const FormShareInfo & info)829 int32_t FormMgrService::RecvFormShareInfoFromRemote(const FormShareInfo &info)
830 {
831     HILOG_DEBUG("%{public}s called.", __func__);
832     InitFormShareMgrEventHandler();
833 
834     return DelayedSingleton<FormShareMgr>::GetInstance()->RecvFormShareInfoFromRemote(info);
835 }
836 
DumpInit()837 void FormMgrService::DumpInit()
838 {
839     dumpFuncMap_[DumpKey::KEY_DUMP_HELP] = &FormMgrService::HiDumpHelp;
840     dumpFuncMap_[DumpKey::KEY_DUMP_STORAGE] = &FormMgrService::HiDumpStorageFormInfos;
841     dumpFuncMap_[DumpKey::KEY_DUMP_BY_BUNDLE_NAME] = &FormMgrService::HiDumpFormInfoByBundleName;
842     dumpFuncMap_[DumpKey::KEY_DUMP_BY_FORM_ID] = &FormMgrService::HiDumpFormInfoByFormId;
843 }
844 
Dump(int fd,const std::vector<std::u16string> & args)845 int FormMgrService::Dump(int fd, const std::vector<std::u16string> &args)
846 {
847     if (!IsReady()) {
848         HILOG_ERROR("%{public}s, fms is not ready.", __func__);
849         return ERR_APPEXECFWK_FORM_COMMON_CODE;
850     }
851 
852     std::string result;
853     Dump(args, result);
854     int ret = dprintf(fd, "%s\n", result.c_str());
855     if (ret < 0) {
856         HILOG_ERROR("%{public}s, dprintf error.", __func__);
857         return ERR_APPEXECFWK_FORM_COMMON_CODE;
858     }
859     return ERR_OK;
860 }
861 
Dump(const std::vector<std::u16string> & args,std::string & result)862 void FormMgrService::Dump(const std::vector<std::u16string> &args, std::string &result)
863 {
864     DumpKey key;
865     std::string value;
866     if (!ParseOption(args, key, value, result)) {
867         result.append('\n' + FORM_DUMP_HELP);
868         return;
869     }
870 
871     auto iter = dumpFuncMap_.find(key);
872     if (iter == dumpFuncMap_.end() || iter->second == nullptr) {
873         result = "error: unknow function.";
874         return;
875     }
876 
877     auto dumpFunc = iter->second;
878     (this->*dumpFunc)(value, result);
879 }
880 
ParseOption(const std::vector<std::u16string> & args,DumpKey & key,std::string & value,std::string & result)881 bool FormMgrService::ParseOption(const std::vector<std::u16string> &args, DumpKey &key, std::string &value,
882     std::string &result)
883 {
884     auto size = args.size();
885     if (size == 0) {
886         result = "error: must contain arguments.";
887         return false;
888     }
889 
890     if (size > FORM_DUMP_ARGC_MAX) {
891         result = "error: arguments numer out of limit.";
892         return false;
893     }
894 
895     std::string optionKey = Str16ToStr8(args[0]);
896     auto iter = dumpKeyMap_.find(optionKey);
897     if (iter == dumpKeyMap_.end()) {
898         result = "error: unkown option.";
899         return false;
900     }
901 
902     key = iter->second;
903 
904     if (args.size() == FORM_DUMP_ARGC_MAX) {
905         value = Str16ToStr8(args[1]);
906     }
907 
908     return true;
909 }
910 
HiDumpHelp(const std::string & args,std::string & result)911 void FormMgrService::HiDumpHelp([[maybe_unused]] const std::string &args, std::string &result)
912 {
913     result = FORM_DUMP_HELP;
914 }
915 
HiDumpStorageFormInfos(const std::string & args,std::string & result)916 void FormMgrService::HiDumpStorageFormInfos([[maybe_unused]] const std::string &args, std::string &result)
917 {
918     DumpStorageFormInfos(result);
919 }
920 
HiDumpFormInfoByBundleName(const std::string & args,std::string & result)921 void FormMgrService::HiDumpFormInfoByBundleName(const std::string &args, std::string &result)
922 {
923     if (args.empty()) {
924         result = "error: request a bundle name.";
925         return;
926     }
927     DumpFormInfoByBundleName(args, result);
928 }
929 
HiDumpFormInfoByFormId(const std::string & args,std::string & result)930 void FormMgrService::HiDumpFormInfoByFormId(const std::string &args, std::string &result)
931 {
932     if (args.empty()) {
933         result = "error: request a form ID.";
934         return;
935     }
936     int64_t formId = atoll(args.c_str());
937     if (formId == 0) {
938         result = "error: form ID is invalid.";
939         return;
940     }
941     DumpFormInfoByFormId(formId, result);
942 }
943 }  // namespace AppExecFwk
944 }  // namespace OHOS