• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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 <cinttypes>
17 
18 #include "appexecfwk_errors.h"
19 #include "form_cache_mgr.h"
20 #include "form_constants.h"
21 #include "form_data_mgr.h"
22 #include "form_provider_mgr.h"
23 #include "form_util.h"
24 #include "hilog_wrapper.h"
25 #include "ipc_skeleton.h"
26 
27 
28 namespace OHOS {
29 namespace AppExecFwk {
FormDataMgr()30 FormDataMgr::FormDataMgr()
31 {
32     HILOG_INFO("create form data manager instance");
33     udidHash_ = 0L;
34 }
~FormDataMgr()35 FormDataMgr::~FormDataMgr()
36 {
37     HILOG_INFO("destroy form data manager instance");
38 }
39 
40 /**
41  * @brief Allot form info by item info.
42  * @param formInfo Form item info.
43  * @param callingUid The UID of the proxy.
44  * @param userId User ID.
45  * @return Returns form record.
46  */
AllotFormRecord(const FormItemInfo & formInfo,const int callingUid,const int32_t userId)47 FormRecord FormDataMgr::AllotFormRecord(const FormItemInfo &formInfo, const int callingUid, const int32_t userId)
48 {
49     HILOG_INFO("%{public}s, allot form info", __func__);
50     if (formInfo.IsTemporaryForm() && !ExistTempForm(formInfo.GetFormId())) {
51         std::lock_guard<std::mutex> lock(formTempMutex_);
52         tempForms_.emplace_back(formInfo.GetFormId());
53     }
54     FormRecord record;
55     {
56         std::lock_guard<std::mutex> lock(formRecordMutex_);
57         if (formRecords_.empty()) { // formRecords_ is empty, create a new one
58             HILOG_DEBUG("%{public}s, form info not exist", __func__);
59             record = CreateFormRecord(formInfo, callingUid, userId);
60             formRecords_.emplace(formInfo.GetFormId(), record);
61         } else {
62             auto info = formRecords_.find(formInfo.GetFormId());
63             if (info == formRecords_.end()) {
64                 HILOG_DEBUG("%{public}s, form info not find", __func__);
65                 record = CreateFormRecord(formInfo, callingUid, userId);
66                 formRecords_.emplace(formInfo.GetFormId(), record);
67             } else {
68                 record = info->second;
69             }
70         }
71     }
72     HILOG_INFO("%{public}s end", __func__);
73     return record;
74 }
75 /**
76  * @brief Delete form js info by form record.
77  * @param formId The Id of the form.
78  * @return Returns true if this function is successfully called; returns false otherwise.
79  */
DeleteFormRecord(const int64_t formId)80 bool FormDataMgr::DeleteFormRecord(const int64_t formId)
81 {
82     HILOG_INFO("%{public}s, delete form info", __func__);
83     std::lock_guard<std::mutex> lock(formRecordMutex_);
84     auto iter = formRecords_.find(formId);
85     if (iter == formRecords_.end()) {
86         HILOG_ERROR("%{public}s, form info is not exist", __func__);
87         return true;
88     }
89     formRecords_.erase(iter);
90     return true;
91 }
92 /**
93  * @brief Allot form host record by caller token.
94  * @param info The form item info.
95  * @param callerToken callerToken
96  * @param formId The Id of the form.
97  * @param callingUid The UID of the proxy.
98  * @param record Form host record.
99  * @return Returns true if this function is successfully called; returns false otherwise.
100  */
AllotFormHostRecord(const FormItemInfo & info,const sptr<IRemoteObject> & callerToken,const int64_t formId,const int callingUid)101 bool FormDataMgr::AllotFormHostRecord(const FormItemInfo &info, const sptr<IRemoteObject> &callerToken,
102     const int64_t formId, const int callingUid)
103 {
104     HILOG_INFO("%{public}s, allot form Host info", __func__);
105     std::lock_guard<std::mutex> lock(formHostRecordMutex_);
106     for (auto &record : clientRecords_) {
107         if (callerToken == record.GetClientStub()) {
108             record.AddForm(formId);
109             HILOG_INFO("%{public}s end", __func__);
110             return true;
111         }
112     }
113     FormHostRecord hostRecord;
114     bool isCreated = CreateHostRecord(info, callerToken, callingUid, hostRecord);
115     if (isCreated) {
116         hostRecord.AddForm(formId);
117         clientRecords_.emplace_back(hostRecord);
118         HILOG_INFO("%{public}s end", __func__);
119         return true;
120     }
121     HILOG_INFO("%{public}s end", __func__);
122     return false;
123 }
124 /**
125  * @brief Create host record.
126  * @param info The form item info.
127  * @param callerToken The UID of the proxy.
128  * @param callingUid The UID of the proxy.
129  * @param record The form host record.
130  * @return Returns true if this function is successfully called; returns false otherwise.
131  */
CreateHostRecord(const FormItemInfo & info,const sptr<IRemoteObject> & callerToken,const int callingUid,FormHostRecord & record)132 bool FormDataMgr::CreateHostRecord(const FormItemInfo &info, const sptr<IRemoteObject> &callerToken,
133     const int callingUid, FormHostRecord& record)
134 {
135     if (callerToken == nullptr) {
136         HILOG_ERROR("%{public}s, invalid param", __func__);
137         return false;
138     }
139 
140     record = FormHostRecord::CreateRecord(info, callerToken, callingUid);
141     return true;
142 }
143 /**
144  * @brief Create form record.
145  * @param formInfo The form item info.
146  * @param callingUid The UID of the proxy.
147  * @param userId User ID.
148  * @return Form record.
149  */
CreateFormRecord(const FormItemInfo & formInfo,const int callingUid,const int32_t userId) const150 FormRecord FormDataMgr::CreateFormRecord(const FormItemInfo &formInfo, const int callingUid, const int32_t userId) const
151 {
152     HILOG_INFO("%{public}s, create form info", __func__);
153     FormRecord newRecord;
154     newRecord.formId = formInfo.GetFormId();
155     newRecord.userId = userId;
156     newRecord.packageName = formInfo.GetPackageName();
157     newRecord.bundleName = formInfo.GetProviderBundleName();
158     newRecord.moduleName = formInfo.GetModuleName();
159     newRecord.abilityName = formInfo.GetAbilityName();
160     newRecord.formName = formInfo.GetFormName();
161     newRecord.specification = formInfo.GetSpecificationId();
162     newRecord.isEnableUpdate = formInfo.IsEnableUpdateFlag();
163     newRecord.formTempFlg = formInfo.IsTemporaryForm();
164     newRecord.formVisibleNotify = formInfo.IsFormVisibleNotify();
165     newRecord.jsFormCodePath = formInfo.GetHapSourceByModuleName(newRecord.moduleName);
166     newRecord.formSrc = formInfo.GetFormSrc();
167     newRecord.formWindow = formInfo.GetFormWindow();
168     newRecord.versionName = formInfo.GetVersionName();
169     newRecord.versionCode = formInfo.GetVersionCode();
170     newRecord.compatibleVersion = formInfo.GetCompatibleVersion();
171     newRecord.icon = formInfo.GetIcon();
172 
173     newRecord.formVisibleNotifyState = 0;
174     if (newRecord.isEnableUpdate) {
175         ParseUpdateConfig(newRecord, formInfo);
176     }
177     if (std::find(newRecord.formUserUids.begin(), newRecord.formUserUids.end(),
178         callingUid) == newRecord.formUserUids.end()) {
179         newRecord.formUserUids.emplace_back(callingUid);
180     }
181 
182     formInfo.GetHapSourceDirs(newRecord.hapSourceDirs);
183     HILOG_INFO("%{public}s end", __func__);
184     return newRecord;
185 }
186 /**
187  * @brief Create form js info by form record.
188  * @param formId The Id of the form.
189  * @param record Form record.
190  * @param formInfo Js info.
191  * @return None.
192  */
CreateFormInfo(const int64_t formId,const FormRecord & record,FormJsInfo & formInfo)193 void FormDataMgr::CreateFormInfo(const int64_t formId, const FormRecord &record, FormJsInfo &formInfo)
194 {
195     formInfo.formId = formId;
196     formInfo.bundleName = record.bundleName;
197     formInfo.abilityName = record.abilityName;
198     formInfo.formName = record.formName;
199     formInfo.formTempFlg = record.formTempFlg;
200     formInfo.jsFormCodePath = record.jsFormCodePath;
201     formInfo.formSrc = record.formSrc;
202     formInfo.formWindow = record.formWindow;
203     formInfo.versionCode = record.versionCode;
204     formInfo.versionName = record.versionName;
205     formInfo.compatibleVersion = record.compatibleVersion;
206     formInfo.icon = record.icon;
207 }
208 /**
209  * @brief Check temp form count is max.
210  * @return Returns ERR_OK if the temp form not reached; returns ERR_MAX_SYSTEM_TEMP_FORMS is reached.
211  */
CheckTempEnoughForm() const212 int FormDataMgr::CheckTempEnoughForm() const
213 {
214     if (tempForms_.size() >= Constants::MAX_TEMP_FORMS) {
215         HILOG_WARN("%{public}s, already exist %{public}d temp forms in system", __func__, Constants::MAX_TEMP_FORMS);
216         return ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS;
217     }
218     return ERR_OK;
219 }
220 /**
221  * @brief Check form count is max.
222  * @param callingUid The UID of the proxy.
223  * @param currentUserId The current userId.
224  * @return Returns true if this function is successfully called; returns false otherwise.
225  */
CheckEnoughForm(const int callingUid,const int32_t currentUserId) const226 int FormDataMgr::CheckEnoughForm(const int callingUid, const int32_t currentUserId) const
227 {
228     HILOG_INFO("%{public}s, callingUid: %{public}d, current userId: %{public}d", __func__, callingUid, currentUserId);
229 
230     int formsInSystem = 0;
231     int callingUidFormCounts = 0;
232     for (auto &recordPair : formRecords_) {
233         FormRecord record = recordPair.second;
234         if ((record.userId == currentUserId) && !record.formTempFlg) {
235             if (++formsInSystem >= Constants::MAX_FORMS) {
236                 HILOG_WARN("%{public}s, already exist %{public}d forms in system", __func__, Constants::MAX_FORMS);
237                 return ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS;
238             }
239             for (auto &userUid : record.formUserUids) {
240                 if (userUid != callingUid) {
241                     continue;
242                 }
243                 if (++callingUidFormCounts >= Constants::MAX_RECORD_PER_APP) {
244                     HILOG_WARN("%{public}s, already use %{public}d forms", __func__, Constants::MAX_RECORD_PER_APP);
245                     return ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT;
246                 }
247                 break;
248             }
249         }
250     }
251     return ERR_OK;
252 }
253 /**
254  * @brief Delete temp form.
255  * @param formId The Id of the form.
256  * @return Returns true if this function is successfully called; returns false otherwise.
257  */
DeleteTempForm(const int64_t formId)258 bool FormDataMgr::DeleteTempForm(const int64_t formId)
259 {
260     std::lock_guard<std::mutex> lock(formTempMutex_);
261     auto iter = std::find(tempForms_.begin(), tempForms_.end(), formId);
262     if (iter == tempForms_.end()) {
263         HILOG_ERROR("%{public}s, temp form is not exist", __func__);
264         return false;
265     }
266     tempForms_.erase(iter);
267     return true;
268 }
269 /**
270  * @brief Check temp form is exist.
271  * @param formId The Id of the form.
272  * @return Returns true if the temp form is exist; returns false is not exist.
273  */
ExistTempForm(const int64_t formId) const274 bool FormDataMgr::ExistTempForm(const int64_t formId) const
275 {
276     return (std::find(tempForms_.begin(), tempForms_.end(), formId) != tempForms_.end());
277 }
278 /**
279  * @brief Check calling uid is valid.
280  * @param formUserUids The form user uids.
281  * @return Returns true if this user uid is valid; returns false otherwise.
282  */
IsCallingUidValid(const std::vector<int> & formUserUids) const283 bool FormDataMgr::IsCallingUidValid(const std::vector<int> &formUserUids) const
284 {
285     if (formUserUids.size() != 0) {
286         for (auto &userUid : formUserUids) {
287             if (userUid == IPCSkeleton::GetCallingUid()) {
288                 return true;
289             }
290         }
291     }
292     return false;
293 }
294 /**
295  * @brief Modify form temp flag by formId.
296  * @param formId The Id of the form.
297  * @param formTempFlg The form temp flag.
298  * @return Returns true if this function is successfully called; returns false otherwise.
299  */
ModifyFormTempFlg(const int64_t formId,const bool formTempFlg)300 bool FormDataMgr::ModifyFormTempFlg(const int64_t formId, const bool formTempFlg)
301 {
302     HILOG_INFO("%{public}s, modify form temp flag by formId", __func__);
303     std::lock_guard<std::mutex> lock(formRecordMutex_);
304     if (!ExistFormRecord(formId)) {
305         HILOG_ERROR("%{public}s, form info is not exist", __func__);
306         return false;
307     }
308     formRecords_[formId].formTempFlg = formTempFlg;
309     return true;
310 }
311 /**
312  * @brief Add form user uid from form record.
313  * @param formId The Id of the form.
314  * @param formRecord The form record.
315  * @return Returns true if this function is successfully called; returns false otherwise.
316  */
AddFormUserUid(const int64_t formId,const int formUserUid)317 bool FormDataMgr::AddFormUserUid(const int64_t formId, const int formUserUid)
318 {
319     HILOG_INFO("%{public}s, add form user uid by formId", __func__);
320     std::lock_guard<std::mutex> lock(formRecordMutex_);
321     if (!ExistFormRecord(formId)) {
322         HILOG_ERROR("%{public}s, form info is not exist", __func__);
323         return false;
324     }
325     if (std::find(formRecords_[formId].formUserUids.begin(), formRecords_[formId].formUserUids.end(),
326         formUserUid) == formRecords_[formId].formUserUids.end()) {
327         formRecords_[formId].formUserUids.emplace_back(formUserUid);
328     }
329     return true;
330 }
331 /**
332  * @brief Delete form user uid from form record.
333  * @param formId The Id of the form.
334  * @param uid calling user id.
335  * @return Returns true if this function is successfully called; returns false otherwise.
336  */
DeleteFormUserUid(const int64_t formId,const int uid)337 bool FormDataMgr::DeleteFormUserUid(const int64_t formId, const int uid)
338 {
339     HILOG_INFO("%{public}s, delete form user uid from form record", __func__);
340     std::lock_guard<std::mutex> lock(formRecordMutex_);
341     if (ExistFormRecord(formId)) {
342         auto iter = std::find(formRecords_.at(formId).formUserUids.begin(),
343             formRecords_.at(formId).formUserUids.end(), uid);
344         if (iter != formRecords_.at(formId).formUserUids.end()) {
345             formRecords_.at(formId).formUserUids.erase(iter);
346         }
347         return true;
348     } else {
349         HILOG_ERROR("%{public}s, form info not find", __func__);
350         return false;
351     }
352 }
353 /**
354  * @brief Update form record.
355  * @param formId The Id of the form.
356  * @param formRecord The form record.
357  * @return Returns true if this function is successfully called; returns false otherwise.
358  */
UpdateFormRecord(const int64_t formId,const FormRecord & formRecord)359 bool FormDataMgr::UpdateFormRecord(const int64_t formId, const FormRecord &formRecord)
360 {
361     HILOG_INFO("%{public}s, get form record by formId", __func__);
362     std::lock_guard<std::mutex> lock(formRecordMutex_);
363     auto info = formRecords_.find(formId);
364     if (info != formRecords_.end()) {
365         formRecords_[formId] = formRecord;
366         return true;
367     }
368     return false;
369 }
370 /**
371  * @brief Get form record.
372  * @param formId The Id of the form.
373  * @param formRecord The form record.
374  * @return Returns true if this function is successfully called; returns false otherwise.
375  */
GetFormRecord(const int64_t formId,FormRecord & formRecord) const376 bool FormDataMgr::GetFormRecord(const int64_t formId, FormRecord &formRecord) const
377 {
378     HILOG_INFO("%{public}s, get form record by formId", __func__);
379     std::lock_guard<std::mutex> lock(formRecordMutex_);
380     auto info = formRecords_.find(formId);
381     if (info == formRecords_.end()) {
382         HILOG_ERROR("%{public}s, form info not find", __func__);
383         return false;
384     }
385     formRecord = info->second;
386 
387     HILOG_INFO("%{public}s, get form record successfully", __func__);
388     return true;
389 }
390 /**
391  * @brief Get form record.
392  * @param bundleName Bundle name.
393  * @param formInfos The form record.
394  * @return Returns true if this function is successfully called; returns false otherwise.
395  */
GetFormRecord(const std::string & bundleName,std::vector<FormRecord> & formInfos)396 bool FormDataMgr::GetFormRecord(const std::string &bundleName, std::vector<FormRecord> &formInfos)
397 {
398     HILOG_INFO("%{public}s, get form record by bundleName", __func__);
399     std::lock_guard<std::mutex> lock(formRecordMutex_);
400     std::map<int64_t, FormRecord>::iterator itFormRecord;
401     for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) {
402         if (bundleName == itFormRecord->second.bundleName) {
403             formInfos.emplace_back(itFormRecord->second);
404         }
405     }
406     if (formInfos.size() > 0) {
407         return true;
408     } else {
409         HILOG_INFO("%{public}s, form info not find", __func__);
410         return false;
411     }
412 }
413 /**
414  * @brief Check form record is exist.
415  * @param formId The Id of the form.
416  * @return Returns true if the form record is exist; returns false is not exist.
417  */
ExistFormRecord(const int64_t formId) const418 bool FormDataMgr::ExistFormRecord(const int64_t formId) const
419 {
420     HILOG_INFO("%{public}s, check form record is exist", __func__);
421     return (formRecords_.count(formId) > 0);
422 }
423 /**
424  * @brief Has form user uids in form record.
425  * @param formId The Id of the form.
426  * @return Returns true if this form has form user uids; returns false is not has.
427  */
HasFormUserUids(const int64_t formId) const428 bool FormDataMgr::HasFormUserUids(const int64_t formId) const
429 {
430     HILOG_INFO("%{public}s, check form has user uids", __func__);
431     FormRecord record;
432     if (GetFormRecord(formId, record)) {
433         return record.formUserUids.empty() ? false : true;
434     }
435     return false;
436 }
437 /**
438  * @brief Get form host record.
439  * @param formId The id of the form.
440  * @param formHostRecord The form host record.
441  * @return Returns true if this function is successfully called; returns false otherwise.
442  */
GetFormHostRecord(const int64_t formId,FormHostRecord & formHostRecord) const443 bool FormDataMgr::GetFormHostRecord(const int64_t formId, FormHostRecord &formHostRecord) const
444 {
445     HILOG_INFO("%{public}s, get form host record by formId", __func__);
446     std::lock_guard<std::mutex> lock(formHostRecordMutex_);
447     for (auto &record : clientRecords_) {
448         if (record.Contains(formId)) {
449             formHostRecord = record;
450             return true;
451         }
452     }
453 
454     HILOG_ERROR("%{public}s, form host record not find", __func__);
455     return false;
456 }
457 /**
458  * @brief Delete form host record.
459  * @param callerToken The client stub of the form host record.
460  * @param formId The id of the form.
461  * @return Returns true if this function is successfully called; returns false otherwise.
462  */
DeleteHostRecord(const sptr<IRemoteObject> & callerToken,const int64_t formId)463 bool FormDataMgr::DeleteHostRecord(const sptr<IRemoteObject> &callerToken, const int64_t formId)
464 {
465     HILOG_INFO("%{public}s start, delete form host record", __func__);
466     std::lock_guard<std::mutex> lock(formHostRecordMutex_);
467     std::vector<FormHostRecord>::iterator iter;
468     for (iter = clientRecords_.begin(); iter != clientRecords_.end(); ++iter) {
469         if (callerToken == iter->GetClientStub()) {
470             iter->DelForm(formId);
471             if (iter->IsEmpty()) {
472                 iter->CleanResource();
473                 iter = clientRecords_.erase(iter);
474             }
475             break;
476         }
477     }
478     HILOG_INFO("%{public}s end", __func__);
479     return true;
480 }
481 /**
482  * @brief Clean removed forms form host.
483  * @param removedFormIds The id list of the forms.
484  */
CleanHostRemovedForms(const std::vector<int64_t> & removedFormIds)485 void FormDataMgr::CleanHostRemovedForms(const std::vector<int64_t> &removedFormIds)
486 {
487     HILOG_INFO("%{public}s start, delete form host record by formId list", __func__);
488     std::vector<int64_t> matchedIds;
489     std::lock_guard<std::mutex> lock(formHostRecordMutex_);
490     std::vector<FormHostRecord>::iterator itHostRecord;
491     for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) {
492         for (const int64_t& formId : removedFormIds) {
493             if (itHostRecord->Contains(formId)) {
494                 matchedIds.emplace_back(formId);
495                 itHostRecord->DelForm(formId);
496             }
497         }
498         if (!matchedIds.empty()) {
499             HILOG_INFO("%{public}s, OnFormUninstalled called", __func__);
500             itHostRecord->OnFormUninstalled(matchedIds);
501         }
502     }
503 
504     HILOG_INFO("%{public}s end", __func__);
505 }
506 /**
507  * @brief Handle form host died.
508  * @param remoteHost Form host proxy object.
509  */
HandleHostDied(const sptr<IRemoteObject> & remoteHost)510 void FormDataMgr::HandleHostDied(const sptr<IRemoteObject> &remoteHost)
511 {
512     std::vector<int64_t> recordTempForms;
513     {
514         std::lock_guard<std::mutex> lock(formHostRecordMutex_);
515         std::vector<FormHostRecord>::iterator itHostRecord;
516         for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();) {
517             if (remoteHost == itHostRecord->GetClientStub()) {
518                 HandleHostDiedForTempForms(*itHostRecord, recordTempForms);
519                 HILOG_INFO("find died client, remove it");
520                 itHostRecord->CleanResource();
521                 itHostRecord = clientRecords_.erase(itHostRecord);
522                 break;
523             } else {
524                 itHostRecord++;
525             }
526         }
527     }
528     {
529         std::lock_guard<std::mutex> lock(formRecordMutex_);
530         std::map<int64_t, FormRecord>::iterator itFormRecord;
531         for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) {
532             int64_t formId = itFormRecord->first;
533             // if temp form, remove it
534             if (std::find(recordTempForms.begin(), recordTempForms.end(), formId) != recordTempForms.end()) {
535                 FormRecord formRecord = itFormRecord->second;
536                 itFormRecord = formRecords_.erase(itFormRecord);
537                 FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, formRecord);
538             } else {
539                 itFormRecord++;
540             }
541         }
542     }
543     {
544         std::lock_guard<std::mutex> lock(formStateRecordMutex_);
545         std::map<std::string, FormHostRecord>::iterator itFormStateRecord;
546         for (itFormStateRecord = formStateRecord_.begin(); itFormStateRecord != formStateRecord_.end();) {
547             if (remoteHost == itFormStateRecord->second.GetClientStub()) {
548                 HILOG_INFO("find died client, remove it from formStateRecord_");
549                 itFormStateRecord->second.CleanResource();
550                 itFormStateRecord = formStateRecord_.erase(itFormStateRecord);
551                 break;
552             } else {
553                 itFormStateRecord++;
554             }
555         }
556     }
557 }
558 
559 /**
560  * @brief Get the temp forms from host and delete temp form in cache.
561  * @param record The form record.
562  * @param recordTempForms Getted the temp forms.
563  */
HandleHostDiedForTempForms(const FormHostRecord & record,std::vector<int64_t> & recordTempForms)564 void FormDataMgr::HandleHostDiedForTempForms(const FormHostRecord &record, std::vector<int64_t> &recordTempForms)
565 {
566     std::lock_guard<std::mutex> lock(formTempMutex_);
567     std::vector<int64_t>::iterator itForm;
568     for (itForm = tempForms_.begin(); itForm != tempForms_.end();) {
569         if (record.Contains(*itForm)) {
570             recordTempForms.emplace_back(*itForm);
571             itForm = tempForms_.erase(itForm);
572         } else {
573             itForm++;
574         }
575     }
576 }
577 
578 /**
579  * @brief Refresh enable or not.
580  * @param formId The Id of the form.
581  * @return true on enbale, false on disable.
582  */
IsEnableRefresh(int64_t formId)583 bool FormDataMgr::IsEnableRefresh(int64_t formId)
584 {
585     std::lock_guard<std::mutex> lock(formHostRecordMutex_);
586     for (auto &record : clientRecords_) {
587         if (record.IsEnableRefresh(formId)) {
588             return true;
589         }
590     }
591 
592     return false;
593 }
594 
595 /**
596  * @brief update enable or not.
597  * @param formId The Id of the form.
598  * @return true on enbale, false on disable.
599  */
IsEnableUpdate(int64_t formId)600 bool FormDataMgr::IsEnableUpdate(int64_t formId)
601 {
602     std::lock_guard<std::mutex> lock(formHostRecordMutex_);
603     for (auto &record : clientRecords_) {
604         if (record.IsEnableUpdate(formId)) {
605             return true;
606         }
607     }
608     return false;
609 }
610 
611 /**
612  * @brief Generate form id.
613  * @return form id.
614  */
GenerateFormId()615 int64_t FormDataMgr::GenerateFormId()
616 {
617     // generate udidHash_
618     if (udidHash_ < 0) {
619         HILOG_ERROR("%{public}s fail, generateFormId no invalid udidHash_", __func__);
620         return ERR_APPEXECFWK_FORM_COMMON_CODE;
621     }
622     return FormUtil::GenerateFormId(udidHash_);
623 }
624 /**
625  * @brief Generate udid.
626  * @return Returns true if this function is successfully called; returns false otherwise.
627  */
GenerateUdidHash()628 bool FormDataMgr::GenerateUdidHash()
629 {
630     if (udidHash_ != Constants::INVALID_UDID_HASH) {
631         return true;
632     }
633 
634     bool bGenUdid = FormUtil::GenerateUdidHash(udidHash_);
635     if (!bGenUdid) {
636         HILOG_ERROR("%{public}s, Failed to generate udid.", __func__);
637         return false;
638     }
639 
640     return true;
641 }
642 /**
643  * @brief Get udid.
644  * @return udid.
645  */
GetUdidHash() const646 int64_t FormDataMgr::GetUdidHash() const
647 {
648     return udidHash_;
649 }
650 /**
651  * @brief Set udid.
652  * @param udidHash udid.
653  */
SetUdidHash(const int64_t udidHash)654 void FormDataMgr::SetUdidHash(const int64_t udidHash)
655 {
656     udidHash_ = udidHash;
657 }
658 
659 /**
660  * @brief Get the matched form host record by client stub.
661  *
662  * @param callerToken The client stub of the form host record.
663  * @param formHostRecord The form host record.
664  * @return Returns true if this function is successfully called, returns false otherwise.
665  */
GetMatchedHostClient(const sptr<IRemoteObject> & callerToken,FormHostRecord & formHostRecord) const666 bool FormDataMgr::GetMatchedHostClient(const sptr<IRemoteObject> &callerToken, FormHostRecord &formHostRecord) const
667 {
668     HILOG_INFO("%{public}s, get the matched form host record by client stub.", __func__);
669     std::lock_guard<std::mutex> lock(formHostRecordMutex_);
670     for (const FormHostRecord &record : clientRecords_) {
671         if (callerToken == record.GetClientStub()) {
672             formHostRecord = record;
673             return true;
674         }
675     }
676 
677     HILOG_ERROR("%{public}s, form host record not find.", __func__);
678     return false;
679 }
680 
681 /**
682  * @brief Set needRefresh for FormRecord.
683  * @param formId The Id of the form.
684  * @param needRefresh true or false.
685  */
SetNeedRefresh(const int64_t formId,const bool needRefresh)686 void FormDataMgr::SetNeedRefresh(const int64_t formId, const bool needRefresh)
687 {
688     std::lock_guard<std::mutex> lock(formRecordMutex_);
689     auto itFormRecord = formRecords_.find(formId);
690     if (itFormRecord == formRecords_.end()) {
691         HILOG_ERROR("%{public}s, form info not find", __func__);
692         return;
693     }
694     itFormRecord->second.needRefresh = needRefresh;
695 }
696 
697 /**
698  * @brief Set isCountTimerRefresh for FormRecord.
699  * @param formId The Id of the form.
700  * @param countTimerRefresh true or false.
701  */
SetCountTimerRefresh(const int64_t formId,const bool countTimerRefresh)702 void FormDataMgr::SetCountTimerRefresh(const int64_t formId, const bool countTimerRefresh)
703 {
704     std::lock_guard<std::mutex> lock(formRecordMutex_);
705     auto itFormRecord = formRecords_.find(formId);
706     if (itFormRecord == formRecords_.end()) {
707         HILOG_ERROR("%{public}s, form info not find", __func__);
708         return;
709     }
710     itFormRecord->second.isCountTimerRefresh = countTimerRefresh;
711 }
712 
713 /**
714  * @brief Get updated form.
715  * @param record FormRecord.
716  * @param targetForms Target forms.
717  * @param updatedForm Updated formnfo.
718  * @return Returns true on success, false on failure.
719  */
GetUpdatedForm(const FormRecord & record,const std::vector<FormInfo> & targetForms,FormInfo & updatedForm)720 bool FormDataMgr::GetUpdatedForm(
721     const FormRecord &record,
722     const std::vector<FormInfo> &targetForms,
723     FormInfo &updatedForm)
724 {
725     if (targetForms.empty()) {
726         HILOG_ERROR("%{public}s error, targetForms is empty.", __func__);
727         return false;
728     }
729 
730     for (const FormInfo &item : targetForms) {
731         if (IsSameForm(record, item)) {
732             updatedForm = item;
733             HILOG_DEBUG("%{public}s, find matched form.", __func__);
734             return true;
735         }
736     }
737     return false;
738 }
739 /**
740  * @brief Set isEnableUpdate for FormRecord.
741  * @param formId The Id of the form.
742  * @param enableUpdate true or false.
743  */
SetEnableUpdate(const int64_t formId,const bool enableUpdate)744 void FormDataMgr::SetEnableUpdate(const int64_t formId, const bool enableUpdate)
745 {
746     std::lock_guard<std::mutex> lock(formRecordMutex_);
747     auto itFormRecord = formRecords_.find(formId);
748     if (itFormRecord == formRecords_.end()) {
749         HILOG_ERROR("%{public}s, form info not find", __func__);
750         return;
751     }
752     itFormRecord->second.isEnableUpdate = enableUpdate;
753 }
754 /**
755  * @brief Set update info for FormRecord.
756  * @param formId The Id of the form.
757  * @param enableUpdate true or false.
758  * @param updateDuration Update duration.
759  * @param updateAtHour Update at hour.
760  * @param updateAtMin Update at minute.
761  */
SetUpdateInfo(const int64_t formId,const bool enableUpdate,const long updateDuration,const int updateAtHour,const int updateAtMin)762 void FormDataMgr::SetUpdateInfo(
763     const int64_t formId,
764     const bool enableUpdate,
765     const long updateDuration,
766     const int updateAtHour,
767     const int updateAtMin)
768 {
769     std::lock_guard<std::mutex> lock(formRecordMutex_);
770     auto itFormRecord = formRecords_.find(formId);
771     if (itFormRecord == formRecords_.end()) {
772         HILOG_ERROR("%{public}s, form info not find", __func__);
773         return;
774     }
775 
776     itFormRecord->second.isEnableUpdate = enableUpdate;
777     itFormRecord->second.updateDuration = updateDuration;
778     itFormRecord->second.updateAtHour = updateAtHour;
779     itFormRecord->second.updateAtMin = updateAtMin;
780 }
781 /**
782  * @brief Check if two forms is same or not.
783  * @param record FormRecord.
784  * @param formInfo FormInfo.
785  * @return Returns true on success, false on failure.
786  */
IsSameForm(const FormRecord & record,const FormInfo & formInfo)787 bool FormDataMgr::IsSameForm(const FormRecord &record, const FormInfo &formInfo)
788 {
789     if (record.bundleName == formInfo.bundleName
790         && record.moduleName == formInfo.moduleName
791         && record.abilityName == formInfo.abilityName
792         && record.formName == formInfo.name
793         && std::find(formInfo.supportDimensions.begin(), formInfo.supportDimensions.end(), record.specification)
794         != formInfo.supportDimensions.end()) {
795         return true;
796     }
797 
798     return false;
799 }
800 /**
801  * @brief Clean removed form records.
802  * @param removedForms The id list of the forms.
803  */
CleanRemovedFormRecords(const std::string & bundleName,std::set<int64_t> & removedForms)804 void FormDataMgr::CleanRemovedFormRecords(const std::string &bundleName, std::set<int64_t> &removedForms)
805 {
806     HILOG_INFO("%{public}s, clean removed form records", __func__);
807     std::lock_guard<std::mutex> lock(formRecordMutex_);
808     std::map<int64_t, FormRecord>::iterator itFormRecord;
809     for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) {
810         auto itForm = std::find(removedForms.begin(), removedForms.end(), itFormRecord->first);
811         if (itForm != removedForms.end()) {
812             itFormRecord = formRecords_.erase(itFormRecord);
813         } else {
814             itFormRecord++;
815         }
816     }
817 }
818 /**
819  * @brief Clean removed temp form records.
820  * @param  bundleName BundleName.
821  * @param removedForms The id list of the forms.
822  */
CleanRemovedTempFormRecords(const std::string & bundleName,const int32_t userId,std::set<int64_t> & removedForms)823 void FormDataMgr::CleanRemovedTempFormRecords(const std::string &bundleName, const int32_t userId,
824     std::set<int64_t> &removedForms)
825 {
826     HILOG_INFO("%{public}s, clean removed form records", __func__);
827     std::set<int64_t> removedTempForms;
828     {
829         std::lock_guard<std::mutex> lock(formRecordMutex_);
830         std::map<int64_t, FormRecord>::iterator itFormRecord;
831         for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) {
832             if ((itFormRecord->second.formTempFlg) && (bundleName == itFormRecord->second.bundleName)
833                 && (userId == itFormRecord->second.userId)) {
834                 removedTempForms.emplace(itFormRecord->second.formId);
835                 itFormRecord = formRecords_.erase(itFormRecord);
836             } else {
837                 itFormRecord++;
838             }
839         }
840     }
841 
842     if (removedTempForms.size() > 0) {
843         std::lock_guard<std::mutex> lock(formTempMutex_);
844         std::vector<int64_t>::iterator itTemp;
845         for (itTemp = tempForms_.begin();itTemp != tempForms_.end();) {
846             if (removedTempForms.find(*itTemp) != removedTempForms.end()) {
847                 itTemp = tempForms_.erase(itTemp);
848             } else {
849                 itTemp++;
850             }
851         }
852         removedForms.merge(removedTempForms);
853     }
854 }
855 /**
856  * @brief Get recreate form records.
857  * @param reCreateForms The id list of the forms.
858  */
GetReCreateFormRecordsByBundleName(const std::string & bundleName,std::set<int64_t> & reCreateForms)859 void FormDataMgr::GetReCreateFormRecordsByBundleName(const std::string &bundleName, std::set<int64_t> &reCreateForms)
860 {
861     std::lock_guard<std::mutex> lock(formRecordMutex_);
862     std::map<int64_t, FormRecord>::iterator itFormRecord;
863     for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) {
864         if (bundleName == itFormRecord->second.bundleName) {
865             reCreateForms.emplace(itFormRecord->second.formId);
866         }
867     }
868 }
869 /**
870  * @brief Set form isInited = true.
871  * @param formId The Id of the form.
872  * @param isInited isInited property
873  */
SetFormCacheInited(const int64_t formId,bool isInited)874 void FormDataMgr::SetFormCacheInited(const int64_t formId, bool isInited)
875 {
876     std::lock_guard<std::mutex> lock(formRecordMutex_);
877     auto itFormRecord = formRecords_.find(formId);
878     if (itFormRecord == formRecords_.end()) {
879         HILOG_ERROR("%{public}s, form info not find", __func__);
880         return;
881     }
882     itFormRecord->second.isInited = isInited;
883     itFormRecord->second.needRefresh = !isInited;
884 }
885 /**
886  * @brief Set versionUpgrade.
887  * @param formId The Id of the form.
888  * @param versionUpgrade true or false
889  */
SetVersionUpgrade(const int64_t formId,const bool versionUpgrade)890 void FormDataMgr::SetVersionUpgrade(const int64_t formId, const bool versionUpgrade)
891 {
892     std::lock_guard<std::mutex> lock(formRecordMutex_);
893     auto itFormRecord = formRecords_.find(formId);
894     if (itFormRecord == formRecords_.end()) {
895         HILOG_ERROR("%{public}s, form info not find", __func__);
896         return;
897     }
898     itFormRecord->second.versionUpgrade = versionUpgrade;
899 }
900 /**
901  * @brief Update form for host clients.
902  * @param formId The Id of the form.
903  * @param needRefresh true or false
904  */
UpdateHostNeedRefresh(const int64_t formId,const bool needRefresh)905 void FormDataMgr::UpdateHostNeedRefresh(const int64_t formId, const bool needRefresh)
906 {
907     std::lock_guard<std::mutex> lock(formHostRecordMutex_);
908     std::vector<FormHostRecord>::iterator itHostRecord;
909     for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) {
910         if (itHostRecord->Contains(formId)) {
911             itHostRecord->SetNeedRefresh(formId, needRefresh);
912         }
913     }
914 }
915 
916 /**
917  * @brief Update form for host clients.
918  * @param formId The Id of the form.
919  * @param formRecord The form info.
920  * @return Returns true if form update, false if other.
921  */
UpdateHostForm(const int64_t formId,const FormRecord & formRecord)922 bool FormDataMgr::UpdateHostForm(const int64_t formId, const FormRecord &formRecord)
923 {
924     bool isUpdated = false;
925     std::lock_guard<std::mutex> lock(formHostRecordMutex_);
926     std::vector<FormHostRecord>::iterator itHostRecord;
927     for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) {
928         bool enableRefresh = formRecord.isVisible || itHostRecord->IsEnableUpdate(formId) ||
929                              itHostRecord->IsEnableRefresh(formId);
930         HILOG_INFO("formId:%{public}" PRId64 " enableRefresh:%{public}d", formId, enableRefresh);
931         if (enableRefresh) {
932             // update form
933             itHostRecord->OnUpdate(formId, formRecord);
934             // set needRefresh
935             itHostRecord->SetNeedRefresh(formId, false);
936             isUpdated = true;
937         }
938     }
939     return isUpdated;
940 }
941 
HandleUpdateHostFormFlag(const std::vector<int64_t> & formIds,bool flag,bool isOnlyEnableUpdate,FormHostRecord & formHostRecord,std::vector<int64_t> & refreshForms)942 ErrCode FormDataMgr::HandleUpdateHostFormFlag(const std::vector<int64_t> &formIds, bool flag, bool isOnlyEnableUpdate,
943                                               FormHostRecord &formHostRecord, std::vector<int64_t> &refreshForms)
944 {
945     for (const int64_t formId : formIds) {
946         if (formId <= 0) {
947             HILOG_WARN("%{public}s, formId %{public}" PRId64 " is less than 0", __func__, formId);
948             continue;
949         }
950 
951         int64_t matchedFormId = FindMatchedFormId(formId);
952         if (!formHostRecord.Contains(matchedFormId)) {
953             HILOG_WARN("%{public}s, form %{public}" PRId64 "is not owned by this client, don't need to update flag",
954                 __func__, formId);
955             continue;
956         }
957 
958         if (isOnlyEnableUpdate) {
959             // new API: this flag is used only to control enable update
960             formHostRecord.SetEnableUpdate(matchedFormId, flag);
961             formHostRecord.SetEnableRefresh(matchedFormId, false);
962         } else {
963             // old API: this flag is used to control enable update and visible update
964             formHostRecord.SetEnableRefresh(matchedFormId, flag);
965         }
966 
967         // set disable
968         if (!flag) {
969             HILOG_INFO("%{public}s, flag is disable", __func__);
970             continue;
971         }
972         FormRecord formRecord;
973         if (GetFormRecord(matchedFormId, formRecord)) {
974             if (formRecord.needRefresh) {
975                 HILOG_INFO("%{public}s, formRecord need refresh", __func__);
976                 refreshForms.emplace_back(matchedFormId);
977                 continue;
978             }
979         } else {
980             HILOG_WARN("%{public}s, not exist such form:%{public}" PRId64 "", __func__, matchedFormId);
981             continue;
982         }
983 
984         // if set enable flag, should check whether to refresh form
985         if (!formHostRecord.IsNeedRefresh(matchedFormId)) {
986             HILOG_INFO("%{public}s, host need not refresh", __func__);
987             continue;
988         }
989 
990         if (IsFormCached(formRecord)) {
991             HILOG_INFO("%{public}s, form cached", __func__);
992             formHostRecord.OnUpdate(matchedFormId, formRecord);
993             formHostRecord.SetNeedRefresh(matchedFormId, false);
994         } else {
995             HILOG_INFO("%{public}s, form no cache", __func__);
996             refreshForms.emplace_back(matchedFormId);
997             continue;
998         }
999     }
1000     return ERR_OK;
1001 }
1002 
1003 /**
1004  * @brief handle update form flag.
1005  * @param formIDs The id of the forms.
1006  * @param callerToken Caller ability token.
1007  * @param flag form flag.
1008  * @param isOnlyEnableUpdate form enable update form flag.
1009  * @param refreshForms Refresh forms
1010  * @return Returns ERR_OK on success, others on failure.
1011  */
UpdateHostFormFlag(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,bool flag,bool isOnlyEnableUpdate,std::vector<int64_t> & refreshForms)1012 ErrCode FormDataMgr::UpdateHostFormFlag(const std::vector<int64_t> &formIds, const sptr<IRemoteObject> &callerToken,
1013                                         bool flag, bool isOnlyEnableUpdate, std::vector<int64_t> &refreshForms)
1014 {
1015     HILOG_INFO("%{public}s start, flag: %{public}d", __func__, flag);
1016     std::lock_guard<std::mutex> lock(formHostRecordMutex_);
1017     std::vector<FormHostRecord>::iterator itHostRecord;
1018     for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) {
1019         if (callerToken == itHostRecord->GetClientStub()) {
1020             HandleUpdateHostFormFlag(formIds, flag, isOnlyEnableUpdate, *itHostRecord, refreshForms);
1021             HILOG_INFO("%{public}s end.", __func__);
1022             return ERR_OK;
1023         }
1024     }
1025     HILOG_ERROR("%{public}s, can't find target client", __func__);
1026     return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
1027 }
1028 /**
1029  * @brief Find matched form id.
1030  * @param formId The form id.
1031  * @return Matched form id.
1032  */
FindMatchedFormId(const int64_t formId)1033 int64_t FormDataMgr::FindMatchedFormId(const int64_t formId)
1034 {
1035     uint64_t unsignedFormId = static_cast<uint64_t>(formId);
1036     if ((unsignedFormId & 0xffffffff00000000L) != 0) {
1037         return formId;
1038     }
1039     std::lock_guard<std::mutex> lock(formRecordMutex_);
1040     std::map<int64_t, FormRecord>::iterator itFormRecord;
1041     for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) {
1042         uint64_t unsignedFormId = static_cast<uint64_t>(formId);
1043         uint64_t unsignedItFormRecordFirst = static_cast<uint64_t>(itFormRecord->first);
1044         if ((unsignedItFormRecordFirst & 0x00000000ffffffffL) == (unsignedFormId & 0x00000000ffffffffL)) {
1045             return itFormRecord->first;
1046         }
1047     }
1048     return formId;
1049 }
1050 
1051 /**
1052  * @brief Clear host data by uId.
1053  * @param uId The caller uId.
1054  */
ClearHostDataByUId(const int uId)1055 void FormDataMgr::ClearHostDataByUId(const int uId)
1056 {
1057     std::lock_guard<std::mutex> lock(formHostRecordMutex_);
1058     std::vector<FormHostRecord>::iterator itHostRecord;
1059     for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();) {
1060         if (itHostRecord->GetCallerUid() == uId) {
1061             itHostRecord->CleanResource();
1062             itHostRecord = clientRecords_.erase(itHostRecord);
1063         } else {
1064             itHostRecord++;
1065         }
1066     }
1067 }
1068 /**
1069  * @brief Get no host temp forms.
1070  * @param uid The caller uid.
1071  * @param noHostTempFormsMap no host temp forms.
1072  * @param foundFormsMap Form Id list.
1073  */
GetNoHostTempForms(const int uid,std::map<FormIdKey,std::set<int64_t>> & noHostTempFormsMap,std::map<int64_t,bool> & foundFormsMap)1074 void FormDataMgr::GetNoHostTempForms(
1075     const int uid, std::map<FormIdKey,
1076     std::set<int64_t>> &noHostTempFormsMap,
1077     std::map<int64_t, bool> &foundFormsMap)
1078 {
1079     std::lock_guard<std::mutex> lock(formRecordMutex_);
1080     std::map<int64_t, FormRecord>::iterator itFormRecord;
1081     for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) {
1082         if (itFormRecord->second.formTempFlg) {
1083             auto itUid = std::find(itFormRecord->second.formUserUids.begin(),
1084                 itFormRecord->second.formUserUids.end(), uid);
1085             if (itUid != itFormRecord->second.formUserUids.end()) {
1086                 itFormRecord->second.formUserUids.erase(itUid);
1087                 if (itFormRecord->second.formUserUids.empty()) {
1088                     FormIdKey formIdKey(itFormRecord->second.bundleName, itFormRecord->second.abilityName);
1089                     auto itIdsSet = noHostTempFormsMap.find(formIdKey);
1090                     if (itIdsSet == noHostTempFormsMap.end()) {
1091                         std::set<int64_t> formIdsSet;
1092                         formIdsSet.emplace(itFormRecord->second.formId);
1093                         noHostTempFormsMap.emplace(formIdKey, formIdsSet);
1094                     } else {
1095                         itIdsSet->second.emplace(itFormRecord->second.formId);
1096                     }
1097                 }
1098             } else {
1099                 foundFormsMap.emplace(itFormRecord->second.formId, false);
1100             }
1101         }
1102     }
1103 }
1104 /**
1105  * @brief Parse update config.
1106  * @param record The form record.
1107  * @param info The form item info.
1108  */
ParseUpdateConfig(FormRecord & record,const FormItemInfo & info) const1109 void FormDataMgr::ParseUpdateConfig(FormRecord &record, const FormItemInfo &info) const
1110 {
1111     int configDuration = info.GetUpdateDuration();
1112     if (configDuration > 0) {
1113         ParseIntervalConfig(record, configDuration);
1114     } else {
1115         ParseAtTimerConfig(record, info);
1116     }
1117 }
1118 
1119 /**
1120  * @brief Parse update interval config.
1121  * @param record The form record.
1122  * @param configDuration interval duration.
1123  */
ParseIntervalConfig(FormRecord & record,const int configDuration) const1124 void FormDataMgr::ParseIntervalConfig(FormRecord &record, const int configDuration) const
1125 {
1126     HILOG_INFO("%{public}s, configDuration:%{public}d", __func__, configDuration);
1127     if (configDuration <= Constants::MIN_CONFIG_DURATION) {
1128         record.updateDuration = Constants::MIN_PERIOD;
1129     } else if (configDuration >= Constants::MAX_CONFIG_DURATION) {
1130         record.updateDuration = Constants::MAX_PERIOD;
1131     } else {
1132         record.updateDuration = configDuration * Constants::TIME_CONVERSION;
1133     }
1134     HILOG_INFO("%{public}s end", __func__);
1135 }
1136 
1137 /**
1138  * @brief Parse at time config.
1139  * @param record The form record.
1140  * @param info form item info.
1141  */
ParseAtTimerConfig(FormRecord & record,const FormItemInfo & info) const1142 void FormDataMgr::ParseAtTimerConfig(FormRecord &record, const FormItemInfo &info) const
1143 {
1144     record.isEnableUpdate = false;
1145     record.updateDuration = 0;
1146     std::string configAtTime = info.GetScheduledUpdateTime();
1147     HILOG_INFO("%{public}s, parseAsUpdateAt updateAt:%{public}s", __func__, configAtTime.c_str());
1148     if (configAtTime.empty()) {
1149         return;
1150     }
1151 
1152     std::vector<std::string> temp = FormUtil::StringSplit(configAtTime, Constants::TIME_DELIMETER);
1153     if (temp.size() != Constants::UPDATE_AT_CONFIG_COUNT) {
1154         HILOG_ERROR("%{public}s, invalid config", __func__);
1155         return;
1156     }
1157     int hour = -1;
1158     int min = -1;
1159     hour = std::stoi(temp[0]);
1160     min = std::stoi(temp[1]);
1161     if (hour < Constants::MIN_TIME || hour > Constants::MAX_HOUR || min < Constants::MIN_TIME || min >
1162         Constants::MAX_MINUTE) {
1163         HILOG_ERROR("%{public}s, time is invalid", __func__);
1164         return;
1165     }
1166     record.updateAtHour = hour;
1167     record.updateAtMin = min;
1168     record.isEnableUpdate = true;
1169 }
1170 /**
1171  * @brief handle update form flag.
1172  * @param formIDs The id of the forms.
1173  * @param callerToken Caller ability token.
1174  * @param flag form flag.
1175  * @return Returns ERR_OK on success, others on failure.
1176  */
IsFormCached(const FormRecord record)1177 bool FormDataMgr::IsFormCached(const FormRecord record)
1178 {
1179     if (record.versionUpgrade) {
1180         return false;
1181     }
1182     return FormCacheMgr::GetInstance().IsExist(record.formId);
1183 }
1184 
1185 /**
1186  * @brief Create form state host record.
1187  * @param provider The provider of the form state
1188  * @param info The form item info.
1189  * @param callerToken The UID of the proxy.
1190  * @param callingUid The UID of the proxy.
1191  * @return Returns true if this function is successfully called; returns false otherwise.
1192  */
CreateFormStateRecord(std::string & provider,const FormItemInfo & info,const sptr<IRemoteObject> & callerToken,int callingUid)1193 bool FormDataMgr::CreateFormStateRecord(std::string &provider, const FormItemInfo &info,
1194                                         const sptr<IRemoteObject> &callerToken, int callingUid)
1195 {
1196     std::lock_guard<std::mutex> lock(formStateRecordMutex_);
1197     auto iter = formStateRecord_.find(provider);
1198     if (iter != formStateRecord_.end()) {
1199         if (iter->second.GetClientStub() != callerToken) {
1200             iter->second.SetClientStub(callerToken);
1201         }
1202         return true;
1203     }
1204 
1205     FormHostRecord hostRecord;
1206     bool isCreated = CreateHostRecord(info, callerToken, callingUid, hostRecord);
1207     if (isCreated) {
1208         formStateRecord_.emplace(provider, hostRecord);
1209         return true;
1210     }
1211 
1212     return false;
1213 }
1214 
1215 /**
1216  * @brief acquire form state callback.
1217  * @param state form state.
1218  * @param provider provider indo.
1219  * @param want The want of onAcquireFormState.
1220  * @return Returns true if this function is successfully called; returns false otherwise.
1221  */
AcquireFormStateBack(AppExecFwk::FormState state,const std::string & provider,const AAFwk::Want & want)1222 ErrCode FormDataMgr::AcquireFormStateBack(AppExecFwk::FormState state, const std::string &provider,
1223                                           const AAFwk::Want &want)
1224 {
1225     std::lock_guard<std::mutex> lock(formStateRecordMutex_);
1226     auto iter = formStateRecord_.find(provider);
1227     if (iter == formStateRecord_.end()) {
1228         HILOG_ERROR("filed to get form state host record");
1229         return ERR_APPEXECFWK_FORM_GET_HOST_FAILED;
1230     }
1231     iter->second.OnAcquireState(state, want);
1232     iter->second.CleanResource();
1233     formStateRecord_.erase(iter);
1234     return ERR_OK;
1235 }
1236 
1237 /**
1238  * @brief Notify the form is visible or not.
1239  * @param formIds Indicates the ID of the forms.
1240  * @param isVisible Visible or not.
1241  * @param callerToken Host client.
1242  * @return Returns ERR_OK on success, others on failure.
1243  */
NotifyFormsVisible(const std::vector<int64_t> & formIds,bool isVisible,const sptr<IRemoteObject> & callerToken)1244 ErrCode FormDataMgr::NotifyFormsVisible(const std::vector<int64_t> &formIds, bool isVisible,
1245                                         const sptr<IRemoteObject> &callerToken)
1246 {
1247     if (formIds.empty() || callerToken == nullptr) {
1248         HILOG_ERROR("%{public}s failed, formIds empty.", __func__);
1249         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1250     }
1251 
1252     std::vector<int64_t> foundFormIds {};
1253     {
1254         HILOG_INFO("%{public}s, get the matched form host record by client stub.", __func__);
1255         std::lock_guard<std::mutex> lock(formHostRecordMutex_);
1256         for (const FormHostRecord &record : clientRecords_) {
1257             if (callerToken != record.GetClientStub()) {
1258                 continue;
1259             }
1260             for (int64_t formId : formIds) {
1261                 int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
1262                 if (!record.Contains(matchedFormId)) {
1263                     HILOG_ERROR("%{public}s fail, form is not self-owned, form:%{public}" PRId64 ".", __func__,
1264                         matchedFormId);
1265                 } else {
1266                     foundFormIds.push_back(matchedFormId);
1267                 }
1268             }
1269             break;
1270         }
1271     }
1272 
1273     if (foundFormIds.empty()) {
1274         HILOG_ERROR("%{public}s failed, no valid forms found.", __func__);
1275         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
1276     }
1277 
1278     for (auto matchedFormId : foundFormIds) {
1279         SetRecordVisible(matchedFormId, isVisible);
1280     }
1281     return ERR_OK;
1282 }
1283 
1284 /**
1285  * @brief set form record visible.
1286  * @param matchedFormId form id.
1287  * @param isVisible is visible.
1288  * @return Returns true if this function is successfully called; returns false otherwise.
1289  */
SetRecordVisible(int64_t matchedFormId,bool isVisible)1290 ErrCode FormDataMgr::SetRecordVisible(int64_t matchedFormId, bool isVisible)
1291 {
1292     HILOG_INFO("%{public}s, set form record visible", __func__);
1293     std::lock_guard<std::mutex> lock(formRecordMutex_);
1294     auto info = formRecords_.find(matchedFormId);
1295     if (info == formRecords_.end()) {
1296         HILOG_ERROR("%{public}s, form info not find", __func__);
1297         return ERR_APPEXECFWK_FORM_INVALID_FORM_ID;
1298     }
1299     info->second.isVisible = isVisible;
1300     HILOG_DEBUG("set isVisible to %{public}d, formId: %{public}" PRId64 " ", isVisible, matchedFormId);
1301     return ERR_OK;
1302 }
1303 
1304 /**
1305  * @brief delete forms by userId.
1306  *
1307  * @param userId user ID.
1308  * @param removedFormIds removed userId.
1309  */
DeleteFormsByUserId(const int32_t userId,std::vector<int64_t> & removedFormIds)1310 void FormDataMgr::DeleteFormsByUserId(const int32_t userId, std::vector<int64_t> &removedFormIds)
1311 {
1312     HILOG_INFO("%{public}s,  delete forms by userId", __func__);
1313 
1314     // handle formRecords_
1315     std::vector<int64_t> removedTempForms;
1316     {
1317         std::lock_guard<std::mutex> lock(formRecordMutex_);
1318         auto itFormRecord = formRecords_.begin();
1319         while (itFormRecord != formRecords_.end()) {
1320             if (userId == itFormRecord->second.userId) {
1321                 if (itFormRecord->second.formTempFlg) {
1322                     removedTempForms.emplace_back(itFormRecord->second.formId);
1323                 }
1324                 removedFormIds.emplace_back(itFormRecord->second.formId);
1325                 itFormRecord = formRecords_.erase(itFormRecord);
1326             } else {
1327                 ++itFormRecord;
1328             }
1329         }
1330     }
1331 
1332     // handle tempForms_
1333     if (removedTempForms.size() > 0) {
1334         std::lock_guard<std::mutex> lock(formTempMutex_);
1335         std::vector<int64_t>::iterator itTemp;
1336         for (itTemp = tempForms_.begin();itTemp != tempForms_.end();) {
1337             if (std::find(removedTempForms.begin(), removedTempForms.end(), *itTemp) != removedTempForms.end()) {
1338                 itTemp = tempForms_.erase(itTemp);
1339             } else {
1340                 itTemp++;
1341             }
1342         }
1343     }
1344 }
1345 /**
1346  * @brief Clear form records for st limit value test.
1347  */
ClearFormRecords()1348 void FormDataMgr::ClearFormRecords()
1349 {
1350     {
1351         std::lock_guard<std::mutex> lock(formRecordMutex_);
1352         formRecords_.clear();
1353     }
1354     {
1355         std::lock_guard<std::mutex> lock(formTempMutex_);
1356         tempForms_.clear();
1357     }
1358 }
1359 
1360 /**
1361  * @brief handle get no host invalid temp forms.
1362  * @param userId User ID.
1363  * @param callingUid The UID of the proxy.
1364  * @param matchedFormIds The set of the valid forms.
1365  * @param noHostTempFormsMap The map of the no host forms.
1366  * @param foundFormsMap The map of the found forms.
1367  */
GetNoHostInvalidTempForms(int32_t userId,int32_t callingUid,std::set<int64_t> & matchedFormIds,std::map<FormIdKey,std::set<int64_t>> & noHostTempFormsMap,std::map<int64_t,bool> & foundFormsMap)1368 void FormDataMgr::GetNoHostInvalidTempForms(int32_t userId, int32_t callingUid, std::set<int64_t> &matchedFormIds,
1369                                             std::map<FormIdKey, std::set<int64_t>> &noHostTempFormsMap,
1370                                             std::map<int64_t, bool> &foundFormsMap)
1371 {
1372     std::lock_guard<std::mutex> lock(formRecordMutex_);
1373     for (auto &formRecordInfo : formRecords_) {
1374         int64_t formId = formRecordInfo.first;
1375         FormRecord &formRecord = formRecordInfo.second;
1376 
1377         // check userID and temp flag
1378         if (userId != formRecord.userId || !formRecord.formTempFlg) {
1379             continue;
1380         }
1381         // check UID
1382         auto iter = std::find(formRecord.formUserUids.begin(), formRecord.formUserUids.end(), callingUid);
1383         if (iter == formRecord.formUserUids.end()) {
1384             continue;
1385         }
1386         // check valid form set
1387         if (matchedFormIds.find(formId) != matchedFormIds.end()) {
1388             continue;
1389         }
1390 
1391         HILOG_DEBUG("found invalid form: %{public}" PRId64 "", formId);
1392         formRecord.formUserUids.erase(iter);
1393         if (formRecord.formUserUids.empty()) {
1394             FormIdKey formIdKey(formRecord.bundleName, formRecord.abilityName);
1395             auto itIdsSet = noHostTempFormsMap.find(formIdKey);
1396             if (itIdsSet == noHostTempFormsMap.end()) {
1397                 std::set<int64_t> formIdsSet;
1398                 formIdsSet.emplace(formId);
1399                 noHostTempFormsMap.emplace(formIdKey, formIdsSet);
1400             } else {
1401                 itIdsSet->second.emplace(formId);
1402             }
1403         } else {
1404             foundFormsMap.emplace(formId, false);
1405         }
1406     }
1407 }
1408 
1409 /**
1410  * @brief handle delete no host temp forms.
1411  * @param callingUid The UID of the proxy.
1412  * @param noHostTempFormsMap The map of the no host forms.
1413  * @param foundFormsMap The map of the found forms.
1414  */
BatchDeleteNoHostTempForms(int32_t callingUid,std::map<FormIdKey,std::set<int64_t>> & noHostTempFormsMap,std::map<int64_t,bool> & foundFormsMap)1415 void FormDataMgr::BatchDeleteNoHostTempForms(int32_t callingUid, std::map<FormIdKey,
1416                                              std::set<int64_t>> &noHostTempFormsMap,
1417                                              std::map<int64_t, bool> &foundFormsMap)
1418 {
1419     std::set<FormIdKey> removableModuleSet;
1420     for (auto &noHostTempForm : noHostTempFormsMap) {
1421         FormIdKey formIdKey = noHostTempForm.first;
1422         std::set<int64_t> &formIdsSet = noHostTempForm.second;
1423         std::string bundleName = formIdKey.bundleName;
1424         std::string abilityName = formIdKey.abilityName;
1425         FormProviderMgr::GetInstance().NotifyProviderFormsBatchDelete(bundleName, abilityName, formIdsSet);
1426         for (int64_t formId: formIdsSet) {
1427             foundFormsMap.emplace(formId, true);
1428             DeleteFormRecord(formId);
1429             DeleteTempForm(formId);
1430         }
1431     }
1432 }
1433 
1434 /**
1435  * @brief delete invalid temp forms.
1436  * @param userId User ID.
1437  * @param callingUid The UID of the proxy.
1438  * @param matchedFormIds The set of the valid forms.
1439  * @param removedFormsMap The map of the removed invalid forms.
1440  * @return Returns ERR_OK on success, others on failure.
1441  */
DeleteInvalidTempForms(int32_t userId,int32_t callingUid,std::set<int64_t> & matchedFormIds,std::map<int64_t,bool> & removedFormsMap)1442 int32_t FormDataMgr::DeleteInvalidTempForms(int32_t userId, int32_t callingUid, std::set<int64_t> &matchedFormIds,
1443                                             std::map<int64_t, bool> &removedFormsMap)
1444 {
1445     HILOG_INFO("DeleteInvalidTempForms start, userId = %{public}d, callingUid = %{public}d", userId, callingUid);
1446     std::map<int64_t, bool> foundFormsMap {};
1447     std::map<FormIdKey, std::set<int64_t>> noHostTempFormsMap {};
1448     GetNoHostInvalidTempForms(userId, callingUid, matchedFormIds, noHostTempFormsMap, foundFormsMap);
1449     BatchDeleteNoHostTempForms(callingUid, noHostTempFormsMap, foundFormsMap);
1450     HILOG_DEBUG("foundFormsMap size: %{public}zu", foundFormsMap.size());
1451     HILOG_DEBUG("noHostTempFormsMap size: %{public}zu", noHostTempFormsMap.size());
1452 
1453     if (!foundFormsMap.empty()) {
1454         removedFormsMap.insert(foundFormsMap.begin(), foundFormsMap.end());
1455     }
1456     HILOG_INFO("DeleteInvalidTempForms done");
1457     return ERR_OK;
1458 }
1459 
1460 /**
1461  * @brief clear host data by invalid forms.
1462  * @param callingUid The UID of the proxy.
1463  * @param removedFormsMap The map of the removed invalid forms.
1464  * @return Returns ERR_OK on success, others on failure.
1465  */
ClearHostDataByInvalidForms(int32_t callingUid,std::map<int64_t,bool> & removedFormsMap)1466 int32_t FormDataMgr::ClearHostDataByInvalidForms(int32_t callingUid, std::map<int64_t, bool> &removedFormsMap)
1467 {
1468     HILOG_INFO("DeleteInvalidForms host start");
1469     std::lock_guard<std::mutex> lock(formHostRecordMutex_);
1470     std::vector<FormHostRecord>::iterator itHostRecord;
1471     for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();) {
1472         if (itHostRecord->GetCallerUid() != callingUid) {
1473             itHostRecord++;
1474             continue;
1475         }
1476         for (auto &removedForm : removedFormsMap) {
1477             if (itHostRecord->Contains(removedForm.first)) {
1478                 itHostRecord->DelForm(removedForm.first);
1479             }
1480         }
1481         if (itHostRecord->IsEmpty()) {
1482             itHostRecord->CleanResource();
1483             itHostRecord = clientRecords_.erase(itHostRecord);
1484         } else {
1485             itHostRecord++;
1486         }
1487     }
1488     HILOG_INFO("DeleteInvalidForms host done");
1489     return ERR_OK;
1490 }
1491 }  // namespace AppExecFwk
1492 }  // namespace OHOS
1493