1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "form_mgr_service.h"
17 
18 #include <chrono>
19 #include <ctime>
20 #include <iomanip>
21 #include <sstream>
22 
23 #include "accesstoken_kit.h"
24 #include "bundle_common_event.h"
25 #include "common_event_manager.h"
26 #include "common_event_support.h"
27 #include "fms_log_wrapper.h"
28 #include "form_ams_helper.h"
29 #include "form_bms_helper.h"
30 #include "form_bundle_forbid_mgr.h"
31 #include "form_cache_mgr.h"
32 #include "form_constants.h"
33 #include "form_data_mgr.h"
34 #include "form_data_proxy_mgr.h"
35 #include "form_db_cache.h"
36 #include "form_event_handler.h"
37 #include "form_event_report.h"
38 #include "form_info_mgr.h"
39 #include "form_mgr_adapter.h"
40 #include "form_mgr_errors.h"
41 #include "form_serial_queue.h"
42 #include "form_share_mgr.h"
43 #include "form_task_mgr.h"
44 #include "form_timer_mgr.h"
45 #include "form_trust_mgr.h"
46 #include "form_util.h"
47 #include "form_xml_parser.h"
48 #include "in_process_call_wrapper.h"
49 #include "ipc_skeleton.h"
50 #include "iservice_registry.h"
51 #include "mem_status_listener.h"
52 #include "os_account_manager.h"
53 #include "permission_constants.h"
54 #include "permission_verification.h"
55 #include "system_ability_definition.h"
56 #include "tokenid_kit.h"
57 #include "hisysevent.h"
58 #include "xcollie/watchdog.h"
59 #include "xcollie/xcollie.h"
60 #include "xcollie/xcollie_define.h"
61 #ifdef MEM_MGR_ENABLE
62 #include "mem_mgr_client.h"
63 #endif
64 #include "form_report.h"
65 
66 #ifdef RES_SCHEDULE_ENABLE
67 #include "form_systemload_listener.h"
68 #include "res_sched_client.h"
69 #include "res_type.h"
70 #endif // RES_SCHEDULE_ENABLE
71 
72 namespace OHOS {
73 namespace AppExecFwk {
74 namespace {
75 const int32_t MAIN_USER_ID = 100;
76 constexpr int MILLISECOND_WIDTH = 3;
77 constexpr char MILLISECOND_FILLCHAR = '0';
78 const int32_t API_TIME_OUT = 5;
79 const int32_t API_TIME_OUT_30s = 30;
80 #ifdef RES_SCHEDULE_ENABLE
81 constexpr int32_t SYSTEMLOADLEVEL_TIMERSTOP_THRESHOLD =
82     static_cast<int32_t>(ResourceSchedule::ResType::SystemloadLevel::HIGH);
83 #endif // RES_SCHEDULE_ENABLE
84 }
85 using namespace std::chrono;
86 
87 const bool REGISTER_RESULT =
88     SystemAbility::MakeAndRegisterAbility(DelayedSingleton<FormMgrService>::GetInstance().get());
89 
90 const std::string NAME_FORM_MGR_SERVICE = "FormMgrService";
91 
92 const std::string FORM_MGR_SERVICE_QUEUE = "FormMgrServiceQueue";
93 
94 constexpr int32_t FORM_DUMP_ARGC_MAX = 2;
95 
96 const std::string FORM_DUMP_HELP = "options list:\n"
97     "  -h, --help                           list available commands\n"
98     "  -b, --bundle-form-info               query all form infos from bundle, Un-added form info will also be dumped\n"
99     "  -v, --visible                        query form visible infos from args like bundleName_userId_instIndex\n"
100     "  -s, --storage                        query form storage info\n"
101     "  -t, --temp                           query temporary form info\n"
102     "  -n  <bundle-name>                    query form info by a bundle name\n"
103     "  -i  <form-id>                        query form info by a form ID\n"
104     "  -r  --running                        query running form info\n"
105     "  -a  --apps-blocked                   query blocked app name list\n";
106 
107 const std::map<std::string, FormMgrService::DumpKey> FormMgrService::dumpKeyMap_ = {
108     {"-h", FormMgrService::DumpKey::KEY_DUMP_HELP},
109     {"--help", FormMgrService::DumpKey::KEY_DUMP_HELP},
110     {"-b", FormMgrService::DumpKey::KEY_DUMP_STATIC},   // *****
111     {"--bundle-form-info", FormMgrService::DumpKey::KEY_DUMP_STATIC},
112     {"-v", FormMgrService::DumpKey::KEY_DUMP_VISIBLE},
113     {"--visible", FormMgrService::DumpKey::KEY_DUMP_VISIBLE},
114     {"-s", FormMgrService::DumpKey::KEY_DUMP_STORAGE},
115     {"--storage", FormMgrService::DumpKey::KEY_DUMP_STORAGE},
116     {"-t", FormMgrService::DumpKey::KEY_DUMP_TEMPORARY},
117     {"--temp", FormMgrService::DumpKey::KEY_DUMP_TEMPORARY},
118     {"-n", FormMgrService::DumpKey::KEY_DUMP_BY_BUNDLE_NAME},
119     {"-i", FormMgrService::DumpKey::KEY_DUMP_BY_FORM_ID},
120     {"-r", FormMgrService::DumpKey::KEY_DUMP_RUNNING},
121     {"--running", FormMgrService::DumpKey::KEY_DUMP_RUNNING},
122     {"-a", FormMgrService::DumpKey::KEY_DUMP_BLOCKED_APPS},
123     {"--apps-blocked", FormMgrService::DumpKey::KEY_DUMP_BLOCKED_APPS},
124 };
125 
FormMgrService()126 FormMgrService::FormMgrService()
127     : SystemAbility(FORM_MGR_SERVICE_ID, true),
128       state_(ServiceRunningState::STATE_NOT_START),
129       serialQueue_(nullptr)
130 {
131     HILOG_INFO("call");
132 }
133 
~FormMgrService()134 FormMgrService::~FormMgrService()
135 {
136     HILOG_INFO("call");
137     if (formSysEventReceiver_ != nullptr) {
138         EventFwk::CommonEventManager::UnSubscribeCommonEvent(formSysEventReceiver_);
139         formSysEventReceiver_ = nullptr;
140         FormBmsHelper::GetInstance().UnregisterBundleEventCallback();
141     }
142 #ifdef MEM_MGR_ENABLE
143     if (memStatusListener_ != nullptr) {
144         Memory::MemMgrClient::GetInstance().UnsubscribeAppState(*memStatusListener_);
145     }
146 #endif
147 }
148 
149 /**
150 * @brief Check form manager service ready.
151 * @return Return true if form manager service Ready; return false otherwise.
152 */
153 
CheckFMSReady()154 bool FormMgrService::CheckFMSReady()
155 {
156     if (state_ != ServiceRunningState::STATE_RUNNING) {
157         return false;
158     }
159 
160     int32_t userId = FormUtil::GetCurrentAccountId();
161     if (userId == Constants::ANY_USERID) {
162         HILOG_ERROR("empty account");
163         return false;
164     }
165     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_CheckFMSReady",
166         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
167     bool result = FormInfoMgr::GetInstance().HasReloadedFormInfos();
168     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
169     return result;
170 }
171 
IsSystemAppForm(const std::string &bundleName)172 bool FormMgrService::IsSystemAppForm(const std::string &bundleName)
173 {
174     HILOG_DEBUG("check %{public}s is system form.", bundleName.c_str());
175 
176     std::vector<FormRecord> formRecords;
177     FormDataMgr::GetInstance().GetFormRecord(bundleName, formRecords);
178     if (formRecords.empty()) {
179         return false;
180     }
181     return formRecords.front().isSystemApp;
182 }
183 
184 /**
185  * @brief Add form with want, send want to form manager service.
186  * @param formId The Id of the forms to add.
187  * @param want The want of the form to add.
188  * @param callerToken Caller ability token.
189  * @param formInfo Form info.
190  * @return Returns ERR_OK on success, others on failure.
191  */
AddForm(const int64_t formId, const Want &want, const sptr<IRemoteObject> &callerToken, FormJsInfo &formInfo)192 int FormMgrService::AddForm(const int64_t formId, const Want &want,
193     const sptr<IRemoteObject> &callerToken, FormJsInfo &formInfo)
194 {
195     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
196         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
197         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
198 
199     ErrCode ret = CheckFormPermission();
200     if (ret != ERR_OK) {
201         HILOG_ERROR("add form permission denied");
202         return ret;
203     }
204     ReportAddFormEvent(formId, want);
205     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_AddForm",
206         API_TIME_OUT_30s, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
207     ret = FormMgrAdapter::GetInstance().AddForm(formId, want, callerToken, formInfo);
208     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
209     return ret;
210 }
211 
212 /**
213  * @brief Add form with want, send want to form manager service.
214  * @param want The want of the form to add.
215  * @param runningFormInfo Running form info.
216  * @return Returns ERR_OK on success, others on failure.
217  */
CreateForm(const Want &want, RunningFormInfo &runningFormInfo)218 int FormMgrService::CreateForm(const Want &want, RunningFormInfo &runningFormInfo)
219 {
220     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
221         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
222         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
223 
224     ErrCode ret = CheckFormPermission();
225     if (ret != ERR_OK) {
226         HILOG_ERROR("create form permission denied");
227         return ret;
228     }
229     ReportAddFormEvent(0, want);
230     return FormMgrAdapter::GetInstance().CreateForm(want, runningFormInfo);
231 }
232 
ReportAddFormEvent(const int64_t formId, const Want &want)233 void FormMgrService::ReportAddFormEvent(const int64_t formId, const Want &want)
234 {
235     FormEventInfo eventInfo;
236     eventInfo.formId = formId;
237     eventInfo.bundleName = want.GetElement().GetBundleName();
238     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
239     eventInfo.abilityName = want.GetElement().GetAbilityName();
240     int ret = FormBmsHelper::GetInstance().GetCallerBundleName(eventInfo.hostBundleName);
241     if (ret != ERR_OK || eventInfo.hostBundleName.empty()) {
242         HILOG_ERROR("cannot get host bundle name by uid");
243     }
244     FormEventReport::SendFormEvent(FormEventName::ADD_FORM, HiSysEventType::BEHAVIOR, eventInfo);
245 }
246 
247 /**
248  * @brief Delete forms with formIds, send formIds to form manager service.
249  * @param formId The Id of the forms to delete.
250  * @param callerToken Caller ability token.
251  * @return Returns ERR_OK on success, others on failure.
252  */
DeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)253 int FormMgrService::DeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
254 {
255     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
256         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
257         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
258 
259     ErrCode ret = CheckFormPermission();
260     if (ret != ERR_OK) {
261         HILOG_ERROR("delete form permission denied");
262         return ret;
263     }
264     FormEventInfo eventInfo;
265     eventInfo.formId = formId;
266     std::vector<FormHostRecord> formHostRecords;
267     FormDataMgr::GetInstance().GetFormHostRecord(formId, formHostRecords);
268     if (formHostRecords.size() != 0) {
269         eventInfo.hostBundleName = formHostRecords.begin()->GetHostBundleName();
270     }
271     FormEventReport::SendSecondFormEvent(FormEventName::DELETE_FORM, HiSysEventType::BEHAVIOR, eventInfo);
272     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_DeleteForm",
273         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
274     ret = FormMgrAdapter::GetInstance().DeleteForm(formId, callerToken);
275     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
276     return ret;
277 }
278 
279 /**
280  * @brief Stop rendering form.
281  * @param formId The Id of the forms to delete.
282  * @param compId The compId of the forms to delete.
283  * @return Returns ERR_OK on success, others on failure.
284  */
StopRenderingForm(const int64_t formId, const std::string &compId)285 int FormMgrService::StopRenderingForm(const int64_t formId, const std::string &compId)
286 {
287     ErrCode ret = CheckFormPermission();
288     if (ret != ERR_OK) {
289         HILOG_ERROR("delete form permission denied");
290         return ret;
291     }
292 
293     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
294     if (ret != ERR_OK) {
295         HILOG_ERROR("invalid formId or not under currentActiveUser");
296         return ret;
297     }
298     return FormMgrAdapter::GetInstance().StopRenderingForm(formId, compId);
299 }
300 
301 /**
302  * @brief Release forms with formIds, send formIds to form manager service.
303  * @param formId The Id of the forms to release.
304  * @param callerToken Caller ability token.
305  * @param delCache Delete Cache or not.
306  * @return Returns ERR_OK on success, others on failure.
307  */
ReleaseForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const bool delCache)308 int FormMgrService::ReleaseForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const bool delCache)
309 {
310     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
311         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
312         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
313 
314     ErrCode ret = CheckFormPermission();
315     if (ret != ERR_OK) {
316         HILOG_ERROR("release form permission denied");
317         return ret;
318     }
319     FormEventInfo eventInfo;
320     eventInfo.formId = formId;
321     FormEventReport::SendSecondFormEvent(FormEventName::RELEASE_FORM, HiSysEventType::BEHAVIOR, eventInfo);
322 
323     return FormMgrAdapter::GetInstance().ReleaseForm(formId, callerToken, delCache);
324 }
325 
326 /**
327  * @brief Update form with formId, send formId to form manager service.
328  * @param formId The Id of the form to update.
329  * @param formBindingData Form binding data.
330  * @return Returns ERR_OK on success, others on failure.
331  */
UpdateForm(const int64_t formId, const FormProviderData &formBindingData)332 int FormMgrService::UpdateForm(const int64_t formId, const FormProviderData &formBindingData)
333 {
334     HILOG_DEBUG("call");
335     auto callingUid = IPCSkeleton::GetCallingUid();
336     return FormMgrAdapter::GetInstance().UpdateForm(formId, callingUid, formBindingData);
337 }
338 
339 /**
340  * @brief Request form with formId and want, send formId and want to form manager service.
341  * @param formId The Id of the form to update.
342  * @param callerToken Caller ability token.
343  * @param want The want of the form to add.
344  * @return Returns ERR_OK on success, others on failure.
345  */
RequestForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const Want &want)346 int FormMgrService::RequestForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const Want &want)
347 {
348     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
349         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
350         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
351     ErrCode ret = CheckFormPermission();
352     if (ret != ERR_OK) {
353         HILOG_ERROR("request form permission denied");
354         return ret;
355     }
356     FormEventInfo eventInfo;
357     eventInfo.formId = formId;
358     eventInfo.bundleName = want.GetElement().GetBundleName();
359     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
360     eventInfo.abilityName = want.GetElement().GetAbilityName();
361     FormEventReport::SendSecondFormEvent(FormEventName::REQUEST_FORM, HiSysEventType::BEHAVIOR, eventInfo);
362 
363     return FormMgrAdapter::GetInstance().RequestForm(formId, callerToken, want);
364 }
365 
366 /**
367  * @brief set next refresh time.
368  * @param formId The id of the form.
369  * @param nextTime next refresh time.
370  * @return Returns ERR_OK on success, others on failure.
371  */
SetNextRefreshTime(const int64_t formId, const int64_t nextTime)372 int FormMgrService::SetNextRefreshTime(const int64_t formId, const int64_t nextTime)
373 {
374     HILOG_DEBUG("call");
375     FormEventInfo eventInfo;
376     eventInfo.formId = formId;
377     FormEventReport::SendSecondFormEvent(
378         FormEventName::SET_NEXT_REFRESH_TIME_FORM, HiSysEventType::BEHAVIOR, eventInfo);
379 
380     return FormMgrAdapter::GetInstance().SetNextRefreshTime(formId, nextTime);
381 }
382 
ReleaseRenderer(int64_t formId, const std::string &compId)383 int FormMgrService::ReleaseRenderer(int64_t formId, const std::string &compId)
384 {
385     HILOG_DEBUG("call");
386     ErrCode ret = CheckFormPermission();
387     if (ret != ERR_OK) {
388         HILOG_ERROR("request form permission denied");
389         return ret;
390     }
391     return FormMgrAdapter::GetInstance().ReleaseRenderer(formId, compId);
392 }
393 
RequestPublishForm(Want &want, bool withFormBindingData, std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId)394 ErrCode FormMgrService::RequestPublishForm(Want &want, bool withFormBindingData,
395     std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId)
396 {
397     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
398         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
399         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
400     bool isFormAgent = want.GetBoolParam(Constants::IS_FORM_AGENT, false);
401     HILOG_INFO("isFormAgent:%{public}d", isFormAgent);
402     if (isFormAgent) {
403         ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_AGENT_REQUIRE_FORM);
404         if (ret != ERR_OK) {
405             HILOG_ERROR("request form permission denied");
406             return ret;
407         }
408     } else {
409         if (!CheckCallerIsSystemApp()) {
410             return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
411         }
412 
413         if (!CheckAcrossLocalAccountsPermission()) {
414             HILOG_ERROR("Across local accounts permission failed");
415             return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
416         }
417     }
418     return FormMgrAdapter::GetInstance().RequestPublishForm(want, withFormBindingData, formBindingData, formId);
419 }
420 
SetPublishFormResult(const int64_t formId, Constants::PublishFormResult &errorCodeInfo)421 ErrCode FormMgrService::SetPublishFormResult(const int64_t formId, Constants::PublishFormResult &errorCodeInfo)
422 {
423     HILOG_INFO("call");
424     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_REQUIRE_FORM);
425     if (ret != ERR_OK) {
426         HILOG_ERROR("request form permission denied");
427         return ret;
428     }
429     return FormMgrAdapter::GetInstance().SetPublishFormResult(formId, errorCodeInfo);
430 }
431 
AcquireAddFormResult(const int64_t formId)432 ErrCode FormMgrService::AcquireAddFormResult(const int64_t formId)
433 {
434     HILOG_INFO("call");
435     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_AGENT_REQUIRE_FORM);
436     if (ret != ERR_OK) {
437         HILOG_ERROR("request form permission denied");
438         return ret;
439     }
440     return FormMgrAdapter::GetInstance().AcquireAddFormResult(formId);
441 }
442 
443 /**
444  * @brief Form visible/invisible notify, send formIds to form manager service.
445  * @param formIds The Id list of the forms to notify.
446  * @param callerToken Caller ability token.
447  * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE.
448  * @return Returns ERR_OK on success, others on failure.
449  */
NotifyWhetherVisibleForms(const std::vector<int64_t> &formIds, const sptr<IRemoteObject> &callerToken, const int32_t formVisibleType)450 int FormMgrService::NotifyWhetherVisibleForms(const std::vector<int64_t> &formIds,
451     const sptr<IRemoteObject> &callerToken, const int32_t formVisibleType)
452 {
453     HILOG_DEBUG("call");
454 
455     ErrCode ret = CheckFormPermission();
456     if (ret != ERR_OK) {
457         HILOG_ERROR("event notify visible permission denied");
458         return ret;
459     }
460     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_NotifyWhetherVisibleForms",
461         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
462     ret = FormMgrAdapter::GetInstance().NotifyWhetherVisibleForms(formIds, callerToken, formVisibleType);
463     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
464     return ret;
465 }
466 
467 /**
468  * @brief Query whether has visible form by tokenId.
469  * @param tokenId Unique identification of application.
470  * @return Returns true if has visible form, false otherwise.
471  */
HasFormVisible(const uint32_t tokenId)472 bool FormMgrService::HasFormVisible(const uint32_t tokenId)
473 {
474     HILOG_DEBUG("call");
475 
476     if (!FormUtil::IsSACall()) {
477         HILOG_ERROR("query form visible with tokenid not a SACall");
478         return false;
479     }
480     return FormMgrAdapter::GetInstance().HasFormVisible(tokenId);
481 }
482 
483 /**
484  * @brief temp form to normal form.
485  * @param formId The Id of the form.
486  * @param callerToken Caller ability token.
487  * @return Returns ERR_OK on success, others on failure.
488  */
CastTempForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)489 int FormMgrService::CastTempForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
490 {
491     HILOG_DEBUG("call");
492 
493     ErrCode ret = CheckFormPermission();
494     if (ret != ERR_OK) {
495         HILOG_ERROR("cast temp form permission denied");
496         return ret;
497     }
498     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
499     if (ret != ERR_OK) {
500         HILOG_ERROR("invalid formId or not under currentActiveUser");
501         return ret;
502     }
503     FormEventInfo eventInfo;
504     eventInfo.formId = formId;
505     FormEventReport::SendSecondFormEvent(FormEventName::CASTTEMP_FORM, HiSysEventType::BEHAVIOR, eventInfo);
506 
507     return FormMgrAdapter::GetInstance().CastTempForm(formId, callerToken);
508 }
509 
510 /**
511  * @brief lifecycle update.
512  * @param formIds formIds of host client.
513  * @param callerToken Caller ability token.
514  * @param updateType update type,enable or disable.
515  * @return Returns true on success, false on failure.
516  */
LifecycleUpdate(const std::vector<int64_t> &formIds, const sptr<IRemoteObject> &callerToken, bool updateType)517 int FormMgrService::LifecycleUpdate(const std::vector<int64_t> &formIds,
518     const sptr<IRemoteObject> &callerToken, bool updateType)
519 {
520     HILOG_INFO("updateType:%{public}d", updateType);
521 
522     ErrCode ret = CheckFormPermission();
523     if (ret != ERR_OK) {
524         HILOG_ERROR("delete form permission denied");
525         return ret;
526     }
527 
528     if (updateType) {
529         return FormMgrAdapter::GetInstance().EnableUpdateForm(formIds, callerToken);
530     } else {
531         return FormMgrAdapter::GetInstance().DisableUpdateForm(formIds, callerToken);
532     }
533 }
534 /**
535  * @brief Dump all of form storage infos.
536  * @param formInfos All of form storage infos.
537  * @return Returns ERR_OK on success, others on failure.
538  */
DumpStorageFormInfos(std::string &formInfos)539 int FormMgrService::DumpStorageFormInfos(std::string &formInfos)
540 {
541     if (!CheckCallerIsSystemApp()) {
542         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
543     }
544     return FormMgrAdapter::GetInstance().DumpStorageFormInfos(formInfos);
545 }
546 /**
547  * @brief Dump form info by a bundle name.
548  * @param bundleName The bundle name of form provider.
549  * @param formInfos Form infos.
550  * @return Returns ERR_OK on success, others on failure.
551  */
DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos)552 int FormMgrService::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos)
553 {
554     if (!CheckCallerIsSystemApp()) {
555         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
556     }
557     return FormMgrAdapter::GetInstance().DumpFormInfoByBundleName(bundleName, formInfos);
558 }
559 /**
560  * @brief Dump form info by a bundle name.
561  * @param formId The id of the form.
562  * @param formInfo Form info.
563  * @return Returns ERR_OK on success, others on failure.
564  */
DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo)565 int FormMgrService::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo)
566 {
567     if (!CheckCallerIsSystemApp()) {
568         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
569     }
570     return FormMgrAdapter::GetInstance().DumpFormInfoByFormId(formId, formInfo);
571 }
572 /**
573  * @brief Dump form timer by form id.
574  * @param formId The id of the form.
575  * @param formInfo Form info.
576  * @return Returns ERR_OK on success, others on failure.
577  */
DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService)578 int FormMgrService::DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService)
579 {
580     if (!CheckCallerIsSystemApp()) {
581         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
582     }
583     return FormMgrAdapter::GetInstance().DumpFormTimerByFormId(formId, isTimingService);
584 }
585 
586 /**
587  * @brief Process js message event.
588  * @param formId Indicates the unique id of form.
589  * @param want information passed to supplier.
590  * @param callerToken Caller ability token.
591  * @return Returns true if execute success, false otherwise.
592  */
MessageEvent(const int64_t formId, const Want &want, const sptr<IRemoteObject> &callerToken)593 int FormMgrService::MessageEvent(const int64_t formId, const Want &want, const sptr<IRemoteObject> &callerToken)
594 {
595     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
596         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
597         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
598     ErrCode ret = CheckFormPermission();
599     if (ret != ERR_OK) {
600         HILOG_ERROR("request form permission denied");
601         return ret;
602     }
603     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
604     if (ret != ERR_OK) {
605         HILOG_ERROR("invalid formId or not under currentActiveUser");
606         return ret;
607     }
608     FormEventInfo eventInfo;
609     eventInfo.bundleName = want.GetElement().GetBundleName();
610     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
611     eventInfo.abilityName = want.GetElement().GetAbilityName();
612     std::vector<FormHostRecord> formHostRecords;
613     FormDataMgr::GetInstance().GetFormHostRecord(formId, formHostRecords);
614     if (formHostRecords.size() != 0) {
615         eventInfo.hostBundleName = formHostRecords.begin()->GetHostBundleName();
616     }
617     FormReport::GetInstance().SetDurationStartTime(formId, FormUtil::GetCurrentSteadyClockMillseconds());
618     FormEventReport::SendFormEvent(FormEventName::MESSAGE_EVENT_FORM, HiSysEventType::BEHAVIOR, eventInfo);
619     return FormMgrAdapter::GetInstance().MessageEvent(formId, want, callerToken);
620 }
621 
622 /**
623  * @brief Process js router event.
624  * @param formId Indicates the unique id of form.
625  * @param want the want of the ability to start.
626  * @param callerToken Caller ability token.
627  * @return Returns true if execute success, false otherwise.
628  */
RouterEvent(const int64_t formId, Want &want, const sptr<IRemoteObject> &callerToken)629 int FormMgrService::RouterEvent(const int64_t formId, Want &want, const sptr<IRemoteObject> &callerToken)
630 {
631     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
632         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
633         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
634     ErrCode ret = CheckFormPermission();
635     if (ret != ERR_OK) {
636         HILOG_ERROR("request form permission denied");
637         return ret;
638     }
639     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
640     if (ret != ERR_OK) {
641         HILOG_ERROR("invalid formId or not under currentActiveUser");
642         return ret;
643     }
644     FormEventInfo eventInfo;
645     eventInfo.formId = formId;
646     eventInfo.bundleName = want.GetElement().GetBundleName();
647     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
648     eventInfo.abilityName = want.GetElement().GetAbilityName();
649     std::vector<FormHostRecord> formHostRecords;
650     FormDataMgr::GetInstance().GetFormHostRecord(formId, formHostRecords);
651     if (formHostRecords.size() != 0) {
652         eventInfo.hostBundleName = formHostRecords.begin()->GetHostBundleName();
653     }
654     FormEventReport::SendFormEvent(FormEventName::ROUTE_EVENT_FORM, HiSysEventType::BEHAVIOR, eventInfo);
655     return FormMgrAdapter::GetInstance().RouterEvent(formId, want, callerToken);
656 }
657 
658 /**
659  * @brief Process Background event.
660  * @param formId Indicates the unique id of form.
661  * @param want the want of the ability to start.
662  * @param callerToken Caller ability token.
663  * @return Returns true if execute success, false otherwise.
664  */
BackgroundEvent(const int64_t formId, Want &want, const sptr<IRemoteObject> &callerToken)665 int FormMgrService::BackgroundEvent(const int64_t formId, Want &want, const sptr<IRemoteObject> &callerToken)
666 {
667     HILOG_INFO("begin:%{public}s,publish:%{public}s,end:%{public}s, onKvDataServiceAddTime:%{public}s",
668         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
669         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
670     ErrCode ret = CheckFormPermission();
671     if (ret != ERR_OK) {
672         HILOG_ERROR("request form permission denied");
673         return ret;
674     }
675     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
676     if (ret != ERR_OK) {
677         HILOG_ERROR("the formId is not under currentActiveUser or invalid");
678         return ret;
679     }
680     FormEventInfo eventInfo;
681     eventInfo.formId = formId;
682     eventInfo.bundleName = want.GetElement().GetBundleName();
683     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
684     eventInfo.abilityName = want.GetElement().GetAbilityName();
685     FormEventReport::SendSecondFormEvent(FormEventName::BACKGROUND_EVENT_FORM, HiSysEventType::BEHAVIOR, eventInfo);
686     return FormMgrAdapter::GetInstance().BackgroundEvent(formId, want, callerToken);
687 }
688 
689 /**
690  * @brief Start event for the form manager service.
691  */
OnStart()692 void FormMgrService::OnStart()
693 {
694     if (state_ == ServiceRunningState::STATE_RUNNING) {
695         HILOG_WARN("start service failed since it's running");
696         return;
697     }
698 
699     onStartBeginTime_ = GetCurrentDateTime();
700     HILOG_INFO("start,time:%{public}s", onStartBeginTime_.c_str());
701     ErrCode errCode = Init();
702     if (errCode != ERR_OK) {
703         HILOG_ERROR("init failed,errCode:%{public}08x", errCode);
704         return;
705     }
706 
707     state_ = ServiceRunningState::STATE_RUNNING;
708     // listener for FormDataProxyMgr
709     AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
710 
711 #ifdef MEM_MGR_ENABLE
712     AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
713 #endif // MEM_MGR_ENABLE
714 
715 #ifdef RES_SCHEDULE_ENABLE
716     AddSystemAbilityListener(RES_SCHED_SYS_ABILITY_ID);
717 #endif // RES_SCHEDULE_ENABLE
718     onStartEndTime_ = GetCurrentDateTime();
719     HILOG_INFO("success,time:%{public}s,onKvDataServiceAddTime:%{public}s",
720         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
721 }
722 /**
723  * @brief Stop event for the form manager service.
724  */
OnStop()725 void FormMgrService::OnStop()
726 {
727     HILOG_INFO("stop");
728 
729     state_ = ServiceRunningState::STATE_NOT_START;
730 
731     if (serialQueue_) {
732         serialQueue_.reset();
733     }
734 
735     if (handler_) {
736         handler_.reset();
737     }
738     FormAmsHelper::GetInstance().UnRegisterConfigurationObserver();
739 }
740 
ReadFormConfigXML()741 ErrCode FormMgrService::ReadFormConfigXML()
742 {
743     FormXMLParser parser;
744     int32_t ret = parser.Parse();
745     if (ret != ERR_OK) {
746         HILOG_WARN("parse form config failed, use the default vaule");
747         return ret;
748     }
749     const std::map<std::string, int32_t> &configMap = parser.GetConfigMap();
750     FormDataMgr::GetInstance().SetConfigMap(configMap);
751     return ERR_OK;
752 }
753 
754 
SubscribeSysEventReceiver()755 void FormMgrService::SubscribeSysEventReceiver()
756 {
757     if (formSysEventReceiver_ == nullptr) {
758         EventFwk::MatchingSkills matchingSkills;
759         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_UPDATED);
760         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED);
761         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED);
762         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
763         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SECOND_MOUNTED);
764         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BUNDLE_SCAN_FINISHED);
765         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
766         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON);
767         // init TimerReceiver
768         EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
769         subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
770         formSysEventReceiver_ = std::make_shared<FormSysEventReceiver>(subscribeInfo);
771         formSysEventReceiver_->SetSerialQueue(serialQueue_);
772         EventFwk::CommonEventManager::SubscribeCommonEvent(formSysEventReceiver_);
773     }
774 }
775 
776 /**
777  * @brief initialization of form manager service.
778  */
Init()779 ErrCode FormMgrService::Init()
780 {
781     HILOG_INFO("call");
782     serialQueue_ = std::make_shared<FormSerialQueue>(FORM_MGR_SERVICE_QUEUE.c_str());
783     if (serialQueue_ == nullptr) {
784         HILOG_ERROR("Init failed,null serialQueue_");
785         return ERR_INVALID_OPERATION;
786     }
787 
788     handler_ = std::make_shared<FormEventHandler>(serialQueue_);
789     if (handler_ == nullptr) {
790         HILOG_ERROR("init failed.null handler_");
791         return ERR_INVALID_OPERATION;
792     }
793     FormTaskMgr::GetInstance().SetSerialQueue(serialQueue_);
794     FormAmsHelper::GetInstance().SetSerialQueue(serialQueue_);
795     /* Publish service maybe failed, so we need call this function at the last,
796      * so it can't affect the TDD test program */
797     if (!Publish(DelayedSingleton<FormMgrService>::GetInstance().get())) {
798         FormEventReport::SendFormFailedEvent(FormEventName::INIT_FMS_FAILED, HiSysEventType::FAULT,
799             static_cast<int64_t>(InitFmsFiledErrorType::PUBLISH_SER_FAILED));
800         HILOG_ERROR("FormMgrService::Init Publish failed");
801         return ERR_INVALID_OPERATION;
802     }
803     onStartPublishTime_ = GetCurrentDateTime();
804     HILOG_INFO("FMS onStart publish done, time:%{public}s", onStartPublishTime_.c_str());
805 
806     SubscribeSysEventReceiver();
807 #ifdef MEM_MGR_ENABLE
808     memStatusListener_ = std::make_shared<MemStatusListener>();
809     Memory::MemMgrClient::GetInstance().SubscribeAppState(*memStatusListener_);
810 #endif
811 
812     FormInfoMgr::GetInstance().Start();
813     FormDbCache::GetInstance().Start();
814     FormTimerMgr::GetInstance(); // Init FormTimerMgr
815     FormCacheMgr::GetInstance().Start();
816 
817     formSysEventReceiver_->InitFormInfosAndRegister();
818 
819     // read param form form_config.xml.
820     if (ReadFormConfigXML() != ERR_OK) {
821         HILOG_WARN("parse form config failed, use the default vaule");
822     }
823     FormMgrAdapter::GetInstance().Init();
824     FormAmsHelper::GetInstance().RegisterConfigurationObserver();
825     return ERR_OK;
826 }
827 
CheckFormPermission(const std::string &permission)828 ErrCode FormMgrService::CheckFormPermission(const std::string &permission)
829 {
830     HILOG_DEBUG("call");
831 
832     if (FormUtil::IsSACall()) {
833         return ERR_OK;
834     }
835 
836     // check if system app
837     if (!CheckCallerIsSystemApp()) {
838         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
839     }
840 
841     auto isCallingPerm = FormUtil::VerifyCallingPermission(permission);
842     if (!isCallingPerm) {
843         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
844     }
845 
846     // checks whether the current user is inactive
847     if (!CheckAcrossLocalAccountsPermission()) {
848         HILOG_ERROR("Across local accounts permission failed");
849         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
850     }
851 
852     HILOG_DEBUG("Permission verification ok");
853     return ERR_OK;
854 }
855 
856 /**
857  * @brief Delete the invalid forms.
858  * @param formIds Indicates the ID of the valid forms.
859  * @param callerToken Caller ability token.
860  * @param numFormsDeleted Returns the number of the deleted forms.
861  * @return Returns ERR_OK on success, others on failure.
862  */
DeleteInvalidForms(const std::vector<int64_t> &formIds, const sptr<IRemoteObject> &callerToken, int32_t &numFormsDeleted)863 int FormMgrService::DeleteInvalidForms(const std::vector<int64_t> &formIds,
864     const sptr<IRemoteObject> &callerToken, int32_t &numFormsDeleted)
865 {
866     HILOG_DEBUG("call");
867     ErrCode ret = CheckFormPermission();
868     if (ret != ERR_OK) {
869         HILOG_ERROR("delete form permission denied");
870         return ret;
871     }
872     FormEventInfo eventInfo;
873     FormEventReport::SendFormEvent(FormEventName::DELETE_INVALID_FORM, HiSysEventType::BEHAVIOR, eventInfo);
874     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_DeleteInvalidForms",
875         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
876     ret = FormMgrAdapter::GetInstance().DeleteInvalidForms(formIds, callerToken, numFormsDeleted);
877     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
878     return ret;
879 }
880 
881 /**
882   * @brief Acquire form state info by passing a set of parameters (using Want) to the form provider.
883   * @param want Indicates a set of parameters to be transparently passed to the form provider.
884   * @param callerToken Caller ability token.
885   * @param stateInfo Returns the form's state info of the specify.
886   * @return Returns ERR_OK on success, others on failure.
887   */
AcquireFormState(const Want &want, const sptr<IRemoteObject> &callerToken, FormStateInfo &stateInfo)888 int FormMgrService::AcquireFormState(const Want &want,
889     const sptr<IRemoteObject> &callerToken, FormStateInfo &stateInfo)
890 {
891     HILOG_DEBUG("call");
892     ErrCode ret = CheckFormPermission();
893     if (ret != ERR_OK) {
894         HILOG_ERROR("acquire form state permission denied");
895         return ret;
896     }
897     FormEventInfo eventInfo;
898     eventInfo.bundleName = want.GetElement().GetBundleName();
899     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
900     eventInfo.abilityName = want.GetElement().GetAbilityName();
901     FormEventReport::SendFormEvent(FormEventName::ACQUIREFORMSTATE_FORM, HiSysEventType::BEHAVIOR, eventInfo);
902     return FormMgrAdapter::GetInstance().AcquireFormState(want, callerToken, stateInfo);
903 }
904 
905 /**
906  * @brief Register form router event proxy.
907  * @param formIds Indicates the ID of the forms.
908  * @param callerToken Host client.
909  * @return Returns ERR_OK on success, others on failure.
910  */
RegisterFormRouterProxy(const std::vector<int64_t> &formIds, const sptr<IRemoteObject> &callerToken)911 int FormMgrService::RegisterFormRouterProxy(const std::vector<int64_t> &formIds,
912     const sptr<IRemoteObject> &callerToken)
913 {
914     HILOG_DEBUG("call");
915     ErrCode ret = CheckFormPermission();
916     if (ret != ERR_OK) {
917         HILOG_ERROR("register form router proxy permission denied");
918         return ret;
919     }
920     return FormMgrAdapter::GetInstance().RegisterFormRouterProxy(formIds, callerToken);
921 }
922 
923 /**
924 * @brief Unregister form router event proxy.
925 * @param formIds Indicates the ID of the forms.
926 * @return Returns ERR_OK on success, others on failure.
927 */
UnregisterFormRouterProxy(const std::vector<int64_t> &formIds)928 int FormMgrService::UnregisterFormRouterProxy(const std::vector<int64_t> &formIds)
929 {
930     HILOG_DEBUG("call");
931     ErrCode ret = CheckFormPermission();
932     if (ret != ERR_OK) {
933         HILOG_ERROR("unregister form router proxy permission denied");
934         return ret;
935     }
936     return FormMgrAdapter::GetInstance().UnregisterFormRouterProxy(formIds);
937 }
938 
939 /**
940  * @brief Notify the form is visible or not.
941  * @param formIds Indicates the ID of the forms.
942  * @param isVisible Visible or not.
943  * @param callerToken Host client.
944  * @return Returns ERR_OK on success, others on failure.
945  */
NotifyFormsVisible(const std::vector<int64_t> &formIds, bool isVisible, const sptr<IRemoteObject> &callerToken)946 int FormMgrService::NotifyFormsVisible(const std::vector<int64_t> &formIds,
947     bool isVisible, const sptr<IRemoteObject> &callerToken)
948 {
949     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
950         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
951         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
952     ErrCode ret = CheckFormPermission();
953     if (ret != ERR_OK) {
954         HILOG_ERROR("notify form visible permission denied");
955         return ret;
956     }
957     return FormMgrAdapter::GetInstance().NotifyFormsVisible(formIds, isVisible, callerToken);
958 }
959 
NotifyFormsPrivacyProtected(const std::vector<int64_t> &formIds, bool isProtected, const sptr<IRemoteObject> &callerToken)960 int FormMgrService::NotifyFormsPrivacyProtected(const std::vector<int64_t> &formIds, bool isProtected,
961     const sptr<IRemoteObject> &callerToken)
962 {
963     HILOG_DEBUG("call");
964     ErrCode ret = CheckFormPermission();
965     if (ret != ERR_OK) {
966         HILOG_ERROR("notify form is privacy protected permission denied");
967         return ret;
968     }
969     return ERR_APPEXECFWK_FORM_COMMON_CODE;
970 }
971 
972 /**
973  * @brief Notify the form is enable to be updated or not.
974  * @param formIds Indicates the ID of the forms.
975  * @param isEnableUpdate enable update or not.
976  * @param callerToken Host client.
977  * @return Returns ERR_OK on success, others on failure.
978  */
NotifyFormsEnableUpdate(const std::vector<int64_t> &formIds, bool isEnableUpdate, const sptr<IRemoteObject> &callerToken)979 int FormMgrService::NotifyFormsEnableUpdate(const std::vector<int64_t> &formIds,
980     bool isEnableUpdate, const sptr<IRemoteObject> &callerToken)
981 {
982     HILOG_DEBUG("call");
983     ErrCode ret = CheckFormPermission();
984     if (ret != ERR_OK) {
985         HILOG_ERROR("notify form enable update permission denied");
986         return ret;
987     }
988     return FormMgrAdapter::GetInstance().NotifyFormsEnableUpdate(formIds, isEnableUpdate, callerToken);
989 }
990 
991 /**
992  * @brief Get All FormsInfo.
993  * @param formInfos Return the form information of all forms provided.
994  * @return Returns ERR_OK on success, others on failure.
995  */
GetAllFormsInfo(std::vector<FormInfo> &formInfos)996 int FormMgrService::GetAllFormsInfo(std::vector<FormInfo> &formInfos)
997 {
998     HILOG_DEBUG("call");
999     if (!CheckCallerIsSystemApp()) {
1000         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1001     }
1002     if (!CheckAcrossLocalAccountsPermission()) {
1003         HILOG_ERROR("Across local accounts permission failed");
1004         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1005     }
1006     return FormMgrAdapter::GetInstance().GetAllFormsInfo(formInfos);
1007 }
1008 
1009 /**
1010  * @brief Get forms info by bundle name.
1011  * @param bundleName Application name.
1012  * @param formInfos Return the form information of the specify application name.
1013  * @return Returns ERR_OK on success, others on failure.
1014  */
GetFormsInfoByApp(std::string &bundleName, std::vector<FormInfo> &formInfos)1015 int FormMgrService::GetFormsInfoByApp(std::string &bundleName, std::vector<FormInfo> &formInfos)
1016 {
1017     HILOG_DEBUG("call");
1018     if (!CheckCallerIsSystemApp()) {
1019         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1020     }
1021     if (!CheckAcrossLocalAccountsPermission()) {
1022         HILOG_ERROR("Across local accounts permission failed");
1023         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1024     }
1025     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_GetFormsInfoByApp",
1026         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
1027     ErrCode ret = FormMgrAdapter::GetInstance().GetFormsInfoByApp(bundleName, formInfos);
1028     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
1029     return ret;
1030 }
1031 
1032 /**
1033  * @brief Get forms info by bundle name and module name.
1034  * @param bundleName bundle name.
1035  * @param moduleName Module name of hap.
1036  * @param formInfos Return the forms information of the specify bundle name and module name.
1037  * @return Returns ERR_OK on success, others on failure.
1038  */
GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, std::vector<FormInfo> &formInfos)1039 int FormMgrService::GetFormsInfoByModule(std::string &bundleName, std::string &moduleName,
1040                                          std::vector<FormInfo> &formInfos)
1041 {
1042     HILOG_DEBUG("call");
1043     if (!CheckCallerIsSystemApp()) {
1044         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1045     }
1046     if (!CheckAcrossLocalAccountsPermission()) {
1047         HILOG_ERROR("Across local accounts permission failed");
1048         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1049     }
1050     return FormMgrAdapter::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos);
1051 }
1052 
GetFormsInfoByFilter(const FormInfoFilter &filter, std::vector<FormInfo> &formInfos)1053 int FormMgrService::GetFormsInfoByFilter(const FormInfoFilter &filter, std::vector<FormInfo> &formInfos)
1054 {
1055     HILOG_DEBUG("call");
1056     if (!CheckCallerIsSystemApp()) {
1057         HILOG_ERROR("Need system authority");
1058         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1059     }
1060     if (!CheckAcrossLocalAccountsPermission()) {
1061         HILOG_ERROR("Across local accounts permission failed");
1062         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1063     }
1064     return FormMgrAdapter::GetInstance().GetFormsInfoByFilter(filter, formInfos);
1065 }
1066 
GetFormsInfo(const FormInfoFilter &filter, std::vector<FormInfo> &formInfos)1067 int32_t FormMgrService::GetFormsInfo(const FormInfoFilter &filter, std::vector<FormInfo> &formInfos)
1068 {
1069     HILOG_DEBUG("call");
1070     std::string callerBundleName;
1071     ErrCode ret = FormBmsHelper::GetInstance().GetCallerBundleName(callerBundleName);
1072     if (ret != ERR_OK) {
1073         HILOG_ERROR("get host bundle name failed");
1074         return ret;
1075     }
1076     // retrieve moduleName from filter.
1077     std::string moduleName = filter.moduleName;
1078     if (moduleName.empty()) {
1079         // fulfill formInfos, the process should be the same as GetFormsInfoByApp.
1080         HILOG_INFO("flows to GetFormsInfoByAPP");
1081         return FormMgrAdapter::GetInstance().GetFormsInfoByApp(callerBundleName, formInfos);
1082     }
1083     HILOG_INFO("flows to GetFormsInfoByModule");
1084     return FormMgrAdapter::GetInstance().GetFormsInfoByModule(callerBundleName, moduleName, formInfos);
1085 }
1086 
AcquireFormData(int64_t formId, int64_t requestCode, const sptr<IRemoteObject> &callerToken, AAFwk::WantParams &formData)1087 int32_t FormMgrService::AcquireFormData(int64_t formId, int64_t requestCode, const sptr<IRemoteObject> &callerToken,
1088     AAFwk::WantParams &formData)
1089 {
1090     HILOG_DEBUG("call");
1091     if (formId <= 0) {
1092         HILOG_ERROR("invalid formId");
1093         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1094     }
1095 
1096     if (callerToken == nullptr) {
1097         HILOG_ERROR("null callerToken");
1098         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1099     }
1100 
1101     if (requestCode <= 0) {
1102         HILOG_ERROR("invalid requestCode");
1103         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1104     }
1105 
1106     ErrCode ret = CheckFormPermission();
1107     if (ret != ERR_OK) {
1108         HILOG_ERROR("request form permission denied");
1109         return ret;
1110     }
1111     return FormMgrAdapter::GetInstance().AcquireFormData(formId, requestCode, callerToken, formData);
1112 }
1113 
IsRequestPublishFormSupported()1114 bool FormMgrService::IsRequestPublishFormSupported()
1115 {
1116     HILOG_DEBUG("call");
1117     if (!CheckCallerIsSystemApp()) {
1118         return false;
1119     }
1120     return FormMgrAdapter::GetInstance().IsRequestPublishFormSupported();
1121 }
1122 
StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken)1123 int32_t FormMgrService::StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken)
1124 {
1125     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
1126         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
1127         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
1128     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_START_ABILITIES_FROM_BACKGROUND);
1129     if (ret != ERR_OK) {
1130         HILOG_ERROR("start ability check permission denied");
1131         return ret;
1132     }
1133     // check abilityName and uri to void implicit want.
1134     if (want.GetElement().GetAbilityName().empty() && want.GetUriString().empty()) {
1135         HILOG_ERROR("empty AbilityName and uri");
1136         return ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY;
1137     }
1138     sptr<AAFwk::IAbilityManager> ams = FormAmsHelper::GetInstance().GetAbilityManager();
1139     if (ams == nullptr) {
1140         HILOG_ERROR("fail get abilityMgr");
1141         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1142     }
1143     return ams->StartAbility(want, callerToken, -1, -1);
1144 }
1145 
InitFormShareMgrSerialQueue()1146 void FormMgrService::InitFormShareMgrSerialQueue()
1147 {
1148     DelayedSingleton<FormShareMgr>::GetInstance()->SetSerialQueue(serialQueue_);
1149     DelayedSingleton<FormShareMgr>::GetInstance()->SetEventHandler(handler_);
1150 }
1151 
ShareForm(int64_t formId, const std::string &deviceId, const sptr<IRemoteObject> &callerToken, int64_t requestCode)1152 int32_t FormMgrService::ShareForm(int64_t formId, const std::string &deviceId, const sptr<IRemoteObject> &callerToken,
1153     int64_t requestCode)
1154 {
1155     HILOG_DEBUG("FormMgrService ShareForm call deviceId :%{public}s, formId:%{public}" PRId64 "",
1156         deviceId.c_str(), formId);
1157     if (formId <= 0) {
1158         HILOG_ERROR("invalid formId");
1159         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1160     }
1161 
1162     if (deviceId.empty()) {
1163         HILOG_ERROR("empty deviceId");
1164         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1165     }
1166 
1167     if (callerToken == nullptr) {
1168         HILOG_ERROR("null callerToken");
1169         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1170     }
1171 
1172     if (requestCode <= 0) {
1173         HILOG_ERROR("invalid requestCode");
1174         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1175     }
1176 
1177     auto ret = CheckFormPermission();
1178     if (ret != ERR_OK) {
1179         HILOG_ERROR("share form permission denied");
1180         return ret;
1181     }
1182 
1183     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
1184     if (ret != ERR_OK) {
1185         HILOG_ERROR("invalid formId or not under currentActiveUser");
1186         return ret;
1187     }
1188 
1189     InitFormShareMgrSerialQueue();
1190 
1191     return DelayedSingleton<FormShareMgr>::GetInstance()->ShareForm(formId, deviceId, callerToken, requestCode);
1192 }
1193 
RecvFormShareInfoFromRemote(const FormShareInfo &info)1194 int32_t FormMgrService::RecvFormShareInfoFromRemote(const FormShareInfo &info)
1195 {
1196     HILOG_DEBUG("call");
1197     if (!FormUtil::IsSACall()) {
1198         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1199     }
1200 
1201     InitFormShareMgrSerialQueue();
1202 
1203     return DelayedSingleton<FormShareMgr>::GetInstance()->RecvFormShareInfoFromRemote(info);
1204 }
1205 
Dump(int fd, const std::vector<std::u16string> &args)1206 int FormMgrService::Dump(int fd, const std::vector<std::u16string> &args)
1207 {
1208     if (!CheckFMSReady()) {
1209         HILOG_ERROR("fms not ready");
1210         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1211     }
1212 
1213     std::string result;
1214     Dump(args, result);
1215     int ret = dprintf(fd, "%s\n", result.c_str());
1216     if (ret < 0) {
1217         HILOG_ERROR("format dprintf error");
1218         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1219     }
1220     return ERR_OK;
1221 }
1222 
Dump(const std::vector<std::u16string> &args, std::string &result)1223 void FormMgrService::Dump(const std::vector<std::u16string> &args, std::string &result)
1224 {
1225     DumpKey key;
1226     std::string value;
1227     if (!ParseOption(args, key, value, result)) {
1228         result.append('\n' + FORM_DUMP_HELP);
1229         return;
1230     }
1231 
1232     switch (key) {
1233         case DumpKey::KEY_DUMP_HELP:
1234             return HiDumpHelp(value, result);
1235         case DumpKey::KEY_DUMP_STATIC:
1236             return HiDumpStaticBundleFormInfos(value, result);
1237         case DumpKey::KEY_DUMP_STORAGE:
1238             return HiDumpStorageFormInfos(value, result);
1239         case DumpKey::KEY_DUMP_VISIBLE:
1240             return HiDumpHasFormVisible(value, result);
1241         case DumpKey::KEY_DUMP_TEMPORARY:
1242             return HiDumpTemporaryFormInfos(value, result);
1243         case DumpKey::KEY_DUMP_BY_BUNDLE_NAME:
1244             return HiDumpFormInfoByBundleName(value, result);
1245         case DumpKey::KEY_DUMP_BY_FORM_ID:
1246             return HiDumpFormInfoByFormId(value, result);
1247         case DumpKey::KEY_DUMP_RUNNING:
1248             return HiDumpFormRunningFormInfos(value, result);
1249         case DumpKey::KEY_DUMP_BLOCKED_APPS:
1250             return HiDumpFormBlockedApps(value, result);
1251         default:
1252             result = "error: unknow function.";
1253             return;
1254     }
1255 }
1256 
RegisterPublishFormInterceptor(const sptr<IRemoteObject> &interceptorCallback)1257 int32_t FormMgrService::RegisterPublishFormInterceptor(const sptr<IRemoteObject> &interceptorCallback)
1258 {
1259     HILOG_DEBUG("call");
1260     sptr<IBundleMgr> bundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1261     if (bundleMgr == nullptr) {
1262         HILOG_ERROR("error to get bundleMgr");
1263         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1264     }
1265     // check if system app
1266     auto callingUid = IPCSkeleton::GetCallingUid();
1267     auto isSystemApp = bundleMgr->CheckIsSystemAppByUid(callingUid);
1268     if (!isSystemApp) {
1269         HILOG_ERROR("no permission");
1270         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1271     }
1272     return FormMgrAdapter::GetInstance().RegisterPublishFormInterceptor(interceptorCallback);
1273 }
1274 
UnregisterPublishFormInterceptor(const sptr<IRemoteObject> &interceptorCallback)1275 int32_t FormMgrService::UnregisterPublishFormInterceptor(const sptr<IRemoteObject> &interceptorCallback)
1276 {
1277     HILOG_DEBUG("call");
1278     sptr<IBundleMgr> bundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1279     if (bundleMgr == nullptr) {
1280         HILOG_ERROR("fail get bundleMgr");
1281         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1282     }
1283     // check if system app
1284     auto callingUid = IPCSkeleton::GetCallingUid();
1285     auto isSystemApp = bundleMgr->CheckIsSystemAppByUid(callingUid);
1286     if (!isSystemApp) {
1287         HILOG_ERROR("permission denied");
1288         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1289     }
1290     return FormMgrAdapter::GetInstance().UnregisterPublishFormInterceptor(interceptorCallback);
1291 }
1292 
OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)1293 void FormMgrService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
1294 {
1295 #ifdef RES_SCHEDULE_ENABLE
1296     if (systemAbilityId == RES_SCHED_SYS_ABILITY_ID) {
1297         auto formSystemloadLevelCb = [this](int32_t level) { this->OnSystemloadLevel(level); };
1298         sptr<FormSystemloadListener> formSystemloadListener
1299             = new (std::nothrow) FormSystemloadListener(formSystemloadLevelCb);
1300         ResourceSchedule::ResSchedClient::GetInstance().RegisterSystemloadNotifier(formSystemloadListener);
1301         HILOG_INFO("RegisterSystemloadNotifier for Systemloadlevel change");
1302         return;
1303     }
1304 #endif // RES_SCHEDULE_ENABLE
1305 
1306 #ifdef MEM_MGR_ENABLE
1307     if (systemAbilityId == MEMORY_MANAGER_SA_ID) {
1308         HILOG_INFO("MEMORY_MANAGER_SA start,SubscribeAppState");
1309         Memory::MemMgrClient::GetInstance().SubscribeAppState(*memStatusListener_);
1310         return;
1311     }
1312 #endif // MEM_MGR_ENABLE
1313 
1314     if (systemAbilityId != DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) {
1315         return;
1316     }
1317     onKvDataServiceAddTime_ = GetCurrentDateTime();
1318     FormDataProxyMgr::GetInstance().RetryFailureSubscribes();
1319     HILOG_INFO("FMS KV data service add time:%{public}s", onKvDataServiceAddTime_.c_str());
1320 }
1321 
ParseOption(const std::vector<std::u16string> &args, DumpKey &key, std::string &value, std::string &result)1322 bool FormMgrService::ParseOption(const std::vector<std::u16string> &args, DumpKey &key, std::string &value,
1323     std::string &result)
1324 {
1325     auto size = args.size();
1326     if (size == 0) {
1327         result = "error: must contain arguments.";
1328         return false;
1329     }
1330 
1331     if (size > FORM_DUMP_ARGC_MAX) {
1332         result = "error: arguments numer out of limit.";
1333         return false;
1334     }
1335 
1336     std::string optionKey = Str16ToStr8(args[0]);
1337     auto iter = dumpKeyMap_.find(optionKey);
1338     if (iter == dumpKeyMap_.end()) {
1339         result = "error: unknown option.";
1340         return false;
1341     }
1342 
1343     key = iter->second;
1344 
1345     if (args.size() == FORM_DUMP_ARGC_MAX) {
1346         value = Str16ToStr8(args[1]);
1347     }
1348 
1349     return true;
1350 }
1351 
HiDumpFormRunningFormInfos([[maybe_unused]]const std::string &args, std::string &result)1352 void FormMgrService::HiDumpFormRunningFormInfos([[maybe_unused]]const std::string &args, std::string &result)
1353 {
1354     HILOG_DEBUG("call");
1355     if (!CheckCallerIsSystemApp()) {
1356         return;
1357     }
1358     FormMgrAdapter::GetInstance().DumpFormRunningFormInfos(result);
1359 }
1360 
HiDumpHelp([[maybe_unused]] const std::string &args, std::string &result)1361 void FormMgrService::HiDumpHelp([[maybe_unused]] const std::string &args, std::string &result)
1362 {
1363     result = FORM_DUMP_HELP;
1364 }
1365 
HiDumpStorageFormInfos([[maybe_unused]] const std::string &args, std::string &result)1366 void FormMgrService::HiDumpStorageFormInfos([[maybe_unused]] const std::string &args, std::string &result)
1367 {
1368     DumpStorageFormInfos(result);
1369 }
1370 
HiDumpTemporaryFormInfos([[maybe_unused]] const std::string &args, std::string &result)1371 void FormMgrService::HiDumpTemporaryFormInfos([[maybe_unused]] const std::string &args, std::string &result)
1372 {
1373     if (!CheckCallerIsSystemApp()) {
1374         return;
1375     }
1376     FormMgrAdapter::GetInstance().DumpTemporaryFormInfos(result);
1377 }
1378 
HiDumpStaticBundleFormInfos([[maybe_unused]] const std::string &args, std::string &result)1379 void FormMgrService::HiDumpStaticBundleFormInfos([[maybe_unused]] const std::string &args, std::string &result)
1380 {
1381     if (!CheckCallerIsSystemApp()) {
1382         return;
1383     }
1384     FormMgrAdapter::GetInstance().DumpStaticBundleFormInfos(result);
1385 }
1386 
HiDumpFormInfoByBundleName(const std::string &args, std::string &result)1387 void FormMgrService::HiDumpFormInfoByBundleName(const std::string &args, std::string &result)
1388 {
1389     if (args.empty()) {
1390         result = "error: request a bundle name.";
1391         return;
1392     }
1393     DumpFormInfoByBundleName(args, result);
1394 }
1395 
HiDumpHasFormVisible(const std::string &args, std::string &result)1396 void FormMgrService::HiDumpHasFormVisible(const std::string &args, std::string &result)
1397 {
1398     if (args.empty()) {
1399         result = "error:request bundle info like bundleName_userId_instIndex.";
1400     }
1401     FormMgrAdapter::GetInstance().DumpHasFormVisible(args, result);
1402 }
1403 
HiDumpFormBlockedApps([[maybe_unused]] const std::string &args, std::string &result)1404 void FormMgrService::HiDumpFormBlockedApps([[maybe_unused]] const std::string &args, std::string &result)
1405 {
1406     if (!CheckCallerIsSystemApp()) {
1407         return;
1408     }
1409     FormTrustMgr::GetInstance().GetUntrustAppNameList(result);
1410 }
1411 
HiDumpFormInfoByFormId(const std::string &args, std::string &result)1412 void FormMgrService::HiDumpFormInfoByFormId(const std::string &args, std::string &result)
1413 {
1414     if (args.empty()) {
1415         result = "error: request a form ID.";
1416         return;
1417     }
1418     int64_t formId = atoll(args.c_str());
1419     if (formId == 0) {
1420         result = "error: form ID is invalid.";
1421         return;
1422     }
1423     DumpFormInfoByFormId(formId, result);
1424 }
1425 
CheckCallerIsSystemApp() const1426 bool FormMgrService::CheckCallerIsSystemApp() const
1427 {
1428     auto callerTokenID = IPCSkeleton::GetCallingFullTokenID();
1429     if (!FormUtil::IsSACall() && !Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(callerTokenID)) {
1430         HILOG_ERROR("The caller not system-app,can't use system-api");
1431         return false;
1432     }
1433     return true;
1434 }
1435 
GetCurrentDateTime()1436 std::string FormMgrService::GetCurrentDateTime()
1437 {
1438     auto cTimeNow = std::chrono::system_clock::now();
1439     auto microPart = std::chrono::duration_cast<std::chrono::milliseconds>(
1440         cTimeNow.time_since_epoch()).count() % 1000;
1441     std::time_t t1 = std::chrono::system_clock::to_time_t(cTimeNow);
1442     char buf[32];
1443     std::tm t2;
1444     localtime_r(&t1, &t2);
1445     (void)strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S.", &t2);
1446     std::stringstream ss;
1447     ss << buf << std::setw(MILLISECOND_WIDTH) << std::setfill(MILLISECOND_FILLCHAR) << microPart;
1448     return ss.str();
1449 }
1450 
CheckAcrossLocalAccountsPermission() const1451 bool FormMgrService::CheckAcrossLocalAccountsPermission() const
1452 {
1453     // checks whether the current user is inactive
1454     int callingUid = IPCSkeleton::GetCallingUid();
1455     int32_t userId = callingUid / Constants::CALLING_UID_TRANSFORM_DIVISOR;
1456     int32_t currentActiveUserId = FormUtil::GetCurrentAccountId();
1457     if (userId != currentActiveUserId) {
1458         HILOG_INFO("currentActiveUserId:%{public}d, userId:%{public}d", currentActiveUserId, userId);
1459         bool isCallingPermAccount =
1460             FormUtil::VerifyCallingPermission(AppExecFwk::Constants::PERMISSION_INTERACT_ACROSS_LOCAL_ACCOUNTS);
1461         if (!isCallingPermAccount) {
1462             HILOG_ERROR("Across local accounts permission failed");
1463             return false;
1464         }
1465     }
1466     return true;
1467 }
1468 
RegisterFormAddObserverByBundle(const std::string bundleName, const sptr<IRemoteObject> &callerToken)1469 ErrCode FormMgrService::RegisterFormAddObserverByBundle(const std::string bundleName,
1470     const sptr<IRemoteObject> &callerToken)
1471 {
1472     HILOG_DEBUG("call");
1473     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1474     if (ret != ERR_OK) {
1475         HILOG_ERROR("register form add observer permission denied");
1476         return ret;
1477     }
1478     return FormMgrAdapter::GetInstance().RegisterFormAddObserverByBundle(bundleName, callerToken);
1479 }
1480 
RegisterFormRemoveObserverByBundle(const std::string bundleName, const sptr<IRemoteObject> &callerToken)1481 ErrCode FormMgrService::RegisterFormRemoveObserverByBundle(const std::string bundleName,
1482     const sptr<IRemoteObject> &callerToken)
1483 {
1484     HILOG_DEBUG("call");
1485     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1486     if (ret != ERR_OK) {
1487         HILOG_ERROR("register form remove observer permission denied");
1488         return ret;
1489     }
1490     return FormMgrAdapter::GetInstance().RegisterFormRemoveObserverByBundle(bundleName, callerToken);
1491 }
1492 
GetFormsCount(bool isTempFormFlag, int32_t &formCount)1493 int32_t FormMgrService::GetFormsCount(bool isTempFormFlag, int32_t &formCount)
1494 {
1495     HILOG_DEBUG("call");
1496     return FormMgrAdapter::GetInstance().GetFormsCount(isTempFormFlag, formCount);
1497 }
1498 
GetHostFormsCount(std::string &bundleName, int32_t &formCount)1499 int32_t FormMgrService::GetHostFormsCount(std::string &bundleName, int32_t &formCount)
1500 {
1501     HILOG_DEBUG("call");
1502     return FormMgrAdapter::GetInstance().GetHostFormsCount(bundleName, formCount);
1503 }
1504 
GetRunningFormInfos(bool isUnusedIncluded, std::vector<RunningFormInfo> &runningFormInfos)1505 ErrCode FormMgrService::GetRunningFormInfos(bool isUnusedIncluded, std::vector<RunningFormInfo> &runningFormInfos)
1506 {
1507     HILOG_DEBUG("call");
1508     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1509     if (ret != ERR_OK) {
1510         HILOG_ERROR("get running form infos permission denied");
1511         return ret;
1512     }
1513     return FormMgrAdapter::GetInstance().GetRunningFormInfos(isUnusedIncluded, runningFormInfos);
1514 }
1515 
GetRunningFormInfosByBundleName( const std::string &bundleName, bool isUnusedIncluded, std::vector<RunningFormInfo> &runningFormInfos)1516 ErrCode FormMgrService::GetRunningFormInfosByBundleName(
1517     const std::string &bundleName, bool isUnusedIncluded, std::vector<RunningFormInfo> &runningFormInfos)
1518 {
1519     HILOG_DEBUG("call");
1520     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1521     if (ret != ERR_OK) {
1522         HILOG_ERROR("get running form infos by bundle name permission denied");
1523         return ret;
1524     }
1525     return FormMgrAdapter::GetInstance().GetRunningFormInfosByBundleName(
1526         bundleName, isUnusedIncluded, runningFormInfos);
1527 }
1528 
GetFormInstancesByFilter(const FormInstancesFilter &formInstancesFilter, std::vector<FormInstance> &formInstances)1529 ErrCode FormMgrService::GetFormInstancesByFilter(const FormInstancesFilter &formInstancesFilter,
1530     std::vector<FormInstance> &formInstances)
1531 {
1532     HILOG_DEBUG("call");
1533     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1534     if (ret != ERR_OK) {
1535         HILOG_ERROR("get form instances by filter permission denied");
1536         return ret;
1537     }
1538     return FormMgrAdapter::GetInstance().GetFormInstancesByFilter(formInstancesFilter, formInstances);
1539 }
1540 
GetFormInstanceById(const int64_t formId, FormInstance &formInstance)1541 ErrCode FormMgrService::GetFormInstanceById(const int64_t formId, FormInstance &formInstance)
1542 {
1543     HILOG_DEBUG("call");
1544     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1545     if (ret != ERR_OK) {
1546         HILOG_ERROR("get form instance by id permission denied");
1547         return ret;
1548     }
1549     return FormMgrAdapter::GetInstance().GetFormInstanceById(formId, formInstance);
1550 }
1551 
GetFormInstanceById(const int64_t formId, bool isUnusedIncluded, FormInstance &formInstance)1552 ErrCode FormMgrService::GetFormInstanceById(const int64_t formId, bool isUnusedIncluded, FormInstance &formInstance)
1553 {
1554     HILOG_DEBUG("call");
1555     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1556     if (ret != ERR_OK) {
1557         HILOG_ERROR("get form instance by id permission denied");
1558         return ret;
1559     }
1560     return FormMgrAdapter::GetInstance().GetFormInstanceById(formId, isUnusedIncluded, formInstance);
1561 }
1562 
RegisterAddObserver(const std::string &bundleName, const sptr<IRemoteObject> &callerToken)1563 ErrCode FormMgrService::RegisterAddObserver(const std::string &bundleName, const sptr<IRemoteObject> &callerToken)
1564 {
1565     HILOG_DEBUG("call");
1566     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1567     if (ret != ERR_OK) {
1568         HILOG_ERROR("register notifyVisible or notifyInVisible observer permission denied");
1569         return ret;
1570     }
1571     return FormMgrAdapter::GetInstance().RegisterAddObserver(bundleName, callerToken);
1572 }
1573 
RegisterRemoveObserver(const std::string &bundleName, const sptr<IRemoteObject> &callerToken)1574 ErrCode FormMgrService::RegisterRemoveObserver(const std::string &bundleName, const sptr<IRemoteObject> &callerToken)
1575 {
1576     HILOG_DEBUG("call");
1577     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1578     if (ret != ERR_OK) {
1579         HILOG_ERROR("unregister notifyVisible or notifyInVisible observer permission denied");
1580         return ret;
1581     }
1582     return FormMgrAdapter::GetInstance().RegisterRemoveObserver(bundleName, callerToken);
1583 }
1584 
UpdateProxyForm(int64_t formId, const FormProviderData &formBindingData, const std::vector<FormDataProxy> &formDataProxies)1585 ErrCode FormMgrService::UpdateProxyForm(int64_t formId, const FormProviderData &formBindingData,
1586     const std::vector<FormDataProxy> &formDataProxies)
1587 {
1588     HILOG_DEBUG("call");
1589     auto callingUid = IPCSkeleton::GetCallingUid();
1590     return FormMgrAdapter::GetInstance().UpdateForm(formId, callingUid, formBindingData, formDataProxies);
1591 }
1592 
RequestPublishProxyForm(Want &want, bool withFormBindingData, std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId, const std::vector<FormDataProxy> &formDataProxies)1593 ErrCode FormMgrService::RequestPublishProxyForm(Want &want, bool withFormBindingData,
1594     std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId,
1595     const std::vector<FormDataProxy> &formDataProxies)
1596 {
1597     HILOG_DEBUG("call");
1598     if (!CheckCallerIsSystemApp()) {
1599         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1600     }
1601 
1602     if (!CheckAcrossLocalAccountsPermission()) {
1603         HILOG_ERROR("Across local accounts permission failed");
1604         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1605     }
1606     return FormMgrAdapter::GetInstance().RequestPublishForm(want, withFormBindingData, formBindingData, formId,
1607         formDataProxies);
1608 }
1609 
RegisterClickEventObserver( const std::string &bundleName, const std::string &formEventType, const sptr<IRemoteObject> &observer)1610 ErrCode FormMgrService::RegisterClickEventObserver(
1611     const std::string &bundleName, const std::string &formEventType, const sptr<IRemoteObject> &observer)
1612 {
1613     HILOG_DEBUG("call");
1614     if (observer == nullptr) {
1615         HILOG_ERROR("empty callerTokenParameter");
1616         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1617     }
1618     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1619     if (ret != ERR_OK) {
1620         HILOG_ERROR("register form add observer permission denied");
1621         return ret;
1622     }
1623     return FormMgrAdapter::GetInstance().RegisterClickEventObserver(bundleName, formEventType, observer);
1624 }
1625 
UnregisterClickEventObserver( const std::string &bundleName, const std::string &formEventType, const sptr<IRemoteObject> &observer)1626 ErrCode FormMgrService::UnregisterClickEventObserver(
1627     const std::string &bundleName, const std::string &formEventType, const sptr<IRemoteObject> &observer)
1628 {
1629     HILOG_DEBUG("call");
1630     if (observer == nullptr) {
1631         HILOG_ERROR("empty callerTokenParameter");
1632         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1633     }
1634     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1635     if (ret != ERR_OK) {
1636         HILOG_ERROR("register form add observer permission denied");
1637         return ret;
1638     }
1639     return FormMgrAdapter::GetInstance().UnregisterClickEventObserver(bundleName, formEventType, observer);
1640 }
1641 
SetFormsRecyclable(const std::vector<int64_t> &formIds)1642 int32_t FormMgrService::SetFormsRecyclable(const std::vector<int64_t> &formIds)
1643 {
1644     HILOG_DEBUG("call");
1645     ErrCode ret = CheckFormPermission();
1646     if (ret != ERR_OK) {
1647         HILOG_ERROR("set forms recyclable permission denied");
1648         return ret;
1649     }
1650     return FormMgrAdapter::GetInstance().SetFormsRecyclable(formIds);
1651 }
1652 
RecycleForms(const std::vector<int64_t> &formIds, const Want &want)1653 int32_t FormMgrService::RecycleForms(const std::vector<int64_t> &formIds, const Want &want)
1654 {
1655     HILOG_DEBUG("call");
1656     ErrCode ret = CheckFormPermission();
1657     if (ret != ERR_OK) {
1658         HILOG_ERROR("recycle forms permission denied");
1659         return ret;
1660     }
1661     return FormMgrAdapter::GetInstance().RecycleForms(formIds, want);
1662 }
1663 
RecoverForms(const std::vector<int64_t> &formIds, const Want &want)1664 int32_t FormMgrService::RecoverForms(const std::vector<int64_t> &formIds, const Want &want)
1665 {
1666     HILOG_DEBUG("call");
1667     ErrCode ret = CheckFormPermission();
1668     if (ret != ERR_OK) {
1669         HILOG_ERROR("recover forms permission denied");
1670         return ret;
1671     }
1672     return FormMgrAdapter::GetInstance().RecoverForms(formIds, want);
1673 }
1674 
UpdateFormLocation(const int64_t &formId, const int32_t &formLocation)1675 ErrCode FormMgrService::UpdateFormLocation(const int64_t &formId, const int32_t &formLocation)
1676 {
1677     HILOG_DEBUG("call");
1678     ErrCode ret = CheckFormPermission();
1679     if (ret != ERR_OK) {
1680         HILOG_ERROR("update formLocation form infos permission denied");
1681         return ret;
1682     }
1683     return FormMgrAdapter::GetInstance().UpdateFormLocation(formId, formLocation);
1684 }
1685 
BatchRefreshForms(const int32_t formRefreshType)1686 ErrCode FormMgrService::BatchRefreshForms(const int32_t formRefreshType)
1687 {
1688     HILOG_DEBUG("call");
1689     ErrCode ret = CheckFormPermission();
1690     if (ret != ERR_OK) {
1691         HILOG_ERROR("batch update forms permission denied");
1692         return ret;
1693     }
1694     return FormMgrAdapter::GetInstance().BatchRefreshForms(formRefreshType);
1695 }
1696 
RequestPublishFormWithSnapshot(Want &want, bool withFormBindingData, std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId)1697 ErrCode FormMgrService::RequestPublishFormWithSnapshot(Want &want, bool withFormBindingData,
1698     std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId)
1699 {
1700     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
1701         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
1702         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
1703 
1704     return FormMgrAdapter::GetInstance().RequestPublishForm(want, withFormBindingData, formBindingData,
1705                                                             formId, {}, false);
1706 }
1707 
1708 #ifdef RES_SCHEDULE_ENABLE
OnSystemloadLevel(int32_t level)1709 void FormMgrService::OnSystemloadLevel(int32_t level)
1710 {
1711     if (level >= SYSTEMLOADLEVEL_TIMERSTOP_THRESHOLD) {
1712         FormMgrAdapter::GetInstance().SetTimerTaskNeeded(false);
1713     } else {
1714         FormMgrAdapter::GetInstance().SetTimerTaskNeeded(true);
1715     }
1716 }
1717 #endif // RES_SCHEDULE_ENABLE
1718 
EnableForms(const std::string bundleName, const bool enable)1719 int32_t FormMgrService::EnableForms(const std::string bundleName, const bool enable)
1720 {
1721     ErrCode ret = CheckFormPermission();
1722     if (ret != ERR_OK) {
1723         HILOG_ERROR("disable forms permission denied");
1724         return ret;
1725     }
1726     return FormMgrAdapter::GetInstance().EnableForms(bundleName, enable);
1727 }
1728 
IsFormBundleForbidden(const std::string &bundleName)1729 bool FormMgrService::IsFormBundleForbidden(const std::string &bundleName)
1730 {
1731     HILOG_DEBUG("call");
1732     if (!CheckCallerIsSystemApp()) {
1733         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1734     }
1735     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_IsFormBundleForbidden",
1736         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
1737     bool result = FormBundleForbidMgr::GetInstance().IsBundleForbidden(bundleName);
1738     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
1739     return result;
1740 }
1741 }  // namespace AppExecFwk
1742 }  // namespace OHOS
1743