• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 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 "accesstoken_kit.h"
19 #include "bundle_common_event.h"
20 #include "common_event_manager.h"
21 #include "common_event_support.h"
22 #include "fms_log_wrapper.h"
23 #include "form_ams_helper.h"
24 #include "form_bms_helper.h"
25 #include "form_cache_mgr.h"
26 #include "form_constants.h"
27 #include "form_data_mgr.h"
28 #include "form_db_cache.h"
29 #include "form_event_handler.h"
30 #include "form_event_report.h"
31 #include "form_info_mgr.h"
32 #include "form_mgr_adapter.h"
33 #include "form_mgr_errors.h"
34 #include "form_serial_queue.h"
35 #include "form_share_mgr.h"
36 #include "form_task_mgr.h"
37 #include "form_timer_mgr.h"
38 #include "form_trust_mgr.h"
39 #include "form_util.h"
40 #include "form_xml_parser.h"
41 #include "in_process_call_wrapper.h"
42 #include "ipc_skeleton.h"
43 #include "iservice_registry.h"
44 #include "os_account_manager.h"
45 #include "permission_constants.h"
46 #include "permission_verification.h"
47 #include "system_ability_definition.h"
48 #include "tokenid_kit.h"
49 #include "hisysevent.h"
50 #include "xcollie/watchdog.h"
51 
52 namespace OHOS {
53 namespace AppExecFwk {
54 namespace {
55 const int32_t MAIN_USER_ID = 100;
56 constexpr int32_t GET_CALLING_UID_TRANSFORM_DIVISOR = 200000;
57 }
58 using namespace std::chrono;
59 
60 const bool REGISTER_RESULT =
61     SystemAbility::MakeAndRegisterAbility(DelayedSingleton<FormMgrService>::GetInstance().get());
62 
63 const std::string NAME_FORM_MGR_SERVICE = "FormMgrService";
64 
65 const std::string FORM_MGR_SERVICE_QUEUE = "FormMgrServiceQueue";
66 
67 constexpr int32_t FORM_DUMP_ARGC_MAX = 2;
68 
69 const std::string FORM_DUMP_HELP = "options list:\n"
70     "  -h, --help                           list available commands\n"
71     "  -b, --bundle-form-info               query all form infos from bundle, Un-added form info will also be dumped\n"
72     "  -s, --storage                        query form storage info\n"
73     "  -t, --temp                           query temporary form info\n"
74     "  -n  <bundle-name>                    query form info by a bundle name\n"
75     "  -i  <form-id>                        query form info by a form ID\n";
76 
77 const std::map<std::string, FormMgrService::DumpKey> FormMgrService::dumpKeyMap_ = {
78     {"-h", FormMgrService::DumpKey::KEY_DUMP_HELP},
79     {"--help", FormMgrService::DumpKey::KEY_DUMP_HELP},
80     {"-b", FormMgrService::DumpKey::KEY_DUMP_STATIC},   // *****
81     {"--bundle-form-info", FormMgrService::DumpKey::KEY_DUMP_STATIC},
82     {"-s", FormMgrService::DumpKey::KEY_DUMP_STORAGE},
83     {"--storage", FormMgrService::DumpKey::KEY_DUMP_STORAGE},
84     {"-t", FormMgrService::DumpKey::KEY_DUMP_TEMPORARY},
85     {"--temp", FormMgrService::DumpKey::KEY_DUMP_TEMPORARY},
86     {"-n", FormMgrService::DumpKey::KEY_DUMP_BY_BUNDLE_NAME},
87     {"-i", FormMgrService::DumpKey::KEY_DUMP_BY_FORM_ID},
88 };
89 
FormMgrService()90 FormMgrService::FormMgrService()
91     : SystemAbility(FORM_MGR_SERVICE_ID, true),
92       state_(ServiceRunningState::STATE_NOT_START),
93       serialQueue_(nullptr)
94 {
95     DumpInit();
96 }
97 
~FormMgrService()98 FormMgrService::~FormMgrService()
99 {
100     if (formSysEventReceiver_ != nullptr) {
101         EventFwk::CommonEventManager::UnSubscribeCommonEvent(formSysEventReceiver_);
102         formSysEventReceiver_ = nullptr;
103         sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
104         if (iBundleMgr == nullptr) {
105             return;
106         }
107         if (!iBundleMgr->UnregisterBundleEventCallback(formBundleEventCallback_)) {
108             HILOG_ERROR("%{public}s fail, UnregisterBundleEventCallback failed", __func__);
109         }
110         formBundleEventCallback_ = nullptr;
111     }
112 }
113 
IsReady() const114 bool FormMgrService::IsReady() const
115 {
116     if (state_ != ServiceRunningState::STATE_RUNNING) {
117         return false;
118     }
119 
120     int32_t userId = FormUtil::GetCurrentAccountId();
121     if (userId == Constants::ANY_USERID) {
122         HILOG_ERROR("%{public}s fail, account is empty", __func__);
123         return false;
124     }
125     return true;
126 }
127 
128 /**
129 * @brief Check form manager service ready.
130 * @return Return true if form manager service Ready; return false otherwise.
131 */
132 
CheckFMSReady()133 bool FormMgrService::CheckFMSReady()
134 {
135     return IsReady();
136 }
137 
138 /**
139  * @brief Add form with want, send want to form manager service.
140  * @param formId The Id of the forms to add.
141  * @param want The want of the form to add.
142  * @param callerToken Caller ability token.
143  * @param formInfo Form info.
144  * @return Returns ERR_OK on success, others on failure.
145  */
AddForm(const int64_t formId,const Want & want,const sptr<IRemoteObject> & callerToken,FormJsInfo & formInfo)146 int FormMgrService::AddForm(const int64_t formId, const Want &want,
147     const sptr<IRemoteObject> &callerToken, FormJsInfo &formInfo)
148 {
149     HILOG_DEBUG("called.");
150 
151     ErrCode ret = CheckFormPermission();
152     FormEventInfo eventInfo;
153     eventInfo.formId = formId;
154     eventInfo.bundleName = want.GetElement().GetBundleName();
155     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
156     eventInfo.abilityName = want.GetElement().GetAbilityName();
157     FormEventReport::SendFormEvent(FormEventName::ADD_FORM, HiSysEventType::BEHAVIOR, eventInfo);
158     if (ret != ERR_OK) {
159         HILOG_ERROR("%{public}s fail, add form permission denied", __func__);
160         return ret;
161     }
162     return FormMgrAdapter::GetInstance().AddForm(formId, want, callerToken, formInfo);
163 }
164 
165 /**
166  * @brief Delete forms with formIds, send formIds to form manager service.
167  * @param formId The Id of the forms to delete.
168  * @param callerToken Caller ability token.
169  * @return Returns ERR_OK on success, others on failure.
170  */
DeleteForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)171 int FormMgrService::DeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
172 {
173     HILOG_DEBUG("called.");
174 
175     ErrCode ret = CheckFormPermission();
176     if (ret != ERR_OK) {
177         HILOG_ERROR("%{public}s fail, delete form permission denied", __func__);
178         return ret;
179     }
180     FormEventInfo eventInfo;
181     eventInfo.formId = formId;
182     FormEventReport::SendFormEvent(FormEventName::DELETE_FORM, HiSysEventType::BEHAVIOR, eventInfo);
183 
184     return FormMgrAdapter::GetInstance().DeleteForm(formId, callerToken);
185 }
186 
187 /**
188  * @brief Stop rendering form.
189  * @param formId The Id of the forms to delete.
190  * @param compId The compId of the forms to delete.
191  * @return Returns ERR_OK on success, others on failure.
192  */
StopRenderingForm(const int64_t formId,const std::string & compId)193 int FormMgrService::StopRenderingForm(const int64_t formId, const std::string &compId)
194 {
195     ErrCode ret = CheckFormPermission();
196     if (ret != ERR_OK) {
197         HILOG_ERROR("%{public}s fail, delete form permission denied", __func__);
198         return ret;
199     }
200 
201     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
202     if (ret != ERR_OK) {
203         HILOG_ERROR("fail, the form id is invalid or not under the current active user.");
204         return ret;
205     }
206     return FormMgrAdapter::GetInstance().StopRenderingForm(formId, compId);
207 }
208 
209 
210 
211 /**
212  * @brief Release forms with formIds, send formIds to form manager service.
213  * @param formId The Id of the forms to release.
214  * @param callerToken Caller ability token.
215  * @param delCache Delete Cache or not.
216  * @return Returns ERR_OK on success, others on failure.
217  */
ReleaseForm(const int64_t formId,const sptr<IRemoteObject> & callerToken,const bool delCache)218 int FormMgrService::ReleaseForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const bool delCache)
219 {
220     HILOG_DEBUG("called.");
221 
222     ErrCode ret = CheckFormPermission();
223     if (ret != ERR_OK) {
224         HILOG_ERROR("%{public}s fail, release form permission denied", __func__);
225         return ret;
226     }
227     FormEventInfo eventInfo;
228     eventInfo.formId = formId;
229     FormEventReport::SendFormEvent(FormEventName::RELEASE_FORM, HiSysEventType::BEHAVIOR, eventInfo);
230 
231     return FormMgrAdapter::GetInstance().ReleaseForm(formId, callerToken, delCache);
232 }
233 
234 /**
235  * @brief Update form with formId, send formId to form manager service.
236  * @param formId The Id of the form to update.
237  * @param formBindingData Form binding data.
238  * @return Returns ERR_OK on success, others on failure.
239  */
UpdateForm(const int64_t formId,const FormProviderData & formBindingData)240 int FormMgrService::UpdateForm(const int64_t formId, const FormProviderData &formBindingData)
241 {
242     HILOG_DEBUG("called.");
243     std::string callerBundleName;
244     auto ret = FormBmsHelper::GetInstance().GetCallerBundleName(callerBundleName);
245     if (ret != ERR_OK) {
246         HILOG_ERROR("%{public}s fail, get caller bundle name failed", __func__);
247         return ret;
248     }
249     return FormMgrAdapter::GetInstance().UpdateForm(formId, callerBundleName, formBindingData);
250 }
251 
252 /**
253  * @brief Request form with formId and want, send formId and want to form manager service.
254  * @param formId The Id of the form to update.
255  * @param callerToken Caller ability token.
256  * @param want The want of the form to add.
257  * @return Returns ERR_OK on success, others on failure.
258  */
RequestForm(const int64_t formId,const sptr<IRemoteObject> & callerToken,const Want & want)259 int FormMgrService::RequestForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const Want &want)
260 {
261     HILOG_INFO("%{public}s called.", __func__);
262 
263     ErrCode ret = CheckFormPermission();
264     if (ret != ERR_OK) {
265         HILOG_ERROR("%{public}s fail, request form permission denied", __func__);
266         return ret;
267     }
268     FormEventInfo eventInfo;
269     eventInfo.formId = formId;
270     eventInfo.bundleName = want.GetElement().GetBundleName();
271     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
272     eventInfo.abilityName = want.GetElement().GetAbilityName();
273     FormEventReport::SendFormEvent(FormEventName::REQUEST_FORM, HiSysEventType::BEHAVIOR, eventInfo);
274 
275     return FormMgrAdapter::GetInstance().RequestForm(formId, callerToken, want);
276 }
277 
278 /**
279  * @brief set next refresh time.
280  * @param formId The id of the form.
281  * @param nextTime next refresh time.
282  * @return Returns ERR_OK on success, others on failure.
283  */
SetNextRefreshTime(const int64_t formId,const int64_t nextTime)284 int FormMgrService::SetNextRefreshTime(const int64_t formId, const int64_t nextTime)
285 {
286     HILOG_INFO("%{public}s called.", __func__);
287     FormEventInfo eventInfo;
288     eventInfo.formId = formId;
289     FormEventReport::SendFormEvent(
290         FormEventName::SET_NEXT_REFRESH_TIME_FORM, HiSysEventType::BEHAVIOR, eventInfo);
291 
292     return FormMgrAdapter::GetInstance().SetNextRefreshTime(formId, nextTime);
293 }
294 
ReleaseRenderer(int64_t formId,const std::string & compId)295 int FormMgrService::ReleaseRenderer(int64_t formId, const std::string &compId)
296 {
297     HILOG_INFO("%{public}s called.", __func__);
298     ErrCode ret = CheckFormPermission();
299     if (ret != ERR_OK) {
300         HILOG_ERROR("%{public}s fail, request form permission denied", __func__);
301         return ret;
302     }
303     return FormMgrAdapter::GetInstance().ReleaseRenderer(formId, compId);
304 }
305 
RequestPublishForm(Want & want,bool withFormBindingData,std::unique_ptr<FormProviderData> & formBindingData,int64_t & formId)306 ErrCode FormMgrService::RequestPublishForm(Want &want, bool withFormBindingData,
307     std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId)
308 {
309     HILOG_INFO("%{public}s called.", __func__);
310     if (!CheckCallerIsSystemApp()) {
311         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
312     }
313     return FormMgrAdapter::GetInstance().RequestPublishForm(want, withFormBindingData, formBindingData, formId);
314 }
315 
316 /**
317  * @brief Form visible/invisible notify, send formIds to form manager service.
318  * @param formIds The Id list of the forms to notify.
319  * @param callerToken Caller ability token.
320  * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE.
321  * @return Returns ERR_OK on success, others on failure.
322  */
NotifyWhetherVisibleForms(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,const int32_t formVisibleType)323 int FormMgrService::NotifyWhetherVisibleForms(const std::vector<int64_t> &formIds,
324     const sptr<IRemoteObject> &callerToken, const int32_t formVisibleType)
325 {
326     HILOG_DEBUG("called.");
327 
328     ErrCode ret = CheckFormPermission();
329     if (ret != ERR_OK) {
330         HILOG_ERROR("%{public}s fail, event notify visible permission denied", __func__);
331         return ret;
332     }
333     return FormMgrAdapter::GetInstance().NotifyWhetherVisibleForms(formIds, callerToken, formVisibleType);
334 }
335 
336 /**
337  * @brief temp form to normal form.
338  * @param formId The Id of the form.
339  * @param callerToken Caller ability token.
340  * @return Returns ERR_OK on success, others on failure.
341  */
CastTempForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)342 int FormMgrService::CastTempForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
343 {
344     HILOG_DEBUG("called.");
345 
346     ErrCode ret = CheckFormPermission();
347     if (ret != ERR_OK) {
348         HILOG_ERROR("%{public}s fail, cast temp form permission denied", __func__);
349         return ret;
350     }
351     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
352     if (ret != ERR_OK) {
353         HILOG_ERROR("fail, the form id is invalid or not under the current active user.");
354         return ret;
355     }
356     FormEventInfo eventInfo;
357     eventInfo.formId = formId;
358     FormEventReport::SendFormEvent(FormEventName::CASTTEMP_FORM, HiSysEventType::BEHAVIOR, eventInfo);
359 
360     return FormMgrAdapter::GetInstance().CastTempForm(formId, callerToken);
361 }
362 
363 /**
364  * @brief lifecycle update.
365  * @param formIds formIds of host client.
366  * @param callerToken Caller ability token.
367  * @param updateType update type,enable or disable.
368  * @return Returns true on success, false on failure.
369  */
LifecycleUpdate(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,bool updateType)370 int FormMgrService::LifecycleUpdate(const std::vector<int64_t> &formIds,
371     const sptr<IRemoteObject> &callerToken, bool updateType)
372 {
373     HILOG_INFO("lifecycleUpdate. %{public}d", updateType);
374 
375     ErrCode ret = CheckFormPermission();
376     if (ret != ERR_OK) {
377         HILOG_ERROR("fail, delete form permission denied");
378         return ret;
379     }
380 
381     if (updateType) {
382         return FormMgrAdapter::GetInstance().EnableUpdateForm(formIds, callerToken);
383     } else {
384         return FormMgrAdapter::GetInstance().DisableUpdateForm(formIds, callerToken);
385     }
386 }
387 /**
388  * @brief Dump all of form storage infos.
389  * @param formInfos All of form storage infos.
390  * @return Returns ERR_OK on success, others on failure.
391  */
DumpStorageFormInfos(std::string & formInfos)392 int FormMgrService::DumpStorageFormInfos(std::string &formInfos)
393 {
394     if (!CheckCallerIsSystemApp()) {
395         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
396     }
397     return FormMgrAdapter::GetInstance().DumpStorageFormInfos(formInfos);
398 }
399 /**
400  * @brief Dump form info by a bundle name.
401  * @param bundleName The bundle name of form provider.
402  * @param formInfos Form infos.
403  * @return Returns ERR_OK on success, others on failure.
404  */
DumpFormInfoByBundleName(const std::string & bundleName,std::string & formInfos)405 int FormMgrService::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos)
406 {
407     if (!CheckCallerIsSystemApp()) {
408         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
409     }
410     return FormMgrAdapter::GetInstance().DumpFormInfoByBundleName(bundleName, formInfos);
411 }
412 /**
413  * @brief Dump form info by a bundle name.
414  * @param formId The id of the form.
415  * @param formInfo Form info.
416  * @return Returns ERR_OK on success, others on failure.
417  */
DumpFormInfoByFormId(const std::int64_t formId,std::string & formInfo)418 int FormMgrService::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo)
419 {
420     if (!CheckCallerIsSystemApp()) {
421         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
422     }
423     return FormMgrAdapter::GetInstance().DumpFormInfoByFormId(formId, formInfo);
424 }
425 /**
426  * @brief Dump form timer by form id.
427  * @param formId The id of the form.
428  * @param formInfo Form info.
429  * @return Returns ERR_OK on success, others on failure.
430  */
DumpFormTimerByFormId(const std::int64_t formId,std::string & isTimingService)431 int FormMgrService::DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService)
432 {
433     if (!CheckCallerIsSystemApp()) {
434         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
435     }
436     return FormMgrAdapter::GetInstance().DumpFormTimerByFormId(formId, isTimingService);
437 }
438 /**
439  * @brief Process js message event.
440  * @param formId Indicates the unique id of form.
441  * @param want information passed to supplier.
442  * @param callerToken Caller ability token.
443  * @return Returns true if execute success, false otherwise.
444  */
MessageEvent(const int64_t formId,const Want & want,const sptr<IRemoteObject> & callerToken)445 int FormMgrService::MessageEvent(const int64_t formId, const Want &want, const sptr<IRemoteObject> &callerToken)
446 {
447     HILOG_INFO("%{public}s called.", __func__);
448     ErrCode ret = CheckFormPermission();
449     if (ret != ERR_OK) {
450         HILOG_ERROR("%{public}s fail, request form permission denied", __func__);
451         return ret;
452     }
453     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
454     if (ret != ERR_OK) {
455         HILOG_ERROR("fail, the form id is invalid or not under the current active user.");
456         return ret;
457     }
458     FormEventInfo eventInfo;
459     eventInfo.bundleName = want.GetElement().GetBundleName();
460     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
461     eventInfo.abilityName = want.GetElement().GetAbilityName();
462     FormEventReport::SendFormEvent(FormEventName::MESSAGE_EVENT_FORM, HiSysEventType::BEHAVIOR, eventInfo);
463     return FormMgrAdapter::GetInstance().MessageEvent(formId, want, callerToken);
464 }
465 
466 /**
467  * @brief Process js router event.
468  * @param formId Indicates the unique id of form.
469  * @param want the want of the ability to start.
470  * @param callerToken Caller ability token.
471  * @return Returns true if execute success, false otherwise.
472  */
RouterEvent(const int64_t formId,Want & want,const sptr<IRemoteObject> & callerToken)473 int FormMgrService::RouterEvent(const int64_t formId, Want &want, const sptr<IRemoteObject> &callerToken)
474 {
475     HILOG_INFO("%{public}s called.", __func__);
476     ErrCode ret = CheckFormPermission();
477     if (ret != ERR_OK) {
478         HILOG_ERROR("%{public}s fail, request form permission denied", __func__);
479         return ret;
480     }
481     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
482     if (ret != ERR_OK) {
483         HILOG_ERROR("fail, the form id is invalid or not under the current active user.");
484         return ret;
485     }
486     FormEventInfo eventInfo;
487     eventInfo.formId = formId;
488     eventInfo.bundleName = want.GetElement().GetBundleName();
489     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
490     eventInfo.abilityName = want.GetElement().GetAbilityName();
491     FormEventReport::SendFormEvent(FormEventName::ROUTE_EVENT_FORM, HiSysEventType::BEHAVIOR, eventInfo);
492     return FormMgrAdapter::GetInstance().RouterEvent(formId, want, callerToken);
493 }
494 
495 /**
496  * @brief Process Background event.
497  * @param formId Indicates the unique id of form.
498  * @param want the want of the ability to start.
499  * @param callerToken Caller ability token.
500  * @return Returns true if execute success, false otherwise.
501  */
BackgroundEvent(const int64_t formId,Want & want,const sptr<IRemoteObject> & callerToken)502 int FormMgrService::BackgroundEvent(const int64_t formId, Want &want, const sptr<IRemoteObject> &callerToken)
503 {
504     HILOG_INFO("%{public}s called.", __func__);
505     ErrCode ret = CheckFormPermission();
506     if (ret != ERR_OK) {
507         HILOG_ERROR("%{public}s fail, request form permission denied", __func__);
508         return ret;
509     }
510     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
511     if (ret != ERR_OK) {
512         HILOG_ERROR("fail, the form id is invalid or not under the current active user.");
513         return ret;
514     }
515     FormEventInfo eventInfo;
516     eventInfo.formId = formId;
517     eventInfo.bundleName = want.GetElement().GetBundleName();
518     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
519     eventInfo.abilityName = want.GetElement().GetAbilityName();
520     FormEventReport::SendFormEvent(FormEventName::BACKGROUND_EVENT_FORM, HiSysEventType::BEHAVIOR, eventInfo);
521     return FormMgrAdapter::GetInstance().BackgroundEvent(formId, want, callerToken);
522 }
523 
524 /**
525  * @brief Start event for the form manager service.
526  */
OnStart()527 void FormMgrService::OnStart()
528 {
529     if (state_ == ServiceRunningState::STATE_RUNNING) {
530         HILOG_WARN("%{public}s fail, Failed to start service since it's already running", __func__);
531         return;
532     }
533 
534     HILOG_INFO("Form Mgr Service start...");
535     ErrCode errCode = Init();
536     if (errCode != ERR_OK) {
537         HILOG_ERROR("%{public}s fail, Failed to init, errCode: %{public}08x", __func__, errCode);
538         return;
539     }
540 
541     state_ = ServiceRunningState::STATE_RUNNING;
542     HILOG_INFO("Form Mgr Service start success.");
543 }
544 /**
545  * @brief Stop event for the form manager service.
546  */
OnStop()547 void FormMgrService::OnStop()
548 {
549     HILOG_INFO("stop service");
550 
551     state_ = ServiceRunningState::STATE_NOT_START;
552 
553     if (serialQueue_) {
554         serialQueue_.reset();
555     }
556 
557     if (handler_) {
558         handler_.reset();
559     }
560 }
561 
ReadFormConfigXML()562 ErrCode FormMgrService::ReadFormConfigXML()
563 {
564     FormXMLParser parser;
565     int32_t ret = parser.Parse();
566     if (ret != ERR_OK) {
567         HILOG_WARN("parse form config failed, use the default vaule.");
568         return ret;
569     }
570     const std::map<std::string, int32_t> &configMap = parser.GetConfigMap();
571     FormDataMgr::GetInstance().SetConfigMap(configMap);
572     return ERR_OK;
573 }
574 
575 /**
576  * @brief initialization of form manager service.
577  */
Init()578 ErrCode FormMgrService::Init()
579 {
580     HILOG_INFO("FormMgrService Init start");
581     serialQueue_ = std::make_shared<FormSerialQueue>(FORM_MGR_SERVICE_QUEUE.c_str());
582     if (serialQueue_ == nullptr) {
583         HILOG_ERROR("Init fail, Failed to init due to create serialQueue_ error");
584         return ERR_INVALID_OPERATION;
585     }
586 
587     handler_ = std::make_shared<FormEventHandler>(serialQueue_);
588     if (handler_ == nullptr) {
589         HILOG_ERROR("%{public}s fail, Failed to init due to create handler error", __func__);
590         return ERR_INVALID_OPERATION;
591     }
592     FormTaskMgr::GetInstance().SetSerialQueue(serialQueue_);
593     FormAmsHelper::GetInstance().SetSerialQueue(serialQueue_);
594     /* Publish service maybe failed, so we need call this function at the last,
595      * so it can't affect the TDD test program */
596     bool ret = Publish(DelayedSingleton<FormMgrService>::GetInstance().get());
597     if (!ret) {
598         HILOG_ERROR("%{public}s fail, FormMgrService::Init Publish failed!", __func__);
599         return ERR_INVALID_OPERATION;
600     }
601 
602     if (formSysEventReceiver_ == nullptr) {
603         EventFwk::MatchingSkills matchingSkills;
604         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_UPDATED);
605         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED);
606         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED);
607         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
608         matchingSkills.AddEvent(COMMON_EVENT_BUNDLE_SCAN_FINISHED);
609         // init TimerReceiver
610         EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
611         subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
612         formSysEventReceiver_ = std::make_shared<FormSysEventReceiver>(subscribeInfo);
613         formSysEventReceiver_->SetSerialQueue(serialQueue_);
614         EventFwk::CommonEventManager::SubscribeCommonEvent(formSysEventReceiver_);
615     }
616 
617     FormTrustMgr::GetInstance().Start();
618     FormInfoMgr::GetInstance().Start();
619     FormInfoMgr::GetInstance().ReloadFormInfos(MAIN_USER_ID);
620     FormDbCache::GetInstance().Start();
621     FormTimerMgr::GetInstance(); // Init FormTimerMgr
622     FormCacheMgr::GetInstance().Start();
623     // Register formbundleEventCallback to receive hap updates
624     formBundleEventCallback_ = new (std::nothrow) FormBundleEventCallback();
625     if (formBundleEventCallback_ == nullptr) {
626         HILOG_ERROR("fail, allocate formBundleEventCallback_ failed!");
627         return ERR_APPEXECFWK_FORM_COMMON_CODE;
628     }
629     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
630     if (iBundleMgr == nullptr) {
631         return ERR_APPEXECFWK_FORM_COMMON_CODE;
632     }
633     bool re = iBundleMgr->RegisterBundleEventCallback(formBundleEventCallback_);
634     if (!re) {
635         HILOG_ERROR("fail, RegisterBundleEventCallback failed!");
636         return ERR_APPEXECFWK_FORM_COMMON_CODE;
637     }
638 
639     // read param form form_config.xml.
640     int32_t result = ReadFormConfigXML();
641     if (result != ERR_OK) {
642         HILOG_WARN("parse form config failed, use the default vaule.");
643     }
644     HILOG_INFO("init success");
645     return ERR_OK;
646 }
647 
CheckFormObserverPermission()648 ErrCode FormMgrService::CheckFormObserverPermission()
649 {
650     HILOG_DEBUG("called.");
651 
652     if (FormUtil::IsSACall()) {
653         return ERR_OK;
654     }
655 
656     // check if system app
657     if (!CheckCallerIsSystemApp()) {
658         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
659     }
660 
661     if (!CheckAcrossLocalAccountsPermission()) {
662         HILOG_ERROR("Across local accounts permission failed.");
663         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
664     }
665 
666     if (!FormUtil::VerifyCallingPermission(AppExecFwk::Constants::PERMISSION_REQUIRE_FORM) &&
667         !FormUtil::VerifyCallingPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING)) {
668         HILOG_ERROR("verify calling permission failed!");
669         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
670     }
671     HILOG_DEBUG("Form Observer permission verification ok!");
672     return ERR_OK;
673 }
674 
CheckFormPermission()675 ErrCode FormMgrService::CheckFormPermission()
676 {
677     HILOG_DEBUG("called.");
678 
679     if (FormUtil::IsSACall()) {
680         return ERR_OK;
681     }
682 
683     // check if system app
684     if (!CheckCallerIsSystemApp()) {
685         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
686     }
687 
688     auto isCallingPerm = FormUtil::VerifyCallingPermission(AppExecFwk::Constants::PERMISSION_REQUIRE_FORM);
689     if (!isCallingPerm) {
690         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
691     }
692 
693     // checks whether the current user is inactive
694     if (!CheckAcrossLocalAccountsPermission()) {
695         HILOG_ERROR("Across local accounts permission failed.");
696         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
697     }
698 
699     HILOG_DEBUG("Permission verification ok!");
700     return ERR_OK;
701 }
702 
703 /**
704  * @brief Delete the invalid forms.
705  * @param formIds Indicates the ID of the valid forms.
706  * @param callerToken Caller ability token.
707  * @param numFormsDeleted Returns the number of the deleted forms.
708  * @return Returns ERR_OK on success, others on failure.
709  */
DeleteInvalidForms(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,int32_t & numFormsDeleted)710 int FormMgrService::DeleteInvalidForms(const std::vector<int64_t> &formIds,
711     const sptr<IRemoteObject> &callerToken, int32_t &numFormsDeleted)
712 {
713     HILOG_INFO("called.");
714     ErrCode ret = CheckFormPermission();
715     if (ret != ERR_OK) {
716         HILOG_ERROR("fail, delete form permission denied");
717         return ret;
718     }
719     FormEventInfo eventInfo;
720     FormEventReport::SendFormEvent(FormEventName::DELETE_INVALID_FORM, HiSysEventType::BEHAVIOR, eventInfo);
721     return FormMgrAdapter::GetInstance().DeleteInvalidForms(formIds, callerToken, numFormsDeleted);
722 }
723 
724 /**
725   * @brief Acquire form state info by passing a set of parameters (using Want) to the form provider.
726   * @param want Indicates a set of parameters to be transparently passed to the form provider.
727   * @param callerToken Caller ability token.
728   * @param stateInfo Returns the form's state info of the specify.
729   * @return Returns ERR_OK on success, others on failure.
730   */
AcquireFormState(const Want & want,const sptr<IRemoteObject> & callerToken,FormStateInfo & stateInfo)731 int FormMgrService::AcquireFormState(const Want &want,
732     const sptr<IRemoteObject> &callerToken, FormStateInfo &stateInfo)
733 {
734     HILOG_INFO("called.");
735     ErrCode ret = CheckFormPermission();
736     if (ret != ERR_OK) {
737         HILOG_ERROR("fail, acquire form state permission denied");
738         return ret;
739     }
740     FormEventInfo eventInfo;
741     eventInfo.bundleName = want.GetElement().GetBundleName();
742     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
743     eventInfo.abilityName = want.GetElement().GetAbilityName();
744     FormEventReport::SendFormEvent(FormEventName::ACQUIREFORMSTATE_FORM, HiSysEventType::BEHAVIOR, eventInfo);
745     return FormMgrAdapter::GetInstance().AcquireFormState(want, callerToken, stateInfo);
746 }
747 
748 /**
749  * @brief Notify the form is visible or not.
750  * @param formIds Indicates the ID of the forms.
751  * @param isVisible Visible or not.
752  * @param callerToken Host client.
753  * @return Returns ERR_OK on success, others on failure.
754  */
NotifyFormsVisible(const std::vector<int64_t> & formIds,bool isVisible,const sptr<IRemoteObject> & callerToken)755 int FormMgrService::NotifyFormsVisible(const std::vector<int64_t> &formIds,
756     bool isVisible, const sptr<IRemoteObject> &callerToken)
757 {
758     HILOG_INFO("called.");
759     ErrCode ret = CheckFormPermission();
760     if (ret != ERR_OK) {
761         HILOG_ERROR("fail, notify form visible permission denied");
762         return ret;
763     }
764     return FormMgrAdapter::GetInstance().NotifyFormsVisible(formIds, isVisible, callerToken);
765 }
766 
NotifyFormsPrivacyProtected(const std::vector<int64_t> & formIds,bool isProtected,const sptr<IRemoteObject> & callerToken)767 int FormMgrService::NotifyFormsPrivacyProtected(const std::vector<int64_t> &formIds, bool isProtected,
768     const sptr<IRemoteObject> &callerToken)
769 {
770     HILOG_INFO("called.");
771     ErrCode ret = CheckFormPermission();
772     if (ret != ERR_OK) {
773         HILOG_ERROR("fail, notify form is privacy protected permission denied");
774         return ret;
775     }
776     return ERR_APPEXECFWK_FORM_COMMON_CODE;
777 }
778 
779 /**
780  * @brief Notify the form is enable to be updated or not.
781  * @param formIds Indicates the ID of the forms.
782  * @param isEnableUpdate enable update or not.
783  * @param callerToken Host client.
784  * @return Returns ERR_OK on success, others on failure.
785  */
NotifyFormsEnableUpdate(const std::vector<int64_t> & formIds,bool isEnableUpdate,const sptr<IRemoteObject> & callerToken)786 int FormMgrService::NotifyFormsEnableUpdate(const std::vector<int64_t> &formIds,
787     bool isEnableUpdate, const sptr<IRemoteObject> &callerToken)
788 {
789     HILOG_INFO("called.");
790     ErrCode ret = CheckFormPermission();
791     if (ret != ERR_OK) {
792         HILOG_ERROR("fail, notify form enable update permission denied");
793         return ret;
794     }
795     return FormMgrAdapter::GetInstance().NotifyFormsEnableUpdate(formIds, isEnableUpdate, callerToken);
796 }
797 
798 /**
799  * @brief Get All FormsInfo.
800  * @param formInfos Return the form information of all forms provided.
801  * @return Returns ERR_OK on success, others on failure.
802  */
GetAllFormsInfo(std::vector<FormInfo> & formInfos)803 int FormMgrService::GetAllFormsInfo(std::vector<FormInfo> &formInfos)
804 {
805     HILOG_INFO("called.");
806     if (!CheckCallerIsSystemApp()) {
807         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
808     }
809     if (!CheckAcrossLocalAccountsPermission()) {
810         HILOG_ERROR("Across local accounts permission failed.");
811         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
812     }
813     return FormMgrAdapter::GetInstance().GetAllFormsInfo(formInfos);
814 }
815 
816 /**
817  * @brief Get forms info by bundle name.
818  * @param bundleName Application name.
819  * @param formInfos Return the form information of the specify application name.
820  * @return Returns ERR_OK on success, others on failure.
821  */
GetFormsInfoByApp(std::string & bundleName,std::vector<FormInfo> & formInfos)822 int FormMgrService::GetFormsInfoByApp(std::string &bundleName, std::vector<FormInfo> &formInfos)
823 {
824     HILOG_INFO("called.");
825     if (!CheckCallerIsSystemApp()) {
826         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
827     }
828     if (!CheckAcrossLocalAccountsPermission()) {
829         HILOG_ERROR("Across local accounts permission failed.");
830         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
831     }
832     return FormMgrAdapter::GetInstance().GetFormsInfoByApp(bundleName, formInfos);
833 }
834 
835 /**
836  * @brief Get forms info by bundle name and module name.
837  * @param bundleName bundle name.
838  * @param moduleName Module name of hap.
839  * @param formInfos Return the forms information of the specify bundle name and module name.
840  * @return Returns ERR_OK on success, others on failure.
841  */
GetFormsInfoByModule(std::string & bundleName,std::string & moduleName,std::vector<FormInfo> & formInfos)842 int FormMgrService::GetFormsInfoByModule(std::string &bundleName, std::string &moduleName,
843                                          std::vector<FormInfo> &formInfos)
844 {
845     HILOG_INFO("called.");
846     if (!CheckCallerIsSystemApp()) {
847         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
848     }
849     if (!CheckAcrossLocalAccountsPermission()) {
850         HILOG_ERROR("Across local accounts permission failed.");
851         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
852     }
853     return FormMgrAdapter::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos);
854 }
855 
GetFormsInfo(const FormInfoFilter & filter,std::vector<FormInfo> & formInfos)856 int32_t FormMgrService::GetFormsInfo(const FormInfoFilter &filter, std::vector<FormInfo> &formInfos)
857 {
858     HILOG_INFO("called.");
859     std::string callerBundleName;
860     auto ret = FormBmsHelper::GetInstance().GetCallerBundleName(callerBundleName);
861     if (ret != ERR_OK) {
862         HILOG_ERROR("fail, get host bundle name failed");
863         return ret;
864     }
865     // retrieve moduleName from filter.
866     std::string moduleName = filter.moduleName;
867     if (moduleName.empty()) {
868         // fulfill formInfos, the process should be the same as GetFormsInfoByApp.
869         HILOG_INFO("GetFormsInfo flows to GetFormsInfoByAPP");
870         return FormMgrAdapter::GetInstance().GetFormsInfoByApp(callerBundleName, formInfos);
871     }
872     HILOG_INFO("GetFormsInfo flows to GetFormsInfoByModule");
873     return FormMgrAdapter::GetInstance().GetFormsInfoByModule(callerBundleName, moduleName, formInfos);
874 }
875 
AcquireFormData(int64_t formId,int64_t requestCode,const sptr<IRemoteObject> & callerToken,AAFwk::WantParams & formData)876 int32_t FormMgrService::AcquireFormData(int64_t formId, int64_t requestCode, const sptr<IRemoteObject> &callerToken,
877     AAFwk::WantParams &formData)
878 {
879     HILOG_INFO("called.");
880     if (formId <= 0) {
881         HILOG_ERROR("form formId  is invalid.");
882         return ERR_APPEXECFWK_FORM_COMMON_CODE;
883     }
884 
885     if (callerToken == nullptr) {
886         HILOG_ERROR("callerToken is nullptr.");
887         return ERR_APPEXECFWK_FORM_COMMON_CODE;
888     }
889 
890     if (requestCode <= 0) {
891         HILOG_ERROR("form requestCode is invalid.");
892         return ERR_APPEXECFWK_FORM_COMMON_CODE;
893     }
894 
895     ErrCode ret = CheckFormPermission();
896     if (ret != ERR_OK) {
897         HILOG_ERROR("fail, request form permission denied");
898         return ret;
899     }
900     return FormMgrAdapter::GetInstance().AcquireFormData(formId, requestCode, callerToken, formData);
901 }
902 
IsRequestPublishFormSupported()903 bool FormMgrService::IsRequestPublishFormSupported()
904 {
905     HILOG_INFO("%{public}s called.", __func__);
906     if (!CheckCallerIsSystemApp()) {
907         return false;
908     }
909     return FormMgrAdapter::GetInstance().IsRequestPublishFormSupported();
910 }
911 
StartAbility(const Want & want,const sptr<IRemoteObject> & callerToken)912 int32_t FormMgrService::StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken)
913 {
914     HILOG_INFO("%{public}s called.", __func__);
915     sptr<IBundleMgr> bundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
916     if (bundleMgr == nullptr) {
917         HILOG_ERROR("%{public}s error, failed to get bundleMgr.", __func__);
918         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
919     }
920     if (!CheckCallerIsSystemApp()) {
921         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
922     }
923     // retrieve bundleName of the calling ability.
924     std::string callerBundleName;
925     auto callUid = IPCSkeleton::GetCallingUid();
926     if (IN_PROCESS_CALL(bundleMgr->GetNameForUid(callUid, callerBundleName)) != ERR_OK) {
927         HILOG_ERROR("StartAbility, failed to get form config info.");
928         return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
929     }
930     // caller and callee should be in the same bundle.
931     if (want.GetElement().GetBundleName() != callerBundleName) {
932         return ERR_APPEXECFWK_FORM_INVALID_BUNDLENAME;
933     }
934     // check abilityName to void implicit want.
935     if (want.GetElement().GetAbilityName() == "") {
936         HILOG_ERROR("%{public}s error, AbilityName is empty", __func__);
937         return ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY;
938     }
939     sptr<AAFwk::IAbilityManager> ams = FormAmsHelper::GetInstance().GetAbilityManager();
940     if (ams == nullptr) {
941         HILOG_ERROR("%{public}s error, failed to get ams.", __func__);
942         return ERR_APPEXECFWK_FORM_COMMON_CODE;
943     }
944     return ams->StartAbility(want, callerToken, -1, -1);
945 }
946 
InitFormShareMgrSerialQueue()947 void FormMgrService::InitFormShareMgrSerialQueue()
948 {
949     DelayedSingleton<FormShareMgr>::GetInstance()->SetSerialQueue(serialQueue_);
950     DelayedSingleton<FormShareMgr>::GetInstance()->SetEventHandler(handler_);
951 }
952 
ShareForm(int64_t formId,const std::string & deviceId,const sptr<IRemoteObject> & callerToken,int64_t requestCode)953 int32_t FormMgrService::ShareForm(int64_t formId, const std::string &deviceId, const sptr<IRemoteObject> &callerToken,
954     int64_t requestCode)
955 {
956     HILOG_DEBUG("FormMgrService ShareForm called deviceId : %{public}s, formId: %{public}" PRId64 "",
957         deviceId.c_str(), formId);
958     if (formId <= 0) {
959         HILOG_ERROR("form formId  is invalid.");
960         return ERR_APPEXECFWK_FORM_COMMON_CODE;
961     }
962 
963     if (deviceId.empty()) {
964         HILOG_ERROR("form deviceId is empty.");
965         return ERR_APPEXECFWK_FORM_COMMON_CODE;
966     }
967 
968     if (callerToken == nullptr) {
969         HILOG_ERROR("callerToken is nullptr.");
970         return ERR_APPEXECFWK_FORM_COMMON_CODE;
971     }
972 
973     if (requestCode <= 0) {
974         HILOG_ERROR("form requestCode is invalid.");
975         return ERR_APPEXECFWK_FORM_COMMON_CODE;
976     }
977 
978     auto ret = CheckFormPermission();
979     if (ret != ERR_OK) {
980         HILOG_ERROR("share form permission denied.");
981         return ret;
982     }
983 
984     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
985     if (ret != ERR_OK) {
986         HILOG_ERROR("fail, the form id is invalid or not under the current active user.");
987         return ret;
988     }
989 
990     InitFormShareMgrSerialQueue();
991 
992     return DelayedSingleton<FormShareMgr>::GetInstance()->ShareForm(formId, deviceId, callerToken, requestCode);
993 }
994 
RecvFormShareInfoFromRemote(const FormShareInfo & info)995 int32_t FormMgrService::RecvFormShareInfoFromRemote(const FormShareInfo &info)
996 {
997     HILOG_DEBUG("%{public}s called.", __func__);
998     InitFormShareMgrSerialQueue();
999 
1000     return DelayedSingleton<FormShareMgr>::GetInstance()->RecvFormShareInfoFromRemote(info);
1001 }
1002 
DumpInit()1003 void FormMgrService::DumpInit()
1004 {
1005     dumpFuncMap_[DumpKey::KEY_DUMP_HELP] = &FormMgrService::HiDumpHelp;
1006     dumpFuncMap_[DumpKey::KEY_DUMP_STATIC] = &FormMgrService::HiDumpStaticBundleFormInfos;
1007     dumpFuncMap_[DumpKey::KEY_DUMP_STORAGE] = &FormMgrService::HiDumpStorageFormInfos;
1008     dumpFuncMap_[DumpKey::KEY_DUMP_TEMPORARY] = &FormMgrService::HiDumpTemporaryFormInfos;
1009     dumpFuncMap_[DumpKey::KEY_DUMP_BY_BUNDLE_NAME] = &FormMgrService::HiDumpFormInfoByBundleName;
1010     dumpFuncMap_[DumpKey::KEY_DUMP_BY_FORM_ID] = &FormMgrService::HiDumpFormInfoByFormId;
1011 }
1012 
Dump(int fd,const std::vector<std::u16string> & args)1013 int FormMgrService::Dump(int fd, const std::vector<std::u16string> &args)
1014 {
1015     if (!IsReady()) {
1016         HILOG_ERROR("%{public}s, fms is not ready.", __func__);
1017         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1018     }
1019 
1020     std::string result;
1021     Dump(args, result);
1022     int ret = dprintf(fd, "%s\n", result.c_str());
1023     if (ret < 0) {
1024         HILOG_ERROR("%{public}s, dprintf error.", __func__);
1025         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1026     }
1027     return ERR_OK;
1028 }
1029 
Dump(const std::vector<std::u16string> & args,std::string & result)1030 void FormMgrService::Dump(const std::vector<std::u16string> &args, std::string &result)
1031 {
1032     DumpKey key;
1033     std::string value;
1034     if (!ParseOption(args, key, value, result)) {
1035         result.append('\n' + FORM_DUMP_HELP);
1036         return;
1037     }
1038 
1039     auto iter = dumpFuncMap_.find(key);
1040     if (iter == dumpFuncMap_.end() || iter->second == nullptr) {
1041         result = "error: unknow function.";
1042         return;
1043     }
1044 
1045     auto dumpFunc = iter->second;
1046     (this->*dumpFunc)(value, result);
1047 }
1048 
RegisterPublishFormInterceptor(const sptr<IRemoteObject> & interceptorCallback)1049 int32_t FormMgrService::RegisterPublishFormInterceptor(const sptr<IRemoteObject> &interceptorCallback)
1050 {
1051     HILOG_DEBUG("called.");
1052     sptr<IBundleMgr> bundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1053     if (bundleMgr == nullptr) {
1054         HILOG_ERROR("failed to get bundleMgr.");
1055         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1056     }
1057     // check if system app
1058     auto callingUid = IPCSkeleton::GetCallingUid();
1059     auto isSystemApp = bundleMgr->CheckIsSystemAppByUid(callingUid);
1060     if (!isSystemApp) {
1061         HILOG_ERROR("permission denied.");
1062         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1063     }
1064     return FormMgrAdapter::GetInstance().RegisterPublishFormInterceptor(interceptorCallback);
1065 }
1066 
UnregisterPublishFormInterceptor(const sptr<IRemoteObject> & interceptorCallback)1067 int32_t FormMgrService::UnregisterPublishFormInterceptor(const sptr<IRemoteObject> &interceptorCallback)
1068 {
1069     HILOG_DEBUG("called.");
1070     sptr<IBundleMgr> bundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1071     if (bundleMgr == nullptr) {
1072         HILOG_ERROR("failed to get bundleMgr.");
1073         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1074     }
1075     // check if system app
1076     auto callingUid = IPCSkeleton::GetCallingUid();
1077     auto isSystemApp = bundleMgr->CheckIsSystemAppByUid(callingUid);
1078     if (!isSystemApp) {
1079         HILOG_ERROR("permission denied.");
1080         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1081     }
1082     return FormMgrAdapter::GetInstance().UnregisterPublishFormInterceptor(interceptorCallback);
1083 }
1084 
ParseOption(const std::vector<std::u16string> & args,DumpKey & key,std::string & value,std::string & result)1085 bool FormMgrService::ParseOption(const std::vector<std::u16string> &args, DumpKey &key, std::string &value,
1086     std::string &result)
1087 {
1088     auto size = args.size();
1089     if (size == 0) {
1090         result = "error: must contain arguments.";
1091         return false;
1092     }
1093 
1094     if (size > FORM_DUMP_ARGC_MAX) {
1095         result = "error: arguments numer out of limit.";
1096         return false;
1097     }
1098 
1099     std::string optionKey = Str16ToStr8(args[0]);
1100     auto iter = dumpKeyMap_.find(optionKey);
1101     if (iter == dumpKeyMap_.end()) {
1102         result = "error: unkown option.";
1103         return false;
1104     }
1105 
1106     key = iter->second;
1107 
1108     if (args.size() == FORM_DUMP_ARGC_MAX) {
1109         value = Str16ToStr8(args[1]);
1110     }
1111 
1112     return true;
1113 }
1114 
HiDumpHelp(const std::string & args,std::string & result)1115 void FormMgrService::HiDumpHelp([[maybe_unused]] const std::string &args, std::string &result)
1116 {
1117     result = FORM_DUMP_HELP;
1118 }
1119 
HiDumpStorageFormInfos(const std::string & args,std::string & result)1120 void FormMgrService::HiDumpStorageFormInfos([[maybe_unused]] const std::string &args, std::string &result)
1121 {
1122     DumpStorageFormInfos(result);
1123 }
1124 
HiDumpTemporaryFormInfos(const std::string & args,std::string & result)1125 void FormMgrService::HiDumpTemporaryFormInfos([[maybe_unused]] const std::string &args, std::string &result)
1126 {
1127     if (!CheckCallerIsSystemApp()) {
1128         return;
1129     }
1130     FormMgrAdapter::GetInstance().DumpTemporaryFormInfos(result);
1131 }
1132 
HiDumpStaticBundleFormInfos(const std::string & args,std::string & result)1133 void FormMgrService::HiDumpStaticBundleFormInfos([[maybe_unused]] const std::string &args, std::string &result)
1134 {
1135     if (!CheckCallerIsSystemApp()) {
1136         return;
1137     }
1138     FormMgrAdapter::GetInstance().DumpStaticBundleFormInfos(result);
1139 }
1140 
HiDumpFormInfoByBundleName(const std::string & args,std::string & result)1141 void FormMgrService::HiDumpFormInfoByBundleName(const std::string &args, std::string &result)
1142 {
1143     if (args.empty()) {
1144         result = "error: request a bundle name.";
1145         return;
1146     }
1147     DumpFormInfoByBundleName(args, result);
1148 }
1149 
HiDumpFormInfoByFormId(const std::string & args,std::string & result)1150 void FormMgrService::HiDumpFormInfoByFormId(const std::string &args, std::string &result)
1151 {
1152     if (args.empty()) {
1153         result = "error: request a form ID.";
1154         return;
1155     }
1156     int64_t formId = atoll(args.c_str());
1157     if (formId == 0) {
1158         result = "error: form ID is invalid.";
1159         return;
1160     }
1161     DumpFormInfoByFormId(formId, result);
1162 }
1163 
CheckCallerIsSystemApp() const1164 bool FormMgrService::CheckCallerIsSystemApp() const
1165 {
1166     auto callerTokenID = IPCSkeleton::GetCallingFullTokenID();
1167     if (!FormUtil::IsSACall() && !Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(callerTokenID)) {
1168         HILOG_ERROR("The caller is not system-app, can not use system-api");
1169         return false;
1170     }
1171     return true;
1172 }
1173 
CheckAcrossLocalAccountsPermission() const1174 bool FormMgrService::CheckAcrossLocalAccountsPermission() const
1175 {
1176     // checks whether the current user is inactive
1177     int callingUid = IPCSkeleton::GetCallingUid();
1178     int32_t userId = callingUid / GET_CALLING_UID_TRANSFORM_DIVISOR;
1179     int32_t currentActiveUserId = FormUtil::GetCurrentAccountId();
1180     if (userId != currentActiveUserId) {
1181         HILOG_DEBUG("currentActiveUserId: %{public}d, userId: %{public}d", currentActiveUserId, userId);
1182         bool isCallingPermAccount =
1183             FormUtil::VerifyCallingPermission(AppExecFwk::Constants::PERMISSION_INTERACT_ACROSS_LOCAL_ACCOUNTS);
1184         if (!isCallingPermAccount) {
1185             HILOG_ERROR("Across local accounts permission failed.");
1186             return false;
1187         }
1188     }
1189     return true;
1190 }
1191 
RegisterFormAddObserverByBundle(const std::string bundleName,const sptr<IRemoteObject> & callerToken)1192 ErrCode FormMgrService::RegisterFormAddObserverByBundle(const std::string bundleName,
1193     const sptr<IRemoteObject> &callerToken)
1194 {
1195     HILOG_DEBUG("called.");
1196     ErrCode ret = CheckFormObserverPermission();
1197     if (ret != ERR_OK) {
1198         HILOG_ERROR("fail, register form add observer permission denied");
1199         return ret;
1200     }
1201     return FormMgrAdapter::GetInstance().RegisterFormAddObserverByBundle(bundleName, callerToken);
1202 }
1203 
RegisterFormRemoveObserverByBundle(const std::string bundleName,const sptr<IRemoteObject> & callerToken)1204 ErrCode FormMgrService::RegisterFormRemoveObserverByBundle(const std::string bundleName,
1205     const sptr<IRemoteObject> &callerToken)
1206 {
1207     HILOG_DEBUG("called.");
1208     ErrCode ret = CheckFormObserverPermission();
1209     if (ret != ERR_OK) {
1210         HILOG_ERROR("fail, register form remove observer permission denied");
1211         return ret;
1212     }
1213     return FormMgrAdapter::GetInstance().RegisterFormRemoveObserverByBundle(bundleName, callerToken);
1214 }
1215 
GetFormsCount(bool isTempFormFlag,int32_t & formCount)1216 int32_t FormMgrService::GetFormsCount(bool isTempFormFlag, int32_t &formCount)
1217 {
1218     HILOG_INFO("%{public}s called.", __func__);
1219     return FormMgrAdapter::GetInstance().GetFormsCount(isTempFormFlag, formCount);
1220 }
1221 
GetHostFormsCount(std::string & bundleName,int32_t & formCount)1222 int32_t FormMgrService::GetHostFormsCount(std::string &bundleName, int32_t &formCount)
1223 {
1224     HILOG_INFO("%{public}s called.", __func__);
1225     return FormMgrAdapter::GetInstance().GetHostFormsCount(bundleName, formCount);
1226 }
1227 
GetRunningFormInfos(std::vector<RunningFormInfo> & runningFormInfos)1228 ErrCode FormMgrService::GetRunningFormInfos(std::vector<RunningFormInfo> &runningFormInfos)
1229 {
1230     HILOG_DEBUG("called.");
1231     ErrCode ret = CheckFormObserverPermission();
1232     if (ret != ERR_OK) {
1233         HILOG_ERROR("fail, get running form infos permission denied");
1234         return ret;
1235     }
1236     return FormMgrAdapter::GetInstance().GetRunningFormInfos(runningFormInfos);
1237 }
1238 
GetRunningFormInfosByBundleName(const std::string & bundleName,std::vector<RunningFormInfo> & runningFormInfos)1239 ErrCode FormMgrService::GetRunningFormInfosByBundleName(const std::string &bundleName,
1240     std::vector<RunningFormInfo> &runningFormInfos)
1241 {
1242     HILOG_DEBUG("called.");
1243     ErrCode ret = CheckFormObserverPermission();
1244     if (ret != ERR_OK) {
1245         HILOG_ERROR("fail, get running form infos by bundle name permission denied");
1246         return ret;
1247     }
1248     return FormMgrAdapter::GetInstance().GetRunningFormInfosByBundleName(bundleName, runningFormInfos);
1249 }
1250 
GetFormInstancesByFilter(const FormInstancesFilter & formInstancesFilter,std::vector<FormInstance> & formInstances)1251 ErrCode FormMgrService::GetFormInstancesByFilter(const FormInstancesFilter &formInstancesFilter,
1252     std::vector<FormInstance> &formInstances)
1253 {
1254     HILOG_DEBUG("called.");
1255     ErrCode ret = CheckFormObserverPermission();
1256     if (ret != ERR_OK) {
1257         HILOG_ERROR("fail, get form instances by filter permission denied");
1258         return ret;
1259     }
1260     return FormMgrAdapter::GetInstance().GetFormInstancesByFilter(formInstancesFilter, formInstances);
1261 }
1262 
GetFormInstanceById(const int64_t formId,FormInstance & formInstance)1263 ErrCode FormMgrService::GetFormInstanceById(const int64_t formId, FormInstance &formInstance)
1264 {
1265     HILOG_DEBUG("called.");
1266     ErrCode ret = CheckFormObserverPermission();
1267     if (ret != ERR_OK) {
1268         HILOG_ERROR("fail, get form instance by id permission denied");
1269         return ret;
1270     }
1271     return FormMgrAdapter::GetInstance().GetFormInstanceById(formId, formInstance);
1272 }
1273 
GetFormInstanceById(const int64_t formId,bool isIncludeUnused,FormInstance & formInstance)1274 ErrCode FormMgrService::GetFormInstanceById(const int64_t formId, bool isIncludeUnused, FormInstance &formInstance)
1275 {
1276     HILOG_DEBUG("called.");
1277     ErrCode ret = CheckFormObserverPermission();
1278     if (ret != ERR_OK) {
1279         HILOG_ERROR("fail, get form instance by id permission denied");
1280         return ret;
1281     }
1282     return FormMgrAdapter::GetInstance().GetFormInstanceById(formId, isIncludeUnused, formInstance);
1283 }
1284 
RegisterAddObserver(const std::string & bundleName,const sptr<IRemoteObject> & callerToken)1285 ErrCode FormMgrService::RegisterAddObserver(const std::string &bundleName, const sptr<IRemoteObject> &callerToken)
1286 {
1287     HILOG_DEBUG("called.");
1288     ErrCode ret = CheckFormObserverPermission();
1289     if (ret != ERR_OK) {
1290         HILOG_ERROR("fail, register notifyVisible or notifyInVisible observer permission denied");
1291         return ret;
1292     }
1293     return FormMgrAdapter::GetInstance().RegisterAddObserver(bundleName, callerToken);
1294 }
1295 
RegisterRemoveObserver(const std::string & bundleName,const sptr<IRemoteObject> & callerToken)1296 ErrCode FormMgrService::RegisterRemoveObserver(const std::string &bundleName, const sptr<IRemoteObject> &callerToken)
1297 {
1298     HILOG_DEBUG("called.");
1299     ErrCode ret = CheckFormObserverPermission();
1300     if (ret != ERR_OK) {
1301         HILOG_ERROR("fail, unregister notifyVisible or notifyInVisible observer permission denied");
1302         return ret;
1303     }
1304     return FormMgrAdapter::GetInstance().RegisterRemoveObserver(bundleName, callerToken);
1305 }
1306 
UpdateProxyForm(int64_t formId,const FormProviderData & formBindingData,const std::vector<FormDataProxy> & formDataProxies)1307 ErrCode FormMgrService::UpdateProxyForm(int64_t formId, const FormProviderData &formBindingData,
1308     const std::vector<FormDataProxy> &formDataProxies)
1309 {
1310     HILOG_DEBUG("called.");
1311     std::string callerBundleName;
1312     auto ret = FormBmsHelper::GetInstance().GetCallerBundleName(callerBundleName);
1313     if (ret != ERR_OK) {
1314         HILOG_ERROR("%{public}s fail, get caller bundle name failed", __func__);
1315         return ret;
1316     }
1317     return FormMgrAdapter::GetInstance().UpdateForm(formId, callerBundleName, formBindingData, formDataProxies);
1318 }
1319 
RequestPublishProxyForm(Want & want,bool withFormBindingData,std::unique_ptr<FormProviderData> & formBindingData,int64_t & formId,const std::vector<FormDataProxy> & formDataProxies)1320 ErrCode FormMgrService::RequestPublishProxyForm(Want &want, bool withFormBindingData,
1321     std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId,
1322     const std::vector<FormDataProxy> &formDataProxies)
1323 {
1324     HILOG_DEBUG("called.");
1325     if (!CheckCallerIsSystemApp()) {
1326         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1327     }
1328     return FormMgrAdapter::GetInstance().RequestPublishForm(want, withFormBindingData, formBindingData, formId,
1329         formDataProxies);
1330 }
1331 }  // namespace AppExecFwk
1332 }  // namespace OHOS