• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/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 "ams_mgr/form_ams_helper.h"
29 #include "bms_mgr/form_bms_helper.h"
30 #include "feature/bundle_forbidden/form_bundle_forbid_mgr.h"
31 #include "data_center/form_cache_mgr.h"
32 #include "form_constants.h"
33 #include "data_center/form_data_mgr.h"
34 #include "data_center/form_data_proxy_mgr.h"
35 #include "data_center/database/form_db_cache.h"
36 #include "common/event/form_event_handler.h"
37 #include "common/event/form_event_report.h"
38 #include "data_center/form_info/form_info_mgr.h"
39 #include "form_mgr/form_mgr_adapter.h"
40 #include "form_instance.h"
41 #include "form_mgr_errors.h"
42 #include "common/util/form_serial_queue.h"
43 #include "feature/form_share/form_share_mgr.h"
44 #include "common/timer_mgr/form_timer_mgr.h"
45 #include "common/util/form_trust_mgr.h"
46 #include "common/util/form_util.h"
47 #include "form_xml_parser.h"
48 #include "running_form_info.h"
49 #include "in_process_call_wrapper.h"
50 #include "ipc_skeleton.h"
51 #include "iservice_registry.h"
52 #include "common/util/mem_status_listener.h"
53 #include "os_account_manager.h"
54 #include "permission_constants.h"
55 #include "permission_verification.h"
56 #include "system_ability_definition.h"
57 #include "tokenid_kit.h"
58 #include "hisysevent.h"
59 #include "hitrace_meter.h"
60 #include "xcollie/watchdog.h"
61 #include "xcollie/xcollie.h"
62 #include "xcollie/xcollie_define.h"
63 #include "net_conn_callback_stub.h"
64 #include "net_conn_client.h"
65 #include "net_handle.h"
66 #include "feature/bundle_distributed/form_distributed_mgr.h"
67 #include "feature/bundle_lock/form_bundle_lock_mgr.h"
68 #include "feature/bundle_lock/form_exempt_lock_mgr.h"
69 #include "feature/param_update/param_common_event.h"
70 #include "feature/param_update/param_manager.h"
71 #include "string_wrapper.h"
72 #include "int_wrapper.h"
73 #include "want_params_wrapper.h"
74 #ifdef MEM_MGR_ENABLE
75 #include "mem_mgr_client.h"
76 #endif
77 #include "common/util/form_report.h"
78 #include "iform_host_delegate.h"
79 
80 #ifdef RES_SCHEDULE_ENABLE
81 #include "common/event/system_event/form_systemload_listener.h"
82 #include "res_sched_client.h"
83 #include "res_type.h"
84 #endif // RES_SCHEDULE_ENABLE
85 #include "form_mgr/form_mgr_queue.h"
86 #include "common/util/form_task_common.h"
87 #include "scene_board_judgement.h"
88 #include "form_provider/form_provider_mgr.h"
89 
90 namespace OHOS {
91 namespace AppExecFwk {
92 namespace {
93 const int32_t MAIN_USER_ID = 100;
94 constexpr int MILLISECOND_WIDTH = 3;
95 constexpr char MILLISECOND_FILLCHAR = '0';
96 const int32_t API_TIME_OUT = 5;
97 const int32_t API_TIME_OUT_30S = 30;
98 const int32_t CONDITION_NETWORK = 1;
99 const long FORM_DISCON_NETWORK_CHECK_TIME = 600000; // ms
100 #ifdef RES_SCHEDULE_ENABLE
101 constexpr int32_t SYSTEMLOADLEVEL_TIMERSTOP_THRESHOLD =
102     static_cast<int32_t>(ResourceSchedule::ResType::SystemloadLevel::OVERHEATED);
103 #endif // RES_SCHEDULE_ENABLE
104 }
105 using namespace std::chrono;
106 using namespace OHOS::NetManagerStandard;
107 
108 const bool REGISTER_RESULT =
109     SystemAbility::MakeAndRegisterAbility(DelayedSingleton<FormMgrService>::GetInstance().get());
110 
111 const std::string NAME_FORM_MGR_SERVICE = "FormMgrService";
112 
113 const std::string FORM_MGR_SERVICE_QUEUE = "FormMgrServiceQueue";
114 
115 constexpr int32_t FORM_DUMP_ARGC_MAX = 2;
116 
117 constexpr int32_t FORM_CON_NET_MAX = 100;
118 
119 const std::string FORM_DUMP_HELP = "options list:\n"
120     "  -h, --help                           list available commands\n"
121     "  -b, --bundle-form-info               query all form infos from bundle, Un-added form info will also be dumped\n"
122     "  -v, --visible                        query form visible infos from args like bundleName_userId_instIndex\n"
123     "  -s, --storage                        query form storage info\n"
124     "  -t, --temp                           query temporary form info\n"
125     "  -n  <bundle-name>                    query form info by a bundle name\n"
126     "  -i  <form-id>                        query form info by a form ID\n"
127     "  -r  --running                        query running form info\n"
128     "  -a  --apps-blocked                   query blocked app name list\n";
129 
130 const std::map<std::string, FormMgrService::DumpKey> FormMgrService::dumpKeyMap_ = {
131     {"-h", FormMgrService::DumpKey::KEY_DUMP_HELP},
132     {"--help", FormMgrService::DumpKey::KEY_DUMP_HELP},
133     {"-b", FormMgrService::DumpKey::KEY_DUMP_STATIC},   // *****
134     {"--bundle-form-info", FormMgrService::DumpKey::KEY_DUMP_STATIC},
135     {"-v", FormMgrService::DumpKey::KEY_DUMP_VISIBLE},
136     {"--visible", FormMgrService::DumpKey::KEY_DUMP_VISIBLE},
137     {"-s", FormMgrService::DumpKey::KEY_DUMP_STORAGE},
138     {"--storage", FormMgrService::DumpKey::KEY_DUMP_STORAGE},
139     {"-t", FormMgrService::DumpKey::KEY_DUMP_TEMPORARY},
140     {"--temp", FormMgrService::DumpKey::KEY_DUMP_TEMPORARY},
141     {"-n", FormMgrService::DumpKey::KEY_DUMP_BY_BUNDLE_NAME},
142     {"-i", FormMgrService::DumpKey::KEY_DUMP_BY_FORM_ID},
143     {"-r", FormMgrService::DumpKey::KEY_DUMP_RUNNING},
144     {"--running", FormMgrService::DumpKey::KEY_DUMP_RUNNING},
145     {"-a", FormMgrService::DumpKey::KEY_DUMP_BLOCKED_APPS},
146     {"--apps-blocked", FormMgrService::DumpKey::KEY_DUMP_BLOCKED_APPS},
147 };
148 
FormMgrService()149 FormMgrService::FormMgrService()
150     : SystemAbility(FORM_MGR_SERVICE_ID, true),
151       state_(ServiceRunningState::STATE_NOT_START),
152       serialQueue_(nullptr)
153 {
154     HILOG_INFO("call");
155 }
156 
~FormMgrService()157 FormMgrService::~FormMgrService()
158 {
159     HILOG_INFO("call");
160     if (formSysEventReceiver_ != nullptr) {
161         EventFwk::CommonEventManager::UnSubscribeCommonEvent(formSysEventReceiver_);
162         formSysEventReceiver_ = nullptr;
163         FormBmsHelper::GetInstance().UnregisterBundleEventCallback();
164     }
165 #ifdef MEM_MGR_ENABLE
166     if (memStatusListener_ != nullptr) {
167         Memory::MemMgrClient::GetInstance().UnsubscribeAppState(*memStatusListener_);
168     }
169 #endif
170 }
171 
172 /**
173 * @brief Check form manager service ready.
174 * @return Return true if form manager service Ready; return false otherwise.
175 */
176 
CheckFMSReady()177 bool FormMgrService::CheckFMSReady()
178 {
179     if (state_ != ServiceRunningState::STATE_RUNNING) {
180         return false;
181     }
182 
183     int32_t userId = FormUtil::GetCurrentAccountId();
184     if (userId == Constants::ANY_USERID) {
185         HILOG_ERROR("empty account");
186         return false;
187     }
188     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_CheckFMSReady",
189         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
190     bool result = FormInfoMgr::GetInstance().HasReloadedFormInfos();
191     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
192     return result;
193 }
194 
IsSystemAppForm(const std::string & bundleName)195 bool FormMgrService::IsSystemAppForm(const std::string &bundleName)
196 {
197     HILOG_DEBUG("check %{public}s is system form.", bundleName.c_str());
198 
199     std::vector<FormRecord> formRecords;
200     FormDataMgr::GetInstance().GetFormRecord(bundleName, formRecords);
201     if (formRecords.empty()) {
202         return false;
203     }
204     return formRecords.front().isSystemApp;
205 }
206 
207 /**
208  * @brief Add form with want, send want to form manager service.
209  * @param formId The Id of the forms to add.
210  * @param want The want of the form to add.
211  * @param callerToken Caller ability token.
212  * @param formInfo Form info.
213  * @return Returns ERR_OK on success, others on failure.
214  */
AddForm(const int64_t formId,const Want & want,const sptr<IRemoteObject> & callerToken,FormJsInfo & formInfo)215 int FormMgrService::AddForm(const int64_t formId, const Want &want,
216     const sptr<IRemoteObject> &callerToken, FormJsInfo &formInfo)
217 {
218     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
219         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
220         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
221 
222     ErrCode ret = CheckFormPermission();
223     if (ret != ERR_OK) {
224         HILOG_ERROR("add form permission denied");
225         return ret;
226     }
227     ReportAddFormEvent(formId, want);
228     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_AddForm",
229         API_TIME_OUT_30S, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
230     ret = FormMgrAdapter::GetInstance().AddForm(formId, want, callerToken, formInfo);
231     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
232     HILOG_WARN("add form result:%{public}d, formId:%{public}" PRId64, ret, formId);
233     return ret;
234 }
235 
236 /**
237  * @brief Add form with want, send want to form manager service.
238  * @param want The want of the form to add.
239  * @param runningFormInfo Running form info.
240  * @return Returns ERR_OK on success, others on failure.
241  */
CreateForm(const Want & want,RunningFormInfo & runningFormInfo)242 int FormMgrService::CreateForm(const Want &want, RunningFormInfo &runningFormInfo)
243 {
244     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
245         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
246         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
247 
248     ErrCode ret = CheckFormPermission();
249     if (ret != ERR_OK) {
250         HILOG_ERROR("create form permission denied");
251         return ret;
252     }
253     ReportAddFormEvent(0, want);
254     return FormMgrAdapter::GetInstance().CreateForm(want, runningFormInfo);
255 }
256 
ReportAddFormEvent(const int64_t formId,const Want & want)257 void FormMgrService::ReportAddFormEvent(const int64_t formId, const Want &want)
258 {
259     FormEventInfo eventInfo;
260     eventInfo.formId = formId;
261     eventInfo.bundleName = want.GetElement().GetBundleName();
262     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
263     eventInfo.abilityName = want.GetElement().GetAbilityName();
264     int ret = FormBmsHelper::GetInstance().GetCallerBundleName(eventInfo.hostBundleName);
265     if (ret != ERR_OK || eventInfo.hostBundleName.empty()) {
266         HILOG_ERROR("cannot get host bundle name by uid");
267     }
268     FormEventReport::SendFormEvent(FormEventName::ADD_FORM, HiSysEventType::BEHAVIOR, eventInfo);
269 }
270 
271 /**
272  * @brief Delete forms with formIds, send formIds to form manager service.
273  * @param formId The Id of the forms to delete.
274  * @param callerToken Caller ability token.
275  * @return Returns ERR_OK on success, others on failure.
276  */
DeleteForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)277 int FormMgrService::DeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
278 {
279     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
280         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
281         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
282 
283     ErrCode ret = CheckFormPermission();
284     if (ret != ERR_OK) {
285         HILOG_ERROR("delete form permission denied");
286         FormRecord record;
287         FormDataMgr::GetInstance().GetFormRecord(formId, record);
288         FormEventReport::SendFormFailedEvent(FormEventName::DELETE_FORM_FAILED,
289             formId,
290             record.bundleName,
291             record.formName,
292             static_cast<int32_t>(DeleteFormErrorType::DELETE_NORMAL_FORM_FAILED),
293             ret);
294         return ret;
295     }
296     FormEventInfo eventInfo;
297     eventInfo.formId = formId;
298     std::vector<FormHostRecord> formHostRecords;
299     FormDataMgr::GetInstance().GetFormHostRecord(formId, formHostRecords);
300     if (formHostRecords.size() != 0) {
301         eventInfo.hostBundleName = formHostRecords.begin()->GetHostBundleName();
302     }
303     FormEventReport::SendSecondFormEvent(FormEventName::DELETE_FORM, HiSysEventType::BEHAVIOR, eventInfo);
304     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_DeleteForm",
305         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
306     ret = FormMgrAdapter::GetInstance().DeleteForm(formId, callerToken);
307     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
308     HILOG_WARN("delete form result:%{public}d, formId:%{public}" PRId64, ret, formId);
309     return ret;
310 }
311 
312 /**
313  * @brief Stop rendering form.
314  * @param formId The Id of the forms to delete.
315  * @param compId The compId of the forms to delete.
316  * @return Returns ERR_OK on success, others on failure.
317  */
StopRenderingForm(const int64_t formId,const std::string & compId)318 int FormMgrService::StopRenderingForm(const int64_t formId, const std::string &compId)
319 {
320     ErrCode ret = CheckFormPermission();
321     if (ret != ERR_OK) {
322         HILOG_ERROR("delete form permission denied");
323         return ret;
324     }
325 
326     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
327     if (ret != ERR_OK) {
328         HILOG_ERROR("invalid formId or not under currentActiveUser");
329         return ret;
330     }
331     return FormMgrAdapter::GetInstance().StopRenderingForm(formId, compId);
332 }
333 
334 /**
335  * @brief Release forms with formIds, send formIds to form manager service.
336  * @param formId The Id of the forms to release.
337  * @param callerToken Caller ability token.
338  * @param delCache Delete Cache or not.
339  * @return Returns ERR_OK on success, others on failure.
340  */
ReleaseForm(const int64_t formId,const sptr<IRemoteObject> & callerToken,const bool delCache)341 int FormMgrService::ReleaseForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const bool delCache)
342 {
343     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
344         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
345         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
346 
347     ErrCode ret = CheckFormPermission();
348     if (ret != ERR_OK) {
349         HILOG_ERROR("release form permission denied");
350         return ret;
351     }
352     FormEventInfo eventInfo;
353     eventInfo.formId = formId;
354     FormEventReport::SendSecondFormEvent(FormEventName::RELEASE_FORM, HiSysEventType::BEHAVIOR, eventInfo);
355 
356     return FormMgrAdapter::GetInstance().ReleaseForm(formId, callerToken, delCache);
357 }
358 
359 /**
360  * @brief Update form with formId, send formId to form manager service.
361  * @param formId The Id of the form to update.
362  * @param formBindingData Form binding data.
363  * @return Returns ERR_OK on success, others on failure.
364  */
UpdateForm(const int64_t formId,const FormProviderData & formBindingData)365 int FormMgrService::UpdateForm(const int64_t formId, const FormProviderData &formBindingData)
366 {
367     HILOG_DEBUG("call");
368     auto callingUid = IPCSkeleton::GetCallingUid();
369     return FormMgrAdapter::GetInstance().UpdateForm(formId, callingUid, formBindingData);
370 }
371 
372 /**
373  * @brief Request form with formId and want, send formId and want to form manager service.
374  * @param formId The Id of the form to update.
375  * @param callerToken Caller ability token.
376  * @param want The want of the form to add.
377  * @return Returns ERR_OK on success, others on failure.
378  */
RequestForm(const int64_t formId,const sptr<IRemoteObject> & callerToken,const Want & want)379 int FormMgrService::RequestForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const Want &want)
380 {
381     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
382         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
383         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
384     ErrCode ret = CheckFormPermission();
385     if (ret != ERR_OK) {
386         HILOG_ERROR("request form permission denied");
387         return ret;
388     }
389     FormEventInfo eventInfo;
390     eventInfo.formId = formId;
391     eventInfo.bundleName = want.GetElement().GetBundleName();
392     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
393     eventInfo.abilityName = want.GetElement().GetAbilityName();
394     FormEventReport::SendSecondFormEvent(FormEventName::REQUEST_FORM, HiSysEventType::BEHAVIOR, eventInfo);
395 
396     return FormMgrAdapter::GetInstance().RequestForm(formId, callerToken, want);
397 }
398 
399 /**
400  * @brief set next refresh time.
401  * @param formId The id of the form.
402  * @param nextTime next refresh time.
403  * @return Returns ERR_OK on success, others on failure.
404  */
SetNextRefreshTime(const int64_t formId,const int64_t nextTime)405 int FormMgrService::SetNextRefreshTime(const int64_t formId, const int64_t nextTime)
406 {
407     HILOG_DEBUG("call");
408     FormEventInfo eventInfo;
409     eventInfo.formId = formId;
410     FormEventReport::SendSecondFormEvent(
411         FormEventName::SET_NEXT_REFRESH_TIME_FORM, HiSysEventType::BEHAVIOR, eventInfo);
412 
413     return FormMgrAdapter::GetInstance().SetNextRefreshTime(formId, nextTime);
414 }
415 
ReleaseRenderer(int64_t formId,const std::string & compId)416 int FormMgrService::ReleaseRenderer(int64_t formId, const std::string &compId)
417 {
418     HILOG_DEBUG("call");
419     ErrCode ret = CheckFormPermission();
420     if (ret != ERR_OK) {
421         HILOG_ERROR("request form permission denied");
422         return ret;
423     }
424     return FormMgrAdapter::GetInstance().ReleaseRenderer(formId, compId);
425 }
426 
RequestPublishForm(Want & want,bool withFormBindingData,std::unique_ptr<FormProviderData> & formBindingData,int64_t & formId)427 ErrCode FormMgrService::RequestPublishForm(Want &want, bool withFormBindingData,
428     std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId)
429 {
430     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
431         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
432         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
433     bool isFormAgent = want.GetBoolParam(Constants::IS_FORM_AGENT, false);
434     HILOG_INFO("isFormAgent:%{public}d", isFormAgent);
435     if (isFormAgent) {
436         ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_AGENT_REQUIRE_FORM);
437         if (ret != ERR_OK) {
438             HILOG_ERROR("request form permission denied");
439             return ret;
440         }
441     } else {
442         if (!CheckCallerIsSystemApp()) {
443             return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
444         }
445 
446         if (!CheckAcrossLocalAccountsPermission()) {
447             HILOG_ERROR("Across local accounts permission failed");
448             return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
449         }
450     }
451     std::string bundleName;
452     FormBmsHelper::GetInstance().GetCallerBundleName(bundleName);
453     std::string formName = want.GetStringParam(Constants::PARAM_FORM_NAME_KEY);
454     FormEventReport::SendRequestPublicFormEvent(bundleName, formName);
455     return FormMgrAdapter::GetInstance().RequestPublishForm(want, withFormBindingData, formBindingData, formId);
456 }
457 
SetPublishFormResult(const int64_t formId,Constants::PublishFormResult & errorCodeInfo)458 ErrCode FormMgrService::SetPublishFormResult(const int64_t formId, Constants::PublishFormResult &errorCodeInfo)
459 {
460     HILOG_INFO("call");
461     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_REQUIRE_FORM);
462     if (ret != ERR_OK) {
463         HILOG_ERROR("request form permission denied");
464         return ret;
465     }
466     return FormMgrAdapter::GetInstance().SetPublishFormResult(formId, errorCodeInfo);
467 }
468 
AcquireAddFormResult(const int64_t formId)469 ErrCode FormMgrService::AcquireAddFormResult(const int64_t formId)
470 {
471     HILOG_INFO("call");
472     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_AGENT_REQUIRE_FORM);
473     if (ret != ERR_OK) {
474         HILOG_ERROR("request form permission denied");
475         return ret;
476     }
477     return FormMgrAdapter::GetInstance().AcquireAddFormResult(formId);
478 }
479 
480 /**
481  * @brief Form visible/invisible notify, send formIds to form manager service.
482  * @param formIds The Id list of the forms to notify.
483  * @param callerToken Caller ability token.
484  * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE.
485  * @return Returns ERR_OK on success, others on failure.
486  */
NotifyWhetherVisibleForms(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,const int32_t formVisibleType)487 int FormMgrService::NotifyWhetherVisibleForms(const std::vector<int64_t> &formIds,
488     const sptr<IRemoteObject> &callerToken, const int32_t formVisibleType)
489 {
490     HILOG_DEBUG("call");
491 
492     ErrCode ret = CheckFormPermission();
493     if (ret != ERR_OK) {
494         HILOG_ERROR("event notify visible permission denied");
495         return ret;
496     }
497     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_NotifyWhetherVisibleForms",
498         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
499     ret = FormMgrAdapter::GetInstance().NotifyWhetherVisibleForms(formIds, callerToken, formVisibleType);
500     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
501     return ret;
502 }
503 
504 /**
505  * @brief Query whether has visible form by tokenId.
506  * @param tokenId Unique identification of application.
507  * @return Returns true if has visible form, false otherwise.
508  */
HasFormVisible(const uint32_t tokenId)509 bool FormMgrService::HasFormVisible(const uint32_t tokenId)
510 {
511     HILOG_DEBUG("call");
512 
513     if (!FormUtil::IsSACall()) {
514         HILOG_ERROR("query form visible with tokenid not a SACall");
515         return false;
516     }
517     return FormMgrAdapter::GetInstance().HasFormVisible(tokenId);
518 }
519 
520 /**
521  * @brief temp form to normal form.
522  * @param formId The Id of the form.
523  * @param callerToken Caller ability token.
524  * @return Returns ERR_OK on success, others on failure.
525  */
CastTempForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)526 int FormMgrService::CastTempForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
527 {
528     HILOG_DEBUG("call");
529 
530     ErrCode ret = CheckFormPermission();
531     if (ret != ERR_OK) {
532         HILOG_ERROR("cast temp form permission denied");
533         return ret;
534     }
535     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
536     if (ret != ERR_OK) {
537         HILOG_ERROR("invalid formId or not under currentActiveUser");
538         return ret;
539     }
540     FormEventInfo eventInfo;
541     eventInfo.formId = formId;
542     FormEventReport::SendSecondFormEvent(FormEventName::CASTTEMP_FORM, HiSysEventType::BEHAVIOR, eventInfo);
543 
544     return FormMgrAdapter::GetInstance().CastTempForm(formId, callerToken);
545 }
546 
547 /**
548  * @brief lifecycle update.
549  * @param formIds formIds of host client.
550  * @param callerToken Caller ability token.
551  * @param updateType update type,enable or disable.
552  * @return Returns true on success, false on failure.
553  */
LifecycleUpdate(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,bool updateType)554 int FormMgrService::LifecycleUpdate(const std::vector<int64_t> &formIds,
555     const sptr<IRemoteObject> &callerToken, bool updateType)
556 {
557     HILOG_INFO("updateType:%{public}d", updateType);
558 
559     ErrCode ret = CheckFormPermission();
560     if (ret != ERR_OK) {
561         HILOG_ERROR("delete form permission denied");
562         return ret;
563     }
564 
565     if (updateType) {
566         return FormMgrAdapter::GetInstance().EnableUpdateForm(formIds, callerToken);
567     } else {
568         return FormMgrAdapter::GetInstance().DisableUpdateForm(formIds, callerToken);
569     }
570 }
571 /**
572  * @brief Dump all of form storage infos.
573  * @param formInfos All of form storage infos.
574  * @return Returns ERR_OK on success, others on failure.
575  */
DumpStorageFormInfos(std::string & formInfos)576 int FormMgrService::DumpStorageFormInfos(std::string &formInfos)
577 {
578     if (!CheckCallerIsSystemApp()) {
579         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
580     }
581     return FormMgrAdapter::GetInstance().DumpStorageFormInfos(formInfos);
582 }
583 /**
584  * @brief Dump form info by a bundle name.
585  * @param bundleName The bundle name of form provider.
586  * @param formInfos Form infos.
587  * @return Returns ERR_OK on success, others on failure.
588  */
DumpFormInfoByBundleName(const std::string & bundleName,std::string & formInfos)589 int FormMgrService::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos)
590 {
591     if (!CheckCallerIsSystemApp()) {
592         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
593     }
594     return FormMgrAdapter::GetInstance().DumpFormInfoByBundleName(bundleName, formInfos);
595 }
596 /**
597  * @brief Dump form info by a bundle name.
598  * @param formId The id of the form.
599  * @param formInfo Form info.
600  * @return Returns ERR_OK on success, others on failure.
601  */
DumpFormInfoByFormId(const std::int64_t formId,std::string & formInfo)602 int FormMgrService::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo)
603 {
604     if (!CheckCallerIsSystemApp()) {
605         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
606     }
607     return FormMgrAdapter::GetInstance().DumpFormInfoByFormId(formId, formInfo);
608 }
609 /**
610  * @brief Dump form timer by form id.
611  * @param formId The id of the form.
612  * @param formInfo Form info.
613  * @return Returns ERR_OK on success, others on failure.
614  */
DumpFormTimerByFormId(const std::int64_t formId,std::string & isTimingService)615 int FormMgrService::DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService)
616 {
617     if (!CheckCallerIsSystemApp()) {
618         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
619     }
620     return FormMgrAdapter::GetInstance().DumpFormTimerByFormId(formId, isTimingService);
621 }
622 
623 /**
624  * @brief Process js message event.
625  * @param formId Indicates the unique id of form.
626  * @param want information passed to supplier.
627  * @param callerToken Caller ability token.
628  * @return Returns true if execute success, false otherwise.
629  */
MessageEvent(const int64_t formId,const Want & want,const sptr<IRemoteObject> & callerToken)630 int FormMgrService::MessageEvent(const int64_t formId, const Want &want, const sptr<IRemoteObject> &callerToken)
631 {
632     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
633         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
634         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
635     ErrCode ret = CheckFormPermission();
636     if (ret != ERR_OK) {
637         HILOG_ERROR("request form permission denied");
638         return ret;
639     }
640     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
641     if (ret != ERR_OK) {
642         HILOG_ERROR("invalid formId or not under currentActiveUser");
643         return ret;
644     }
645     FormEventInfo eventInfo;
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     FormReport::GetInstance().SetDurationStartTime(formId, FormUtil::GetCurrentSteadyClockMillseconds());
655     FormEventReport::SendFormEvent(FormEventName::MESSAGE_EVENT_FORM, HiSysEventType::BEHAVIOR, eventInfo);
656     return FormMgrAdapter::GetInstance().MessageEvent(formId, want, callerToken);
657 }
658 
659 /**
660  * @brief Process js router event.
661  * @param formId Indicates the unique id of form.
662  * @param want the want of the ability to start.
663  * @param callerToken Caller ability token.
664  * @return Returns true if execute success, false otherwise.
665  */
RouterEvent(const int64_t formId,Want & want,const sptr<IRemoteObject> & callerToken)666 int FormMgrService::RouterEvent(const int64_t formId, Want &want, const sptr<IRemoteObject> &callerToken)
667 {
668     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
669         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
670         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
671     ErrCode ret = CheckFormPermission();
672     if (ret != ERR_OK) {
673         HILOG_ERROR("request form permission denied");
674         return ret;
675     }
676     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
677     if (ret != ERR_OK) {
678         HILOG_ERROR("invalid formId or not under currentActiveUser");
679         return ret;
680     }
681     FormEventInfo eventInfo;
682     eventInfo.formId = formId;
683     eventInfo.bundleName = want.GetElement().GetBundleName();
684     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
685     eventInfo.abilityName = want.GetElement().GetAbilityName();
686     std::vector<FormHostRecord> formHostRecords;
687     FormDataMgr::GetInstance().GetFormHostRecord(formId, formHostRecords);
688     if (formHostRecords.size() != 0) {
689         eventInfo.hostBundleName = formHostRecords.begin()->GetHostBundleName();
690     }
691     FormEventReport::SendFormEvent(FormEventName::ROUTE_EVENT_FORM, HiSysEventType::BEHAVIOR, eventInfo);
692     return FormMgrAdapter::GetInstance().RouterEvent(formId, want, callerToken);
693 }
694 
695 /**
696  * @brief Process Background event.
697  * @param formId Indicates the unique id of form.
698  * @param want the want of the ability to start.
699  * @param callerToken Caller ability token.
700  * @return Returns true if execute success, false otherwise.
701  */
BackgroundEvent(const int64_t formId,Want & want,const sptr<IRemoteObject> & callerToken)702 int FormMgrService::BackgroundEvent(const int64_t formId, Want &want, const sptr<IRemoteObject> &callerToken)
703 {
704     HILOG_INFO("begin:%{public}s,publish:%{public}s,end:%{public}s, onKvDataServiceAddTime:%{public}s",
705         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
706         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
707     ErrCode ret = CheckFormPermission();
708     if (ret != ERR_OK) {
709         HILOG_ERROR("request form permission denied");
710         return ret;
711     }
712     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
713     if (ret != ERR_OK) {
714         HILOG_ERROR("the formId is not under currentActiveUser or invalid");
715         return ret;
716     }
717     FormEventInfo eventInfo;
718     eventInfo.formId = formId;
719     eventInfo.bundleName = want.GetElement().GetBundleName();
720     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
721     eventInfo.abilityName = want.GetElement().GetAbilityName();
722     FormEventReport::SendSecondFormEvent(FormEventName::BACKGROUND_EVENT_FORM, HiSysEventType::BEHAVIOR, eventInfo);
723     return FormMgrAdapter::GetInstance().BackgroundEvent(formId, want, callerToken);
724 }
725 
726 /**
727  * @brief Start event for the form manager service.
728  */
OnStart()729 void FormMgrService::OnStart()
730 {
731     if (state_ == ServiceRunningState::STATE_RUNNING) {
732         HILOG_WARN("start service failed since it's running");
733         return;
734     }
735 
736     onStartBeginTime_ = GetCurrentDateTime();
737     HILOG_INFO("start,time:%{public}s", onStartBeginTime_.c_str());
738     ErrCode errCode = Init();
739     if (errCode != ERR_OK) {
740         HILOG_ERROR("init failed,errCode:%{public}08x", errCode);
741         return;
742     }
743 
744     state_ = ServiceRunningState::STATE_RUNNING;
745     // listener for FormDataProxyMgr
746     AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
747 
748 #ifdef MEM_MGR_ENABLE
749     AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
750 #endif // MEM_MGR_ENABLE
751 
752 #ifdef RES_SCHEDULE_ENABLE
753     AddSystemAbilityListener(RES_SCHED_SYS_ABILITY_ID);
754 #endif // RES_SCHEDULE_ENABLE
755     onStartEndTime_ = GetCurrentDateTime();
756     HILOG_INFO("success,time:%{public}s,onKvDataServiceAddTime:%{public}s",
757         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
758     FormEventReport::SendDiskUseEvent();
759     FormTimerMgr::GetInstance().StartDiskUseInfoReportTimer();
760 }
761 /**
762  * @brief Stop event for the form manager service.
763  */
OnStop()764 void FormMgrService::OnStop()
765 {
766     HILOG_INFO("stop");
767 
768     state_ = ServiceRunningState::STATE_NOT_START;
769 
770     if (serialQueue_) {
771         serialQueue_.reset();
772     }
773 
774     if (handler_) {
775         handler_.reset();
776     }
777     FormAmsHelper::GetInstance().UnRegisterConfigurationObserver();
778     ParamCommonEvent::GetInstance().UnSubscriberEvent();
779 }
780 
ReadFormConfigXML()781 ErrCode FormMgrService::ReadFormConfigXML()
782 {
783     FormXMLParser parser;
784     int32_t ret = parser.Parse();
785     if (ret != ERR_OK) {
786         HILOG_WARN("parse form config failed, use the default vaule");
787         return ret;
788     }
789     const std::map<std::string, int32_t> &configMap = parser.GetConfigMap();
790     FormDataMgr::GetInstance().SetConfigMap(configMap);
791     return ERR_OK;
792 }
793 
794 
SubscribeSysEventReceiver()795 void FormMgrService::SubscribeSysEventReceiver()
796 {
797     if (formSysEventReceiver_ == nullptr) {
798         EventFwk::MatchingSkills matchingSkills;
799         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_UPDATED);
800         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED);
801         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED);
802         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
803         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SECOND_MOUNTED);
804         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BUNDLE_SCAN_FINISHED);
805         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
806         matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON);
807         // init TimerReceiver
808         EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
809         subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
810         formSysEventReceiver_ = std::make_shared<FormSysEventReceiver>(subscribeInfo);
811         EventFwk::CommonEventManager::SubscribeCommonEvent(formSysEventReceiver_);
812     }
813 }
814 
815 class NetConnCallbackObserver : public NetManagerStandard::NetConnCallbackStub {
816 public:
817     explicit NetConnCallbackObserver(FormMgrService &fmservice);
818     ~NetConnCallbackObserver() override = default;
819     int32_t NetAvailable(sptr<NetManagerStandard::NetHandle> &netHandle) override;
820     int32_t NetCapabilitiesChange(sptr<NetManagerStandard::NetHandle> &netHandle,
821         const sptr<NetManagerStandard::NetAllCapabilities> &netAllCap) override;
822     int32_t NetConnectionPropertiesChange(sptr<NetManagerStandard::NetHandle> &netHandle,
823         const sptr<NetManagerStandard::NetLinkInfo> &info) override;
824     int32_t NetLost(sptr<NetManagerStandard::NetHandle> &netHandle) override;
825     int32_t NetUnavailable() override;
826     int32_t NetBlockStatusChange(sptr<NetManagerStandard::NetHandle> &netHandle, bool blocked) override;
827 
828 private:
829     FormMgrService &fmservice_;
830 };
831 
NetConnCallbackObserver(FormMgrService & fmservice)832 NetConnCallbackObserver::NetConnCallbackObserver(FormMgrService &fmservice):fmservice_(fmservice)
833 {
834 }
835 
NetAvailable(sptr<NetManagerStandard::NetHandle> & netHandle)836 int32_t NetConnCallbackObserver::NetAvailable(sptr<NetManagerStandard::NetHandle> &netHandle)
837 {
838     HILOG_INFO("OnNetworkAvailable");
839     this->fmservice_.SetNetConnect();
840     return ERR_OK;
841 }
842 
NetUnavailable()843 int32_t NetConnCallbackObserver::NetUnavailable()
844 {
845     HILOG_DEBUG("OnNetworkUnavailable");
846     return ERR_OK;
847 }
848 
NetCapabilitiesChange(sptr<NetHandle> & netHandle,const sptr<NetAllCapabilities> & netAllCap)849 int32_t NetConnCallbackObserver::NetCapabilitiesChange(sptr<NetHandle> &netHandle,
850     const sptr<NetAllCapabilities> &netAllCap)
851 {
852     HILOG_DEBUG("OnNetCapabilitiesChange");
853 
854     return ERR_OK;
855 }
856 
NetConnectionPropertiesChange(sptr<NetHandle> & netHandle,const sptr<NetLinkInfo> & info)857 int32_t NetConnCallbackObserver::NetConnectionPropertiesChange(sptr<NetHandle> &netHandle,
858     const sptr<NetLinkInfo> &info)
859 {
860     HILOG_DEBUG("OnNetConnectionPropertiesChange");
861     return ERR_OK;
862 }
863 
NetLost(sptr<NetHandle> & netHandle)864 int32_t NetConnCallbackObserver::NetLost(sptr<NetHandle> &netHandle)
865 {
866     HILOG_INFO("OnNetLost");
867     this->fmservice_.SetDisConnectTypeTime();
868     return ERR_OK;
869 }
870 
NetBlockStatusChange(sptr<NetHandle> & netHandle,bool blocked)871 int32_t NetConnCallbackObserver::NetBlockStatusChange(sptr<NetHandle> &netHandle, bool blocked)
872 {
873     HILOG_DEBUG("OnNetBlockStatusChange");
874     return ERR_OK;
875 }
876 
877 
SubscribeNetConn()878 void FormMgrService::SubscribeNetConn()
879 {
880     HILOG_INFO("Register SubscribeNetConn begin");
881     sptr<NetConnCallbackObserver> defaultNetworkCallback_ = new (std::nothrow) NetConnCallbackObserver(*this);
882     if (defaultNetworkCallback_ == nullptr) {
883         HILOG_ERROR("new operator error.observer is nullptr");
884         return ;
885     }
886     int result = NetConnClient::GetInstance().RegisterNetConnCallback(defaultNetworkCallback_);
887     if (result == ERR_OK) {
888         HILOG_INFO("Register defaultNetworkCallback_ successful");
889         std::list<sptr<NetHandle>> netList;
890         NetConnClient::GetInstance().GetAllNets(netList);
891         if (netList.size() > 0) {
892             SetNetConnect();
893         }
894     } else {
895         HILOG_ERROR("Register defaultNetworkCallback_ failed, netConTime:%{public}d", netConTime);
896         netConTime++;
897         if (netConTime > FORM_CON_NET_MAX) {
898             HILOG_ERROR("Register defaultNetworkCallback_ failed 10 time");
899             return;
900         }
901         PostConnectNetWork();
902     }
903 }
904 
905 /**
906  * @brief initialization of form manager service.
907  */
Init()908 ErrCode FormMgrService::Init()
909 {
910     HILOG_INFO("call");
911     serialQueue_ = std::make_shared<FormSerialQueue>(FORM_MGR_SERVICE_QUEUE.c_str());
912     if (serialQueue_ == nullptr) {
913         HILOG_ERROR("Init failed,null serialQueue_");
914         return ERR_INVALID_OPERATION;
915     }
916 
917     handler_ = std::make_shared<FormEventHandler>(serialQueue_);
918     if (handler_ == nullptr) {
919         HILOG_ERROR("init failed.null handler_");
920         return ERR_INVALID_OPERATION;
921     }
922     /* Publish service maybe failed, so we need call this function at the last,
923      * so it can't affect the TDD test program */
924     if (!Publish(DelayedSingleton<FormMgrService>::GetInstance().get())) {
925         FormEventReport::SendFormFailedEvent(FormEventName::INIT_FMS_FAILED, HiSysEventType::FAULT,
926             static_cast<int64_t>(InitFmsFiledErrorType::PUBLISH_SER_FAILED));
927         HILOG_ERROR("FormMgrService::Init Publish failed");
928         return ERR_INVALID_OPERATION;
929     }
930     onStartPublishTime_ = GetCurrentDateTime();
931     HILOG_INFO("FMS onStart publish done, time:%{public}s", onStartPublishTime_.c_str());
932 
933     SubscribeSysEventReceiver();
934 #ifdef MEM_MGR_ENABLE
935     memStatusListener_ = std::make_shared<MemStatusListener>();
936     Memory::MemMgrClient::GetInstance().SubscribeAppState(*memStatusListener_);
937 #endif
938 
939     FormInfoMgr::GetInstance().Start();
940     FormDbCache::GetInstance().Start();
941     FormTimerMgr::GetInstance(); // Init FormTimerMgr
942     FormCacheMgr::GetInstance().Start();
943     FormDistributedMgr::GetInstance().Start();
944 
945     formSysEventReceiver_->InitFormInfosAndRegister();
946 
947     // read param form form_config.xml.
948     if (ReadFormConfigXML() != ERR_OK) {
949         HILOG_WARN("parse form config failed, use the default vaule");
950     }
951     FormMgrAdapter::GetInstance().Init();
952     FormAmsHelper::GetInstance().RegisterConfigurationObserver();
953     SubscribeNetConn();
954     ParamManager::GetInstance().InitParam();
955     ParamCommonEvent::GetInstance().SubscriberEvent();
956     return ERR_OK;
957 }
958 
CheckFormPermission(const std::string & permission)959 ErrCode FormMgrService::CheckFormPermission(const std::string &permission)
960 {
961     HILOG_DEBUG("call");
962 
963     if (FormUtil::IsSACall()) {
964         return ERR_OK;
965     }
966 
967     // check if system app
968     if (!CheckCallerIsSystemApp()) {
969         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
970     }
971 
972     auto isCallingPerm = FormUtil::VerifyCallingPermission(permission);
973     if (!isCallingPerm) {
974         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
975     }
976 
977     // checks whether the current user is inactive
978     if (!CheckAcrossLocalAccountsPermission()) {
979         HILOG_ERROR("Across local accounts permission failed");
980         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
981     }
982 
983     HILOG_DEBUG("Permission verification ok");
984     return ERR_OK;
985 }
986 
987 /**
988  * @brief Delete the invalid forms.
989  * @param formIds Indicates the ID of the valid forms.
990  * @param callerToken Caller ability token.
991  * @param numFormsDeleted Returns the number of the deleted forms.
992  * @return Returns ERR_OK on success, others on failure.
993  */
DeleteInvalidForms(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,int32_t & numFormsDeleted)994 int FormMgrService::DeleteInvalidForms(const std::vector<int64_t> &formIds,
995     const sptr<IRemoteObject> &callerToken, int32_t &numFormsDeleted)
996 {
997     HILOG_DEBUG("call");
998     ErrCode ret = CheckFormPermission();
999     if (ret != ERR_OK) {
1000         HILOG_ERROR("delete form permission denied");
1001         return ret;
1002     }
1003     FormEventInfo eventInfo;
1004     FormEventReport::SendFormEvent(FormEventName::DELETE_INVALID_FORM, HiSysEventType::BEHAVIOR, eventInfo);
1005     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_DeleteInvalidForms",
1006         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
1007     ret = FormMgrAdapter::GetInstance().DeleteInvalidForms(formIds, callerToken, numFormsDeleted);
1008     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
1009     return ret;
1010 }
1011 
1012 /**
1013   * @brief Acquire form state info by passing a set of parameters (using Want) to the form provider.
1014   * @param want Indicates a set of parameters to be transparently passed to the form provider.
1015   * @param callerToken Caller ability token.
1016   * @param stateInfo Returns the form's state info of the specify.
1017   * @return Returns ERR_OK on success, others on failure.
1018   */
AcquireFormState(const Want & want,const sptr<IRemoteObject> & callerToken,FormStateInfo & stateInfo)1019 int FormMgrService::AcquireFormState(const Want &want,
1020     const sptr<IRemoteObject> &callerToken, FormStateInfo &stateInfo)
1021 {
1022     HILOG_DEBUG("call");
1023     ErrCode ret = CheckFormPermission();
1024     if (ret != ERR_OK) {
1025         HILOG_ERROR("acquire form state permission denied");
1026         return ret;
1027     }
1028     FormEventInfo eventInfo;
1029     eventInfo.bundleName = want.GetElement().GetBundleName();
1030     eventInfo.moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
1031     eventInfo.abilityName = want.GetElement().GetAbilityName();
1032     FormEventReport::SendFormEvent(FormEventName::ACQUIREFORMSTATE_FORM, HiSysEventType::BEHAVIOR, eventInfo);
1033     return FormMgrAdapter::GetInstance().AcquireFormState(want, callerToken, stateInfo);
1034 }
1035 
1036 /**
1037  * @brief Register form router event proxy.
1038  * @param formIds Indicates the ID of the forms.
1039  * @param callerToken Host client.
1040  * @return Returns ERR_OK on success, others on failure.
1041  */
RegisterFormRouterProxy(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken)1042 int FormMgrService::RegisterFormRouterProxy(const std::vector<int64_t> &formIds,
1043     const sptr<IRemoteObject> &callerToken)
1044 {
1045     HILOG_DEBUG("call");
1046     ErrCode ret = CheckFormPermission();
1047     if (ret != ERR_OK) {
1048         HILOG_ERROR("register form router proxy permission denied");
1049         return ret;
1050     }
1051     return FormMgrAdapter::GetInstance().RegisterFormRouterProxy(formIds, callerToken);
1052 }
1053 
1054 /**
1055 * @brief Unregister form router event proxy.
1056 * @param formIds Indicates the ID of the forms.
1057 * @return Returns ERR_OK on success, others on failure.
1058 */
UnregisterFormRouterProxy(const std::vector<int64_t> & formIds)1059 int FormMgrService::UnregisterFormRouterProxy(const std::vector<int64_t> &formIds)
1060 {
1061     HILOG_DEBUG("call");
1062     ErrCode ret = CheckFormPermission();
1063     if (ret != ERR_OK) {
1064         HILOG_ERROR("unregister form router proxy permission denied");
1065         return ret;
1066     }
1067     return FormMgrAdapter::GetInstance().UnregisterFormRouterProxy(formIds);
1068 }
1069 
1070 /**
1071  * @brief Notify the form is visible or not.
1072  * @param formIds Indicates the ID of the forms.
1073  * @param isVisible Visible or not.
1074  * @param callerToken Host client.
1075  * @return Returns ERR_OK on success, others on failure.
1076  */
NotifyFormsVisible(const std::vector<int64_t> & formIds,bool isVisible,const sptr<IRemoteObject> & callerToken)1077 int FormMgrService::NotifyFormsVisible(const std::vector<int64_t> &formIds,
1078     bool isVisible, const sptr<IRemoteObject> &callerToken)
1079 {
1080     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
1081         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
1082         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
1083     ErrCode ret = CheckFormPermission();
1084     if (ret != ERR_OK) {
1085         HILOG_ERROR("notify form visible permission denied");
1086         return ret;
1087     }
1088     return FormMgrAdapter::GetInstance().NotifyFormsVisible(formIds, isVisible, callerToken);
1089 }
1090 
NotifyFormsPrivacyProtected(const std::vector<int64_t> & formIds,bool isProtected,const sptr<IRemoteObject> & callerToken)1091 int FormMgrService::NotifyFormsPrivacyProtected(const std::vector<int64_t> &formIds, bool isProtected,
1092     const sptr<IRemoteObject> &callerToken)
1093 {
1094     HILOG_DEBUG("call");
1095     ErrCode ret = CheckFormPermission();
1096     if (ret != ERR_OK) {
1097         HILOG_ERROR("notify form is privacy protected permission denied");
1098         return ret;
1099     }
1100     return ERR_APPEXECFWK_FORM_COMMON_CODE;
1101 }
1102 
1103 /**
1104  * @brief Notify the form is enable to be updated or not.
1105  * @param formIds Indicates the ID of the forms.
1106  * @param isEnableUpdate enable update or not.
1107  * @param callerToken Host client.
1108  * @return Returns ERR_OK on success, others on failure.
1109  */
NotifyFormsEnableUpdate(const std::vector<int64_t> & formIds,bool isEnableUpdate,const sptr<IRemoteObject> & callerToken)1110 int FormMgrService::NotifyFormsEnableUpdate(const std::vector<int64_t> &formIds,
1111     bool isEnableUpdate, const sptr<IRemoteObject> &callerToken)
1112 {
1113     HILOG_DEBUG("call");
1114     ErrCode ret = CheckFormPermission();
1115     if (ret != ERR_OK) {
1116         HILOG_ERROR("notify form enable update permission denied");
1117         return ret;
1118     }
1119     return FormMgrAdapter::GetInstance().NotifyFormsEnableUpdate(formIds, isEnableUpdate, callerToken);
1120 }
1121 
1122 /**
1123  * @brief Get All FormsInfo.
1124  * @param formInfos Return the form information of all forms provided.
1125  * @return Returns ERR_OK on success, others on failure.
1126  */
GetAllFormsInfo(std::vector<FormInfo> & formInfos)1127 int FormMgrService::GetAllFormsInfo(std::vector<FormInfo> &formInfos)
1128 {
1129     HILOG_DEBUG("call");
1130     if (!CheckCallerIsSystemApp()) {
1131         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1132     }
1133     if (!CheckAcrossLocalAccountsPermission()) {
1134         HILOG_ERROR("Across local accounts permission failed");
1135         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1136     }
1137     return FormMgrAdapter::GetInstance().GetAllFormsInfo(formInfos);
1138 }
1139 
1140 /**
1141  * @brief Get forms info by bundle name.
1142  * @param bundleName Application name.
1143  * @param formInfos Return the form information of the specify application name.
1144  * @return Returns ERR_OK on success, others on failure.
1145  */
GetFormsInfoByApp(std::string & bundleName,std::vector<FormInfo> & formInfos)1146 int FormMgrService::GetFormsInfoByApp(std::string &bundleName, std::vector<FormInfo> &formInfos)
1147 {
1148     HILOG_DEBUG("call");
1149     if (!CheckCallerIsSystemApp()) {
1150         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1151     }
1152     if (!CheckAcrossLocalAccountsPermission()) {
1153         HILOG_ERROR("Across local accounts permission failed");
1154         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1155     }
1156     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_GetFormsInfoByApp",
1157         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
1158     ErrCode ret = FormMgrAdapter::GetInstance().GetFormsInfoByApp(bundleName, formInfos);
1159     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
1160     return ret;
1161 }
1162 
1163 /**
1164  * @brief Get forms info by bundle name and module name.
1165  * @param bundleName bundle name.
1166  * @param moduleName Module name of hap.
1167  * @param formInfos Return the forms information of the specify bundle name and module name.
1168  * @return Returns ERR_OK on success, others on failure.
1169  */
GetFormsInfoByModule(std::string & bundleName,std::string & moduleName,std::vector<FormInfo> & formInfos)1170 int FormMgrService::GetFormsInfoByModule(std::string &bundleName, std::string &moduleName,
1171                                          std::vector<FormInfo> &formInfos)
1172 {
1173     HILOG_DEBUG("call");
1174     if (!CheckCallerIsSystemApp()) {
1175         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1176     }
1177     if (!CheckAcrossLocalAccountsPermission()) {
1178         HILOG_ERROR("Across local accounts permission failed");
1179         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1180     }
1181     return FormMgrAdapter::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos);
1182 }
1183 
GetFormsInfoByFilter(const FormInfoFilter & filter,std::vector<FormInfo> & formInfos)1184 int FormMgrService::GetFormsInfoByFilter(const FormInfoFilter &filter, std::vector<FormInfo> &formInfos)
1185 {
1186     HILOG_DEBUG("call");
1187     if (!CheckCallerIsSystemApp()) {
1188         HILOG_ERROR("Need system authority");
1189         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1190     }
1191     if (!CheckAcrossLocalAccountsPermission()) {
1192         HILOG_ERROR("Across local accounts permission failed");
1193         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1194     }
1195     return FormMgrAdapter::GetInstance().GetFormsInfoByFilter(filter, formInfos);
1196 }
1197 
GetFormsInfo(const FormInfoFilter & filter,std::vector<FormInfo> & formInfos)1198 int32_t FormMgrService::GetFormsInfo(const FormInfoFilter &filter, std::vector<FormInfo> &formInfos)
1199 {
1200     HILOG_DEBUG("call");
1201     std::string callerBundleName;
1202     ErrCode ret = FormBmsHelper::GetInstance().GetCallerBundleName(callerBundleName);
1203     if (ret != ERR_OK) {
1204         HILOG_ERROR("get host bundle name failed");
1205         return ret;
1206     }
1207     // retrieve moduleName from filter.
1208     std::string moduleName = filter.moduleName;
1209     if (moduleName.empty()) {
1210         // fulfill formInfos, the process should be the same as GetFormsInfoByApp.
1211         HILOG_INFO("flows to GetFormsInfoByAPP");
1212         return FormMgrAdapter::GetInstance().GetFormsInfoByApp(callerBundleName, formInfos);
1213     }
1214     HILOG_INFO("flows to GetFormsInfoByModule");
1215     return FormMgrAdapter::GetInstance().GetFormsInfoByModule(callerBundleName, moduleName, formInfos);
1216 }
1217 
GetPublishedFormInfoById(const int64_t formId,RunningFormInfo & formInfo)1218 int32_t FormMgrService::GetPublishedFormInfoById(const int64_t formId, RunningFormInfo &formInfo)
1219 {
1220     HILOG_DEBUG("call");
1221     std::string callerBundleName;
1222     ErrCode ret = FormBmsHelper::GetInstance().GetCallerBundleName(callerBundleName);
1223     if (ret != ERR_OK) {
1224         HILOG_ERROR("get host bundle name failed");
1225         return ret;
1226     }
1227     HILOG_INFO("flows to GetPublishedFormInfoById");
1228     return FormDataMgr::GetInstance().GetPublishedFormInfoById(callerBundleName, formInfo, formId);
1229 }
1230 
GetPublishedFormInfos(std::vector<RunningFormInfo> & formInfos)1231 int32_t FormMgrService::GetPublishedFormInfos(std::vector<RunningFormInfo> &formInfos)
1232 {
1233     HILOG_DEBUG("call");
1234     std::string callerBundleName;
1235     ErrCode ret = FormBmsHelper::GetInstance().GetCallerBundleName(callerBundleName);
1236     if (ret != ERR_OK) {
1237         HILOG_ERROR("get host bundle name failed");
1238         return ret;
1239     }
1240     HILOG_INFO("flows to GetPublishedFormInfos");
1241     return FormDataMgr::GetInstance().GetPublishedFormInfos(callerBundleName, formInfos);
1242 }
1243 
AcquireFormData(int64_t formId,int64_t requestCode,const sptr<IRemoteObject> & callerToken,AAFwk::WantParams & formData)1244 int32_t FormMgrService::AcquireFormData(int64_t formId, int64_t requestCode, const sptr<IRemoteObject> &callerToken,
1245     AAFwk::WantParams &formData)
1246 {
1247     HILOG_DEBUG("call");
1248     if (formId <= 0) {
1249         HILOG_ERROR("invalid formId");
1250         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1251     }
1252 
1253     if (callerToken == nullptr) {
1254         HILOG_ERROR("null callerToken");
1255         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1256     }
1257 
1258     if (requestCode <= 0) {
1259         HILOG_ERROR("invalid requestCode");
1260         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1261     }
1262 
1263     ErrCode ret = CheckFormPermission();
1264     if (ret != ERR_OK) {
1265         HILOG_ERROR("request form permission denied");
1266         return ret;
1267     }
1268     return FormMgrAdapter::GetInstance().AcquireFormData(formId, requestCode, callerToken, formData);
1269 }
1270 
IsRequestPublishFormSupported()1271 bool FormMgrService::IsRequestPublishFormSupported()
1272 {
1273     HILOG_DEBUG("call");
1274     if (!CheckCallerIsSystemApp()) {
1275         return false;
1276     }
1277     return FormMgrAdapter::GetInstance().IsRequestPublishFormSupported();
1278 }
1279 
StartAbility(const Want & want,const sptr<IRemoteObject> & callerToken)1280 int32_t FormMgrService::StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken)
1281 {
1282     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
1283         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
1284         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
1285     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_START_ABILITIES_FROM_BACKGROUND);
1286     if (ret != ERR_OK) {
1287         HILOG_ERROR("start ability check permission denied");
1288         return ret;
1289     }
1290     // check abilityName and uri to void implicit want.
1291     if (want.GetElement().GetAbilityName().empty() && want.GetUriString().empty()) {
1292         HILOG_ERROR("empty AbilityName and uri");
1293         return ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY;
1294     }
1295     sptr<AAFwk::IAbilityManager> ams = FormAmsHelper::GetInstance().GetAbilityManager();
1296     if (ams == nullptr) {
1297         HILOG_ERROR("fail get abilityMgr");
1298         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1299     }
1300     return ams->StartAbility(want, callerToken, -1, -1);
1301 }
1302 
StartAbilityByFms(const Want & want)1303 int32_t FormMgrService::StartAbilityByFms(const Want &want)
1304 {
1305     HILOG_INFO("call");
1306     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1307     std::string dstBundleName = want.GetElement().GetBundleName();
1308     std::string bundleName;
1309     auto ret = FormBmsHelper::GetInstance().GetCallerBundleName(bundleName);
1310     if (ret != ERR_OK) {
1311         HILOG_ERROR("get BundleName failed");
1312         return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED;
1313     }
1314     if (dstBundleName != bundleName) {
1315         HILOG_ERROR("dstBundleName not self");
1316         return ERR_APPEXECFWK_FORM_INVALID_BUNDLENAME;
1317     }
1318     return FormMgrAdapter::GetInstance().StartAbilityByFms(want);
1319 }
1320 
StartAbilityByCrossBundle(const Want & want)1321 int32_t FormMgrService::StartAbilityByCrossBundle(const Want &want)
1322 {
1323     HILOG_INFO("call");
1324     if (!CheckCallerIsSystemApp()) {
1325         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1326     }
1327 
1328     if (!FormUtil::VerifyCallingPermission(AppExecFwk::Constants::PERMISSION_PUBLISH_FORM_CROSS_BUNDLE)) {
1329         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1330     }
1331 
1332     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1333         HILOG_ERROR("capability not support");
1334         return ERR_APPEXECFWK_SYSTEMCAP_ERROR;
1335     }
1336 
1337     return FormMgrAdapter::GetInstance().StartAbilityByFms(want);
1338 }
1339 
InitFormShareMgrSerialQueue()1340 void FormMgrService::InitFormShareMgrSerialQueue()
1341 {
1342     DelayedSingleton<FormShareMgr>::GetInstance()->SetSerialQueue(serialQueue_);
1343     DelayedSingleton<FormShareMgr>::GetInstance()->SetEventHandler(handler_);
1344 }
1345 
ShareForm(int64_t formId,const std::string & deviceId,const sptr<IRemoteObject> & callerToken,int64_t requestCode)1346 int32_t FormMgrService::ShareForm(int64_t formId, const std::string &deviceId, const sptr<IRemoteObject> &callerToken,
1347     int64_t requestCode)
1348 {
1349     HILOG_DEBUG("FormMgrService ShareForm call deviceId :%{public}s, formId:%{public}" PRId64 "",
1350         deviceId.c_str(), formId);
1351     if (formId <= 0) {
1352         HILOG_ERROR("invalid formId");
1353         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1354     }
1355 
1356     if (deviceId.empty()) {
1357         HILOG_ERROR("empty deviceId");
1358         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1359     }
1360 
1361     if (callerToken == nullptr) {
1362         HILOG_ERROR("null callerToken");
1363         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1364     }
1365 
1366     if (requestCode <= 0) {
1367         HILOG_ERROR("invalid requestCode");
1368         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1369     }
1370 
1371     auto ret = CheckFormPermission();
1372     if (ret != ERR_OK) {
1373         HILOG_ERROR("share form permission denied");
1374         return ret;
1375     }
1376 
1377     ret = FormDataMgr::GetInstance().CheckInvalidForm(formId);
1378     if (ret != ERR_OK) {
1379         HILOG_ERROR("invalid formId or not under currentActiveUser");
1380         return ret;
1381     }
1382 
1383     InitFormShareMgrSerialQueue();
1384 
1385     return DelayedSingleton<FormShareMgr>::GetInstance()->ShareForm(formId, deviceId, callerToken, requestCode);
1386 }
1387 
RecvFormShareInfoFromRemote(const FormShareInfo & info)1388 int32_t FormMgrService::RecvFormShareInfoFromRemote(const FormShareInfo &info)
1389 {
1390     HILOG_DEBUG("call");
1391     if (!FormUtil::IsSACall()) {
1392         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1393     }
1394 
1395     InitFormShareMgrSerialQueue();
1396 
1397     return DelayedSingleton<FormShareMgr>::GetInstance()->RecvFormShareInfoFromRemote(info);
1398 }
1399 
Dump(int fd,const std::vector<std::u16string> & args)1400 int FormMgrService::Dump(int fd, const std::vector<std::u16string> &args)
1401 {
1402     if (!CheckFMSReady()) {
1403         HILOG_ERROR("fms not ready");
1404         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1405     }
1406 
1407     std::string result;
1408     Dump(args, result);
1409     int ret = dprintf(fd, "%s\n", result.c_str());
1410     if (ret < 0) {
1411         HILOG_ERROR("format dprintf error");
1412         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1413     }
1414     return ERR_OK;
1415 }
1416 
Dump(const std::vector<std::u16string> & args,std::string & result)1417 void FormMgrService::Dump(const std::vector<std::u16string> &args, std::string &result)
1418 {
1419     DumpKey key;
1420     std::string value;
1421     if (!ParseOption(args, key, value, result)) {
1422         result.append('\n' + FORM_DUMP_HELP);
1423         return;
1424     }
1425 
1426     switch (key) {
1427         case DumpKey::KEY_DUMP_HELP:
1428             return HiDumpHelp(value, result);
1429         case DumpKey::KEY_DUMP_STATIC:
1430             return HiDumpStaticBundleFormInfos(value, result);
1431         case DumpKey::KEY_DUMP_STORAGE:
1432             return HiDumpStorageFormInfos(value, result);
1433         case DumpKey::KEY_DUMP_VISIBLE:
1434             return HiDumpHasFormVisible(value, result);
1435         case DumpKey::KEY_DUMP_TEMPORARY:
1436             return HiDumpTemporaryFormInfos(value, result);
1437         case DumpKey::KEY_DUMP_BY_BUNDLE_NAME:
1438             return HiDumpFormInfoByBundleName(value, result);
1439         case DumpKey::KEY_DUMP_BY_FORM_ID:
1440             return HiDumpFormInfoByFormId(value, result);
1441         case DumpKey::KEY_DUMP_RUNNING:
1442             return HiDumpFormRunningFormInfos(value, result);
1443         case DumpKey::KEY_DUMP_BLOCKED_APPS:
1444             return HiDumpFormBlockedApps(value, result);
1445         default:
1446             result = "error: unknow function.";
1447             return;
1448     }
1449 }
1450 
RegisterPublishFormInterceptor(const sptr<IRemoteObject> & interceptorCallback)1451 int32_t FormMgrService::RegisterPublishFormInterceptor(const sptr<IRemoteObject> &interceptorCallback)
1452 {
1453     HILOG_DEBUG("call");
1454     sptr<IBundleMgr> bundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1455     if (bundleMgr == nullptr) {
1456         HILOG_ERROR("error to get bundleMgr");
1457         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1458     }
1459     // check if system app
1460     auto callingUid = IPCSkeleton::GetCallingUid();
1461     auto isSystemApp = bundleMgr->CheckIsSystemAppByUid(callingUid);
1462     if (!isSystemApp) {
1463         HILOG_ERROR("no permission");
1464         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1465     }
1466     return FormMgrAdapter::GetInstance().RegisterPublishFormInterceptor(interceptorCallback);
1467 }
1468 
UnregisterPublishFormInterceptor(const sptr<IRemoteObject> & interceptorCallback)1469 int32_t FormMgrService::UnregisterPublishFormInterceptor(const sptr<IRemoteObject> &interceptorCallback)
1470 {
1471     HILOG_DEBUG("call");
1472     sptr<IBundleMgr> bundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1473     if (bundleMgr == nullptr) {
1474         HILOG_ERROR("fail get bundleMgr");
1475         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1476     }
1477     // check if system app
1478     auto callingUid = IPCSkeleton::GetCallingUid();
1479     auto isSystemApp = bundleMgr->CheckIsSystemAppByUid(callingUid);
1480     if (!isSystemApp) {
1481         HILOG_ERROR("permission denied");
1482         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1483     }
1484     return FormMgrAdapter::GetInstance().UnregisterPublishFormInterceptor(interceptorCallback);
1485 }
1486 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)1487 void FormMgrService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
1488 {
1489 #ifdef RES_SCHEDULE_ENABLE
1490     if (systemAbilityId == RES_SCHED_SYS_ABILITY_ID) {
1491         auto formSystemloadLevelCb = [this](int32_t level) { this->OnSystemloadLevel(level); };
1492         sptr<FormSystemloadListener> formSystemloadListener
1493             = new (std::nothrow) FormSystemloadListener(formSystemloadLevelCb);
1494         ResourceSchedule::ResSchedClient::GetInstance().RegisterSystemloadNotifier(formSystemloadListener);
1495         HILOG_INFO("RegisterSystemloadNotifier for Systemloadlevel change");
1496         return;
1497     }
1498 #endif // RES_SCHEDULE_ENABLE
1499 
1500 #ifdef MEM_MGR_ENABLE
1501     if (systemAbilityId == MEMORY_MANAGER_SA_ID) {
1502         HILOG_INFO("MEMORY_MANAGER_SA start,SubscribeAppState");
1503         Memory::MemMgrClient::GetInstance().SubscribeAppState(*memStatusListener_);
1504         return;
1505     }
1506 #endif // MEM_MGR_ENABLE
1507 
1508     if (systemAbilityId != DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) {
1509         return;
1510     }
1511     onKvDataServiceAddTime_ = GetCurrentDateTime();
1512     FormDataProxyMgr::GetInstance().RetryFailureSubscribes();
1513     HILOG_INFO("FMS KV data service add time:%{public}s", onKvDataServiceAddTime_.c_str());
1514 }
1515 
ParseOption(const std::vector<std::u16string> & args,DumpKey & key,std::string & value,std::string & result)1516 bool FormMgrService::ParseOption(const std::vector<std::u16string> &args, DumpKey &key, std::string &value,
1517     std::string &result)
1518 {
1519     auto size = args.size();
1520     if (size == 0) {
1521         result = "error: must contain arguments.";
1522         return false;
1523     }
1524 
1525     if (size > FORM_DUMP_ARGC_MAX) {
1526         result = "error: arguments numer out of limit.";
1527         return false;
1528     }
1529 
1530     std::string optionKey = Str16ToStr8(args[0]);
1531     auto iter = dumpKeyMap_.find(optionKey);
1532     if (iter == dumpKeyMap_.end()) {
1533         result = "error: unknown option.";
1534         return false;
1535     }
1536 
1537     key = iter->second;
1538 
1539     if (args.size() == FORM_DUMP_ARGC_MAX) {
1540         value = Str16ToStr8(args[1]);
1541     }
1542 
1543     return true;
1544 }
1545 
HiDumpFormRunningFormInfos(const std::string & args,std::string & result)1546 void FormMgrService::HiDumpFormRunningFormInfos([[maybe_unused]]const std::string &args, std::string &result)
1547 {
1548     HILOG_DEBUG("call");
1549     if (!CheckCallerIsSystemApp()) {
1550         return;
1551     }
1552     FormMgrAdapter::GetInstance().DumpFormRunningFormInfos(result);
1553 }
1554 
HiDumpHelp(const std::string & args,std::string & result)1555 void FormMgrService::HiDumpHelp([[maybe_unused]] const std::string &args, std::string &result)
1556 {
1557     result = FORM_DUMP_HELP;
1558 }
1559 
HiDumpStorageFormInfos(const std::string & args,std::string & result)1560 void FormMgrService::HiDumpStorageFormInfos([[maybe_unused]] const std::string &args, std::string &result)
1561 {
1562     DumpStorageFormInfos(result);
1563 }
1564 
HiDumpTemporaryFormInfos(const std::string & args,std::string & result)1565 void FormMgrService::HiDumpTemporaryFormInfos([[maybe_unused]] const std::string &args, std::string &result)
1566 {
1567     if (!CheckCallerIsSystemApp()) {
1568         return;
1569     }
1570     FormMgrAdapter::GetInstance().DumpTemporaryFormInfos(result);
1571 }
1572 
HiDumpStaticBundleFormInfos(const std::string & args,std::string & result)1573 void FormMgrService::HiDumpStaticBundleFormInfos([[maybe_unused]] const std::string &args, std::string &result)
1574 {
1575     if (!CheckCallerIsSystemApp()) {
1576         return;
1577     }
1578     FormMgrAdapter::GetInstance().DumpStaticBundleFormInfos(result);
1579 }
1580 
HiDumpFormInfoByBundleName(const std::string & args,std::string & result)1581 void FormMgrService::HiDumpFormInfoByBundleName(const std::string &args, std::string &result)
1582 {
1583     if (args.empty()) {
1584         result = "error: request a bundle name.";
1585         return;
1586     }
1587     DumpFormInfoByBundleName(args, result);
1588 }
1589 
HiDumpHasFormVisible(const std::string & args,std::string & result)1590 void FormMgrService::HiDumpHasFormVisible(const std::string &args, std::string &result)
1591 {
1592     if (args.empty()) {
1593         result = "error:request bundle info like bundleName_userId_instIndex.";
1594     }
1595     FormMgrAdapter::GetInstance().DumpHasFormVisible(args, result);
1596 }
1597 
HiDumpFormBlockedApps(const std::string & args,std::string & result)1598 void FormMgrService::HiDumpFormBlockedApps([[maybe_unused]] const std::string &args, std::string &result)
1599 {
1600     if (!CheckCallerIsSystemApp()) {
1601         return;
1602     }
1603     FormTrustMgr::GetInstance().GetUntrustAppNameList(result);
1604 }
1605 
HiDumpFormInfoByFormId(const std::string & args,std::string & result)1606 void FormMgrService::HiDumpFormInfoByFormId(const std::string &args, std::string &result)
1607 {
1608     if (args.empty()) {
1609         result = "error: request a form ID.";
1610         return;
1611     }
1612     int64_t formId = atoll(args.c_str());
1613     if (formId == 0) {
1614         result = "error: form ID is invalid.";
1615         return;
1616     }
1617     DumpFormInfoByFormId(formId, result);
1618 }
1619 
CheckCallerIsSystemApp() const1620 bool FormMgrService::CheckCallerIsSystemApp() const
1621 {
1622     auto callerTokenID = IPCSkeleton::GetCallingFullTokenID();
1623     if (!FormUtil::IsSACall() && !Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(callerTokenID)) {
1624         HILOG_ERROR("The caller not system-app,can't use system-api");
1625         return false;
1626     }
1627     return true;
1628 }
1629 
GetCurrentDateTime()1630 std::string FormMgrService::GetCurrentDateTime()
1631 {
1632     auto cTimeNow = std::chrono::system_clock::now();
1633     auto microPart = std::chrono::duration_cast<std::chrono::milliseconds>(
1634         cTimeNow.time_since_epoch()).count() % 1000;
1635     std::time_t t1 = std::chrono::system_clock::to_time_t(cTimeNow);
1636     char buf[32];
1637     std::tm t2;
1638     localtime_r(&t1, &t2);
1639     (void)strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S.", &t2);
1640     std::stringstream ss;
1641     ss << buf << std::setw(MILLISECOND_WIDTH) << std::setfill(MILLISECOND_FILLCHAR) << microPart;
1642     return ss.str();
1643 }
1644 
CheckAcrossLocalAccountsPermission() const1645 bool FormMgrService::CheckAcrossLocalAccountsPermission() const
1646 {
1647     // checks whether the current user is inactive
1648     int callingUid = IPCSkeleton::GetCallingUid();
1649     int32_t userId = callingUid / Constants::CALLING_UID_TRANSFORM_DIVISOR;
1650     int32_t currentActiveUserId = FormUtil::GetCurrentAccountId();
1651     if (userId != currentActiveUserId) {
1652         HILOG_INFO("currentActiveUserId:%{public}d, userId:%{public}d", currentActiveUserId, userId);
1653         bool isCallingPermAccount =
1654             FormUtil::VerifyCallingPermission(AppExecFwk::Constants::PERMISSION_INTERACT_ACROSS_LOCAL_ACCOUNTS);
1655         if (!isCallingPermAccount) {
1656             HILOG_ERROR("Across local accounts permission failed");
1657             return false;
1658         }
1659     }
1660     return true;
1661 }
1662 
RegisterFormAddObserverByBundle(const std::string bundleName,const sptr<IRemoteObject> & callerToken)1663 ErrCode FormMgrService::RegisterFormAddObserverByBundle(const std::string bundleName,
1664     const sptr<IRemoteObject> &callerToken)
1665 {
1666     HILOG_DEBUG("call");
1667     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1668     if (ret != ERR_OK) {
1669         HILOG_ERROR("register form add observer permission denied");
1670         return ret;
1671     }
1672     return FormMgrAdapter::GetInstance().RegisterFormAddObserverByBundle(bundleName, callerToken);
1673 }
1674 
RegisterFormRemoveObserverByBundle(const std::string bundleName,const sptr<IRemoteObject> & callerToken)1675 ErrCode FormMgrService::RegisterFormRemoveObserverByBundle(const std::string bundleName,
1676     const sptr<IRemoteObject> &callerToken)
1677 {
1678     HILOG_DEBUG("call");
1679     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1680     if (ret != ERR_OK) {
1681         HILOG_ERROR("register form remove observer permission denied");
1682         return ret;
1683     }
1684     return FormMgrAdapter::GetInstance().RegisterFormRemoveObserverByBundle(bundleName, callerToken);
1685 }
1686 
GetFormsCount(bool isTempFormFlag,int32_t & formCount)1687 int32_t FormMgrService::GetFormsCount(bool isTempFormFlag, int32_t &formCount)
1688 {
1689     HILOG_DEBUG("call");
1690     return FormMgrAdapter::GetInstance().GetFormsCount(isTempFormFlag, formCount);
1691 }
1692 
GetHostFormsCount(std::string & bundleName,int32_t & formCount)1693 int32_t FormMgrService::GetHostFormsCount(std::string &bundleName, int32_t &formCount)
1694 {
1695     HILOG_DEBUG("call");
1696     return FormMgrAdapter::GetInstance().GetHostFormsCount(bundleName, formCount);
1697 }
1698 
GetRunningFormInfos(bool isUnusedIncluded,std::vector<RunningFormInfo> & runningFormInfos)1699 ErrCode FormMgrService::GetRunningFormInfos(bool isUnusedIncluded, std::vector<RunningFormInfo> &runningFormInfos)
1700 {
1701     HILOG_DEBUG("call");
1702     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1703     if (ret != ERR_OK) {
1704         HILOG_ERROR("get running form infos permission denied");
1705         return ret;
1706     }
1707     return FormMgrAdapter::GetInstance().GetRunningFormInfos(isUnusedIncluded, runningFormInfos);
1708 }
1709 
GetRunningFormInfosByBundleName(const std::string & bundleName,bool isUnusedIncluded,std::vector<RunningFormInfo> & runningFormInfos)1710 ErrCode FormMgrService::GetRunningFormInfosByBundleName(
1711     const std::string &bundleName, bool isUnusedIncluded, std::vector<RunningFormInfo> &runningFormInfos)
1712 {
1713     HILOG_DEBUG("call");
1714     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1715     if (ret != ERR_OK) {
1716         HILOG_ERROR("get running form infos by bundle name permission denied");
1717         return ret;
1718     }
1719     return FormMgrAdapter::GetInstance().GetRunningFormInfosByBundleName(
1720         bundleName, isUnusedIncluded, runningFormInfos);
1721 }
1722 
GetFormInstancesByFilter(const FormInstancesFilter & formInstancesFilter,std::vector<FormInstance> & formInstances)1723 ErrCode FormMgrService::GetFormInstancesByFilter(const FormInstancesFilter &formInstancesFilter,
1724     std::vector<FormInstance> &formInstances)
1725 {
1726     HILOG_DEBUG("call");
1727     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1728     if (ret != ERR_OK) {
1729         HILOG_ERROR("get form instances by filter permission denied");
1730         return ret;
1731     }
1732     return FormMgrAdapter::GetInstance().GetFormInstancesByFilter(formInstancesFilter, formInstances);
1733 }
1734 
GetFormInstanceById(const int64_t formId,FormInstance & formInstance)1735 ErrCode FormMgrService::GetFormInstanceById(const int64_t formId, FormInstance &formInstance)
1736 {
1737     HILOG_DEBUG("call");
1738     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1739     if (ret != ERR_OK) {
1740         HILOG_ERROR("get form instance by id permission denied");
1741         return ret;
1742     }
1743     return FormMgrAdapter::GetInstance().GetFormInstanceById(formId, formInstance);
1744 }
1745 
GetFormInstanceById(const int64_t formId,bool isUnusedIncluded,FormInstance & formInstance)1746 ErrCode FormMgrService::GetFormInstanceById(const int64_t formId, bool isUnusedIncluded, FormInstance &formInstance)
1747 {
1748     HILOG_DEBUG("call");
1749     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1750     if (ret != ERR_OK) {
1751         HILOG_ERROR("get form instance by id permission denied");
1752         return ret;
1753     }
1754     return FormMgrAdapter::GetInstance().GetFormInstanceById(formId, isUnusedIncluded, formInstance);
1755 }
1756 
RegisterAddObserver(const std::string & bundleName,const sptr<IRemoteObject> & callerToken)1757 ErrCode FormMgrService::RegisterAddObserver(const std::string &bundleName, const sptr<IRemoteObject> &callerToken)
1758 {
1759     HILOG_DEBUG("call");
1760     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1761     if (ret != ERR_OK) {
1762         HILOG_ERROR("register notifyVisible or notifyInVisible observer permission denied");
1763         return ret;
1764     }
1765     return FormMgrAdapter::GetInstance().RegisterAddObserver(bundleName, callerToken);
1766 }
1767 
RegisterRemoveObserver(const std::string & bundleName,const sptr<IRemoteObject> & callerToken)1768 ErrCode FormMgrService::RegisterRemoveObserver(const std::string &bundleName, const sptr<IRemoteObject> &callerToken)
1769 {
1770     HILOG_DEBUG("call");
1771     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1772     if (ret != ERR_OK) {
1773         HILOG_ERROR("unregister notifyVisible or notifyInVisible observer permission denied");
1774         return ret;
1775     }
1776     return FormMgrAdapter::GetInstance().RegisterRemoveObserver(bundleName, callerToken);
1777 }
1778 
UpdateProxyForm(int64_t formId,const FormProviderData & formBindingData,const std::vector<FormDataProxy> & formDataProxies)1779 ErrCode FormMgrService::UpdateProxyForm(int64_t formId, const FormProviderData &formBindingData,
1780     const std::vector<FormDataProxy> &formDataProxies)
1781 {
1782     HILOG_DEBUG("call");
1783     auto callingUid = IPCSkeleton::GetCallingUid();
1784     return FormMgrAdapter::GetInstance().UpdateForm(formId, callingUid, formBindingData, formDataProxies);
1785 }
1786 
RequestPublishProxyForm(Want & want,bool withFormBindingData,std::unique_ptr<FormProviderData> & formBindingData,int64_t & formId,const std::vector<FormDataProxy> & formDataProxies)1787 ErrCode FormMgrService::RequestPublishProxyForm(Want &want, bool withFormBindingData,
1788     std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId,
1789     const std::vector<FormDataProxy> &formDataProxies)
1790 {
1791     HILOG_DEBUG("call");
1792     if (!CheckCallerIsSystemApp()) {
1793         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1794     }
1795 
1796     if (!CheckAcrossLocalAccountsPermission()) {
1797         HILOG_ERROR("Across local accounts permission failed");
1798         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1799     }
1800     return FormMgrAdapter::GetInstance().RequestPublishForm(want, withFormBindingData, formBindingData, formId,
1801         formDataProxies);
1802 }
1803 
RegisterClickEventObserver(const std::string & bundleName,const std::string & formEventType,const sptr<IRemoteObject> & observer)1804 ErrCode FormMgrService::RegisterClickEventObserver(
1805     const std::string &bundleName, const std::string &formEventType, const sptr<IRemoteObject> &observer)
1806 {
1807     HILOG_DEBUG("call");
1808     if (observer == nullptr) {
1809         HILOG_ERROR("empty callerTokenParameter");
1810         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1811     }
1812     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1813     if (ret != ERR_OK) {
1814         HILOG_ERROR("register form add observer permission denied");
1815         return ret;
1816     }
1817     return FormMgrAdapter::GetInstance().RegisterClickEventObserver(bundleName, formEventType, observer);
1818 }
1819 
UnregisterClickEventObserver(const std::string & bundleName,const std::string & formEventType,const sptr<IRemoteObject> & observer)1820 ErrCode FormMgrService::UnregisterClickEventObserver(
1821     const std::string &bundleName, const std::string &formEventType, const sptr<IRemoteObject> &observer)
1822 {
1823     HILOG_DEBUG("call");
1824     if (observer == nullptr) {
1825         HILOG_ERROR("empty callerTokenParameter");
1826         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1827     }
1828     ErrCode ret = CheckFormPermission(AppExecFwk::Constants::PERMISSION_OBSERVE_FORM_RUNNING);
1829     if (ret != ERR_OK) {
1830         HILOG_ERROR("register form add observer permission denied");
1831         return ret;
1832     }
1833     return FormMgrAdapter::GetInstance().UnregisterClickEventObserver(bundleName, formEventType, observer);
1834 }
1835 
SetFormsRecyclable(const std::vector<int64_t> & formIds)1836 int32_t FormMgrService::SetFormsRecyclable(const std::vector<int64_t> &formIds)
1837 {
1838     HILOG_DEBUG("call");
1839     ErrCode ret = CheckFormPermission();
1840     if (ret != ERR_OK) {
1841         HILOG_ERROR("set forms recyclable permission denied");
1842         return ret;
1843     }
1844     return FormMgrAdapter::GetInstance().SetFormsRecyclable(formIds);
1845 }
1846 
RecycleForms(const std::vector<int64_t> & formIds,const Want & want)1847 int32_t FormMgrService::RecycleForms(const std::vector<int64_t> &formIds, const Want &want)
1848 {
1849     HILOG_DEBUG("call");
1850     ErrCode ret = CheckFormPermission();
1851     if (ret != ERR_OK) {
1852         HILOG_ERROR("recycle forms permission denied");
1853         return ret;
1854     }
1855     return FormMgrAdapter::GetInstance().RecycleForms(formIds, want);
1856 }
1857 
RecoverForms(const std::vector<int64_t> & formIds,const Want & want)1858 int32_t FormMgrService::RecoverForms(const std::vector<int64_t> &formIds, const Want &want)
1859 {
1860     HILOG_DEBUG("call");
1861     ErrCode ret = CheckFormPermission();
1862     if (ret != ERR_OK) {
1863         HILOG_ERROR("recover forms permission denied");
1864         return ret;
1865     }
1866     return FormMgrAdapter::GetInstance().RecoverForms(formIds, want);
1867 }
1868 
UpdateFormLocation(const int64_t & formId,const int32_t & formLocation)1869 ErrCode FormMgrService::UpdateFormLocation(const int64_t &formId, const int32_t &formLocation)
1870 {
1871     HILOG_DEBUG("call");
1872     ErrCode ret = CheckFormPermission();
1873     if (ret != ERR_OK) {
1874         HILOG_ERROR("update formLocation form infos permission denied");
1875         return ret;
1876     }
1877     bool isRequestPublishFormWithSnapshot =
1878         requestPublishFormWithSnapshotSet_.find(formId) != requestPublishFormWithSnapshotSet_.end();
1879     return FormMgrAdapter::GetInstance().UpdateFormLocation(formId, formLocation, isRequestPublishFormWithSnapshot);
1880 }
1881 
BatchRefreshForms(const int32_t formRefreshType)1882 ErrCode FormMgrService::BatchRefreshForms(const int32_t formRefreshType)
1883 {
1884     HILOG_DEBUG("call");
1885     ErrCode ret = CheckFormPermission();
1886     if (ret != ERR_OK) {
1887         HILOG_ERROR("batch update forms permission denied");
1888         return ret;
1889     }
1890     return FormMgrAdapter::GetInstance().BatchRefreshForms(formRefreshType);
1891 }
1892 
RequestPublishFormWithSnapshot(Want & want,bool withFormBindingData,std::unique_ptr<FormProviderData> & formBindingData,int64_t & formId)1893 ErrCode FormMgrService::RequestPublishFormWithSnapshot(Want &want, bool withFormBindingData,
1894     std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId)
1895 {
1896     HILOG_INFO("begin:%{public}s, publish:%{public}s, end:%{public}s, onKvDataServiceAddTime:%{public}s",
1897         onStartBeginTime_.c_str(), onStartPublishTime_.c_str(),
1898         onStartEndTime_.c_str(), onKvDataServiceAddTime_.c_str());
1899     std::string bundleName;
1900     FormBmsHelper::GetInstance().GetCallerBundleName(bundleName);
1901     std::string formName = want.GetStringParam(Constants::PARAM_FORM_NAME_KEY);
1902     FormEventReport::SendRequestPublicFormEvent(bundleName, formName, true);
1903     int32_t callingUid = IPCSkeleton::GetCallingUid();
1904     auto ret = FormMgrAdapter::GetInstance().RequestPublishForm(want, withFormBindingData, formBindingData,
1905         formId, {}, false);
1906     if (ret == ERR_OK) {
1907         requestPublishFormWithSnapshotSet_.insert(formId);
1908         auto taskId = std::make_pair((int64_t)TaskType::UPDATE_IS_REQUEST_PUBLISH_FORM_WITH_SNAPSHOT,
1909             static_cast<int64_t>(callingUid));
1910         FormMgrQueue::GetInstance().ScheduleDelayTask(
1911             taskId, IS_FORM_REQUEST_PUBLISH_FORM_TASK_DELAY_TIME,
1912             [this, taskId, formId]() {
1913                 requestPublishFormWithSnapshotSet_.erase(formId);
1914                 FormMgrQueue::GetInstance().CancelDelayTask(taskId);
1915             });
1916     }
1917     return ret;
1918 }
1919 
1920 #ifdef RES_SCHEDULE_ENABLE
OnSystemloadLevel(int32_t level)1921 void FormMgrService::OnSystemloadLevel(int32_t level)
1922 {
1923     if (level >= SYSTEMLOADLEVEL_TIMERSTOP_THRESHOLD) {
1924         FormMgrAdapter::GetInstance().SetTimerTaskNeeded(false);
1925     } else {
1926         FormMgrAdapter::GetInstance().SetTimerTaskNeeded(true);
1927     }
1928 }
1929 #endif // RES_SCHEDULE_ENABLE
1930 
EnableForms(const std::string bundleName,const bool enable)1931 int32_t FormMgrService::EnableForms(const std::string bundleName, const bool enable)
1932 {
1933     ErrCode ret = CheckFormPermission();
1934     if (ret != ERR_OK) {
1935         HILOG_ERROR("disable forms permission denied");
1936         return ret;
1937     }
1938     return FormMgrAdapter::GetInstance().EnableForms(bundleName, enable);
1939 }
1940 
IsFormBundleForbidden(const std::string & bundleName)1941 bool FormMgrService::IsFormBundleForbidden(const std::string &bundleName)
1942 {
1943     HILOG_DEBUG("call");
1944     if (!CheckCallerIsSystemApp()) {
1945         return true;
1946     }
1947     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_IsFormBundleForbidden",
1948         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
1949     bool result = FormBundleForbidMgr::GetInstance().IsBundleForbidden(bundleName);
1950     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
1951     return result;
1952 }
1953 
LockForms(const std::vector<FormLockInfo> & formLockInfos,LockChangeType type)1954 int32_t FormMgrService::LockForms(const std::vector<FormLockInfo> &formLockInfos, LockChangeType type)
1955 {
1956     ErrCode ret = CheckFormPermission();
1957     if (ret != ERR_OK) {
1958         HILOG_ERROR("lock forms permission denied");
1959         return ret;
1960     }
1961 
1962     int32_t retErrCode = ERR_OK;
1963     for (const auto &info : formLockInfos) {
1964         if (type == LockChangeType::SWITCH_CHANGE) {
1965             ret = FormMgrAdapter::GetInstance().SwitchLockForms(info.bundleName, info.userId, info.lock);
1966             if (ret != ERR_OK) {
1967                 HILOG_ERROR("SwitchLockForms failed, bundleName: %{public}s, userId: %{public}d, "
1968                     "lock: %{public}d, ret: %{public}d", info.bundleName.c_str(), info.userId, info.lock, ret);
1969                 retErrCode = ret;
1970             }
1971         } else {
1972             ret = FormMgrAdapter::GetInstance().ProtectLockForms(info.bundleName, info.userId, info.lock);
1973             if (ret != ERR_OK) {
1974                 HILOG_ERROR("ProtectLockForms failed, bundleName: %{public}s, userId: %{public}d, "
1975                     "protect: %{public}d, ret: %{public}d", info.bundleName.c_str(), info.userId, info.lock, ret);
1976                 retErrCode = ret;
1977             }
1978         }
1979     }
1980     return retErrCode;
1981 }
1982 
IsFormBundleProtected(const std::string & bundleName,int64_t formId)1983 bool FormMgrService::IsFormBundleProtected(const std::string &bundleName, int64_t formId)
1984 {
1985     HILOG_DEBUG("call");
1986     if (!CheckCallerIsSystemApp()) {
1987         return true;
1988     }
1989     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_IsFormBundleProtected",
1990         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
1991     bool result = FormBundleLockMgr::GetInstance().IsBundleProtect(bundleName, formId);
1992     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
1993     return result;
1994 }
1995 
IsFormBundleExempt(int64_t formId)1996 bool FormMgrService::IsFormBundleExempt(int64_t formId)
1997 {
1998     HILOG_DEBUG("call");
1999     if (!CheckCallerIsSystemApp()) {
2000         return true;
2001     }
2002     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("FMS_IsFormBundleExempt",
2003         API_TIME_OUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
2004     bool result = FormExemptLockMgr::GetInstance().IsExemptLock(formId);
2005     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
2006     return result;
2007 }
2008 
NotifyFormLocked(const int64_t & formId,bool isLocked)2009 int32_t FormMgrService::NotifyFormLocked(const int64_t &formId, bool isLocked)
2010 {
2011     HILOG_DEBUG("call");
2012     ErrCode ret = CheckFormPermission();
2013     if (ret != ERR_OK) {
2014         HILOG_ERROR("disable forms permission denied");
2015         return ret;
2016     }
2017     return FormMgrAdapter::GetInstance().NotifyFormLocked(formId, isLocked);
2018 }
2019 
UpdateFormSize(const int64_t & formId,float width,float height,float borderWidth)2020 ErrCode FormMgrService::UpdateFormSize(const int64_t &formId, float width, float height, float borderWidth)
2021 {
2022     HILOG_DEBUG("call");
2023     ErrCode ret = CheckFormPermission();
2024     if (ret != ERR_OK) {
2025         HILOG_ERROR("update formSize permission denied");
2026         return ret;
2027     }
2028     return FormMgrAdapter::GetInstance().UpdateFormSize(formId, width, height, borderWidth);
2029 }
2030 
SetNetConnect()2031 void FormMgrService::SetNetConnect()
2032 {
2033     int64_t currentTime = FormUtil::GetCurrentMillisecond();
2034     if ((currentTime - lastNetLostTime_) >= FORM_DISCON_NETWORK_CHECK_TIME) {
2035         FormMgrAdapter::GetInstance().UpdateFormByCondition(CONDITION_NETWORK);
2036     }
2037 }
2038 
SetDisConnectTypeTime()2039 void FormMgrService::SetDisConnectTypeTime()
2040 {
2041     lastNetLostTime_ = FormUtil::GetCurrentMillisecond();
2042 }
2043 
OpenFormEditAbility(const std::string & abilityName,const int64_t & formId,bool isMainPage)2044 ErrCode FormMgrService::OpenFormEditAbility(const std::string &abilityName, const int64_t &formId, bool isMainPage)
2045 {
2046     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2047     int uid = IPCSkeleton::GetCallingUid();
2048     std::string callerName;
2049     ErrCode ret = FormBmsHelper::GetInstance().GetBundleNameByUid(uid, callerName);
2050     if (ret != ERR_OK) {
2051         HILOG_ERROR("Get bundleName by uid failed");
2052         return ret;
2053     }
2054 
2055     RunningFormInfo runningFormInfo;
2056     ret = FormDataMgr::GetInstance().GetRunningFormInfosByFormId(formId, runningFormInfo);
2057     if (ret != ERR_OK) {
2058         HILOG_ERROR("Get running form info by id failed");
2059         return ret;
2060     }
2061 
2062     if (runningFormInfo.bundleName != callerName) {
2063         HILOG_ERROR("check bundleName fialed");
2064         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
2065     }
2066 
2067     if (runningFormInfo.formVisiblity != FormVisibilityType::VISIBLE) {
2068         HILOG_ERROR("check form visibility fialed");
2069         return ERR_APPEXECFWK_FORM_NOT_TRUST;
2070     }
2071 
2072     WantParams wantarams;
2073     if (isMainPage) {
2074         WantParams formInfoParam;
2075         formInfoParam.SetParam("bundleName", String::Box(runningFormInfo.bundleName));
2076         formInfoParam.SetParam("abilityName", String::Box(runningFormInfo.abilityName));
2077         formInfoParam.SetParam("moduleName", String::Box(runningFormInfo.moduleName));
2078         formInfoParam.SetParam("cardDimension", Integer::Box(runningFormInfo.dimension));
2079         formInfoParam.SetParam("cardName", String::Box(runningFormInfo.formName));
2080         formInfoParam.SetParam("cardId", String::Box(std::to_string(formId)));
2081         formInfoParam.SetParam("formConfigAbility", String::Box(abilityName));
2082         wantarams.SetParam("formInfo", WantParamWrapper::Box(formInfoParam));
2083         wantarams.SetParam(Constants::PARMA_REQUEST_METHOD, String::Box(Constants::PARAM_OPEN_FORM_EDIT_VIEW));
2084     } else {
2085         wantarams.SetParam(Constants::PARMA_REQUEST_METHOD, String::Box(Constants::PARAM_OPEN_FORM_EDIT_SEC_PAGE_VIEW));
2086         wantarams.SetParam(Constants::PARAM_SEC_PAGE_ABILITY_NAME, String::Box(abilityName));
2087     }
2088     wantarams.SetParam(Constants::PARAM_PAGE_ROUTER_SERVICE_CODE,
2089         Integer::Box(Constants::PAGE_ROUTER_SERVICE_CODE_FORM_EDIT));
2090 
2091     Want want;
2092     want.SetAction(Constants::FORM_PAGE_ACTION);
2093     want.SetElementName(callerName, abilityName);
2094     want.SetParams(wantarams);
2095     return FormMgrAdapter::GetInstance().StartAbilityByFms(want);
2096 }
PostConnectNetWork()2097 void FormMgrService::PostConnectNetWork()
2098 {
2099     HILOG_DEBUG("start");
2100 
2101     auto connectNetWork = []() {
2102         DelayedSingleton<FormMgrService>::GetInstance()->SubscribeNetConn();
2103     };
2104     FormMgrQueue::GetInstance().ScheduleTask(FORM_CON_NETWORK_DELAY_TIME, connectNetWork);
2105     HILOG_DEBUG("end");
2106 }
RegisterOverflowProxy(const sptr<IRemoteObject> & callerToken)2107 bool FormMgrService::RegisterOverflowProxy(const sptr<IRemoteObject> &callerToken)
2108 {
2109     HILOG_INFO("call");
2110     return FormMgrAdapter::GetInstance().RegisterOverflowProxy(callerToken);
2111 }
2112 
UnregisterOverflowProxy()2113 bool FormMgrService::UnregisterOverflowProxy()
2114 {
2115     HILOG_INFO("call");
2116     return FormMgrAdapter::GetInstance().UnregisterOverflowProxy();
2117 }
2118 
RequestOverflow(const int64_t formId,const OverflowInfo & overflowInfo,bool isOverflow)2119 ErrCode FormMgrService::RequestOverflow(const int64_t formId, const OverflowInfo &overflowInfo, bool isOverflow)
2120 {
2121     HILOG_INFO("call");
2122     int32_t callingUid = IPCSkeleton::GetCallingUid();
2123     return FormMgrAdapter::GetInstance().RequestOverflow(formId, callingUid, overflowInfo, isOverflow);
2124 }
2125 
RegisterChangeSceneAnimationStateProxy(const sptr<IRemoteObject> & callerToken)2126 bool FormMgrService::RegisterChangeSceneAnimationStateProxy(const sptr<IRemoteObject> &callerToken)
2127 {
2128     HILOG_INFO("call");
2129     return FormMgrAdapter::GetInstance().RegisterChangeSceneAnimationStateProxy(callerToken);
2130 }
2131 
UnregisterChangeSceneAnimationStateProxy()2132 bool FormMgrService::UnregisterChangeSceneAnimationStateProxy()
2133 {
2134     HILOG_INFO("call");
2135     return FormMgrAdapter::GetInstance().UnregisterChangeSceneAnimationStateProxy();
2136 }
2137 
ChangeSceneAnimationState(const int64_t formId,int32_t state)2138 ErrCode FormMgrService::ChangeSceneAnimationState(const int64_t formId, int32_t state)
2139 {
2140     HILOG_INFO("call");
2141     int32_t callingUid = IPCSkeleton::GetCallingUid();
2142     return FormMgrAdapter::GetInstance().ChangeSceneAnimationState(formId, callingUid, state);
2143 }
2144 
RegisterGetFormRectProxy(const sptr<IRemoteObject> & callerToken)2145 bool FormMgrService::RegisterGetFormRectProxy(const sptr<IRemoteObject> &callerToken)
2146 {
2147     HILOG_INFO("call");
2148     return FormMgrAdapter::GetInstance().RegisterGetFormRectProxy(callerToken);
2149 }
2150 
UnregisterGetFormRectProxy()2151 bool FormMgrService::UnregisterGetFormRectProxy()
2152 {
2153     HILOG_INFO("call");
2154     return FormMgrAdapter::GetInstance().UnregisterGetFormRectProxy();
2155 }
2156 
GetFormRect(const int64_t formId,Rect & rect)2157 ErrCode FormMgrService::GetFormRect(const int64_t formId, Rect &rect)
2158 {
2159     HILOG_INFO("call");
2160     int32_t callingUid = IPCSkeleton::GetCallingUid();
2161     return FormMgrAdapter::GetInstance().GetFormRect(formId, callingUid, rect);
2162 }
2163 
UpdateFormSize(const int64_t formId,const int32_t newDimension,const Rect & newRect)2164 ErrCode FormMgrService::UpdateFormSize(const int64_t formId, const int32_t newDimension, const Rect &newRect)
2165 {
2166     HILOG_INFO("call");
2167     ErrCode ret = CheckFormPermission();
2168     if (ret != ERR_OK) {
2169         HILOG_ERROR("update formSize permission denied");
2170         return ret;
2171     }
2172     return FormMgrAdapter::GetInstance().UpdateFormSize(formId, newDimension, newRect);
2173 }
2174 
RegisterGetLiveFormStatusProxy(const sptr<IRemoteObject> & callerToken)2175 bool FormMgrService::RegisterGetLiveFormStatusProxy(const sptr<IRemoteObject> &callerToken)
2176 {
2177     HILOG_INFO("call");
2178     return FormMgrAdapter::GetInstance().RegisterGetLiveFormStatusProxy(callerToken);
2179 }
2180 
UnregisterGetLiveFormStatusProxy()2181 bool FormMgrService::UnregisterGetLiveFormStatusProxy()
2182 {
2183     HILOG_INFO("call");
2184     return FormMgrAdapter::GetInstance().UnregisterGetLiveFormStatusProxy();
2185 }
2186 }  // namespace AppExecFwk
2187 }  // namespace OHOS
2188