• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-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 "permission_record_manager.h"
17 
18 #include <algorithm>
19 #include <cinttypes>
20 #include <numeric>
21 
22 #include "ability_manager_access_client.h"
23 #include "access_token.h"
24 #include "accesstoken_config_policy.h"
25 #include "accesstoken_kit.h"
26 #include "accesstoken_log.h"
27 #include "active_status_callback_manager.h"
28 #include "app_manager_access_client.h"
29 #include "audio_manager_privacy_client.h"
30 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
31 #include "background_task_manager_access_client.h"
32 #include "continuous_task_callback_info.h"
33 #endif
34 #include "camera_manager_privacy_client.h"
35 #include "constant.h"
36 #include "constant_common.h"
37 #include "data_translator.h"
38 #include "i_state_change_callback.h"
39 #include "iservice_registry.h"
40 #include "libraryloader.h"
41 #include "parameter.h"
42 #include "parcel_utils.h"
43 #include "permission_record_repository.h"
44 #include "permission_used_record_cache.h"
45 #include "power_manager_access_loader.h"
46 #include "privacy_error.h"
47 #include "privacy_field_const.h"
48 #include "refbase.h"
49 #include "state_change_callback_proxy.h"
50 #include "system_ability_definition.h"
51 #include "time_util.h"
52 #include "want.h"
53 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
54 #include "window_manager_loader.h"
55 #endif
56 
57 namespace OHOS {
58 namespace Security {
59 namespace AccessToken {
60 namespace {
61 static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {
62     LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermissionRecordManager"
63 };
64 static const int32_t VALUE_MAX_LEN = 32;
65 static const std::string DEFAULT_DEVICEID = "0";
66 static const std::string FIELD_COUNT_NUMBER = "count";
67 constexpr const char* CAMERA_PERMISSION_NAME = "ohos.permission.CAMERA";
68 constexpr const char* MICROPHONE_PERMISSION_NAME = "ohos.permission.MICROPHONE";
69 constexpr const char* EDM_MIC_MUTE_KEY = "persist.edm.mic_disable";
70 static const std::string DEFAULT_PERMISSION_MANAGER_BUNDLE_NAME = "com.ohos.permissionmanager";
71 static const std::string DEFAULT_PERMISSION_MANAGER_DIALOG_ABILITY = "com.ohos.permissionmanager.GlobalExtAbility";
72 static const std::string RESOURCE_KEY = "ohos.sensitive.resource";
73 static const int32_t DEFAULT_PERMISSION_USED_RECORD_SIZE_MAXIMUM = 500000;
74 static const int32_t DEFAULT_PERMISSION_USED_RECORD_AGING_TIME = 7;
75 static const uint32_t NORMAL_TYPE_ADD_VALUE = 1;
76 static const uint32_t PICKER_TYPE_ADD_VALUE = 2;
77 static const uint32_t SEC_COMPONENT_TYPE_ADD_VALUE = 4;
78 std::recursive_mutex g_instanceMutex;
79 }
GetInstance()80 PermissionRecordManager& PermissionRecordManager::GetInstance()
81 {
82     static PermissionRecordManager* instance = nullptr;
83     if (instance == nullptr) {
84         std::lock_guard<std::recursive_mutex> lock(g_instanceMutex);
85         if (instance == nullptr) {
86             instance = new PermissionRecordManager();
87         }
88     }
89     return *instance;
90 }
91 
PermissionRecordManager()92 PermissionRecordManager::PermissionRecordManager() : deleteTaskWorker_("DeleteRecord"), hasInited_(false)
93 {
94     bool isEdmMute = false;
95     if (!GetMuteParameter(EDM_MIC_MUTE_KEY, isEdmMute)) {
96         ACCESSTOKEN_LOG_ERROR(LABEL, "Get param failed");
97         return;
98     }
99     ModifyMuteStatus(MICROPHONE_PERMISSION_NAME, EDM, isEdmMute);
100 }
101 
~PermissionRecordManager()102 PermissionRecordManager::~PermissionRecordManager()
103 {
104     if (!hasInited_) {
105         return;
106     }
107     deleteTaskWorker_.Stop();
108     hasInited_ = false;
109     Unregister();
110 }
111 
OnForegroundApplicationChanged(const AppStateData & appStateData)112 void PrivacyAppStateObserver::OnForegroundApplicationChanged(const AppStateData &appStateData)
113 {
114     ACCESSTOKEN_LOG_DEBUG(LABEL, "OnChange(accessTokenId=%{public}d, state=%{public}d)",
115         appStateData.accessTokenId, appStateData.state);
116 
117     uint32_t tokenId = appStateData.accessTokenId;
118 
119     ActiveChangeType status = PERM_INACTIVE;
120     if (appStateData.state == static_cast<int32_t>(ApplicationState::APP_STATE_FOREGROUND)) {
121         status = PERM_ACTIVE_IN_FOREGROUND;
122     } else if (appStateData.state == static_cast<int32_t>(ApplicationState::APP_STATE_BACKGROUND)) {
123         status = PERM_ACTIVE_IN_BACKGROUND;
124     }
125     PermissionRecordManager::GetInstance().NotifyAppStateChange(tokenId, status);
126 }
127 
OnApplicationStateChanged(const AppStateData & appStateData)128 void PrivacyAppStateObserver::OnApplicationStateChanged(const AppStateData &appStateData)
129 {
130     ACCESSTOKEN_LOG_DEBUG(LABEL, "OnChange(accessTokenId=%{public}d, state=%{public}d)",
131         appStateData.accessTokenId, appStateData.state);
132 
133     if (appStateData.state == static_cast<int32_t>(ApplicationState::APP_STATE_TERMINATED)) {
134         PermissionRecordManager::GetInstance().RemoveRecordFromStartListByToken(appStateData.accessTokenId);
135     }
136 }
137 
OnProcessDied(const ProcessData & processData)138 void PrivacyAppStateObserver::OnProcessDied(const ProcessData &processData)
139 {
140     ACCESSTOKEN_LOG_DEBUG(LABEL, "OnChange(accessTokenId=%{public}d, state=%{public}d)",
141         processData.accessTokenId, processData.state);
142 
143     PermissionRecordManager::GetInstance().RemoveRecordFromStartListByToken(processData.accessTokenId);
144 }
145 
NotifyAppManagerDeath()146 void PrivacyAppManagerDeathCallback::NotifyAppManagerDeath()
147 {
148     ACCESSTOKEN_LOG_INFO(LABEL, "AppManagerDeath called");
149 
150     PermissionRecordManager::GetInstance().OnAppMgrRemoteDiedHandle();
151 }
152 
AddRecord(const PermissionRecord & record)153 void PermissionRecordManager::AddRecord(const PermissionRecord& record)
154 {
155     Utils::UniqueWriteGuard<Utils::RWLock> lk(this->rwLock_);
156     ACCESSTOKEN_LOG_INFO(LABEL,
157         "add record: tokenId %{public}d, opCode %{public}d, status: %{public}d,"
158         "lockScreenStatus %{public}d, timestamp %{public}" PRId64 ", type %{public}d",
159         record.tokenId, record.opCode, record.status, record.lockScreenStatus, record.timestamp, record.type);
160     PermissionUsedRecordCache::GetInstance().AddRecordToBuffer(record);
161 }
162 
GetPermissionRecord(const AddPermParamInfo & info,PermissionRecord & record)163 int32_t PermissionRecordManager::GetPermissionRecord(const AddPermParamInfo& info, PermissionRecord& record)
164 {
165     if (AccessTokenKit::GetTokenTypeFlag(info.tokenId) != TOKEN_HAP) {
166         ACCESSTOKEN_LOG_DEBUG(LABEL, "Not hap(%{public}d)", info.tokenId);
167         return PrivacyError::ERR_PARAM_INVALID;
168     }
169     int32_t opCode;
170     if (!Constant::TransferPermissionToOpcode(info.permissionName, opCode)) {
171         ACCESSTOKEN_LOG_ERROR(LABEL, "Invalid perm(%{public}s)", info.permissionName.c_str());
172         return PrivacyError::ERR_PERMISSION_NOT_EXIST;
173     }
174     if ((GetMuteStatus(info.permissionName, EDM)) || (!GetGlobalSwitchStatus(info.permissionName))) {
175         record.status = PERM_INACTIVE;
176     } else {
177         record.status = GetAppStatus(info.tokenId);
178     }
179     record.lockScreenStatus = GetLockScreenStatus();
180     record.tokenId = info.tokenId;
181     record.accessCount = info.successCount;
182     record.rejectCount = info.failCount;
183     record.opCode = opCode;
184     record.timestamp = TimeUtil::GetCurrentTimestamp();
185     record.accessDuration = 0;
186     record.type = info.type;
187     ACCESSTOKEN_LOG_DEBUG(LABEL, "record status: %{public}d", record.status);
188     return Constant::SUCCESS;
189 }
190 
TransformEnumToBitValue(const PermissionUsedType type,uint32_t & value)191 void PermissionRecordManager::TransformEnumToBitValue(const PermissionUsedType type, uint32_t& value)
192 {
193     if (type == PermissionUsedType::NORMAL_TYPE) {
194         value = NORMAL_TYPE_ADD_VALUE;
195     } else if (type == PermissionUsedType::PICKER_TYPE) {
196         value = PICKER_TYPE_ADD_VALUE;
197     } else if (type == PermissionUsedType::SECURITY_COMPONENT_TYPE) {
198         value = SEC_COMPONENT_TYPE_ADD_VALUE;
199     }
200 }
201 
AddOrUpdateUsedTypeIfNeeded(const AccessTokenID tokenId,const int32_t opCode,const PermissionUsedType type)202 bool PermissionRecordManager::AddOrUpdateUsedTypeIfNeeded(const AccessTokenID tokenId, const int32_t opCode,
203     const PermissionUsedType type)
204 {
205     uint32_t inputType = 0;
206     TransformEnumToBitValue(type, inputType);
207 
208     GenericValues conditionValue;
209     conditionValue.Put(PrivacyFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenId));
210     conditionValue.Put(PrivacyFiledConst::FIELD_PERMISSION_CODE, opCode);
211 
212     std::vector<GenericValues> results;
213     if (!PermissionRecordRepository::GetInstance().Query(
214         PermissionUsedRecordDb::DataType::PERMISSION_USED_TYPE, conditionValue, results)) {
215         return false;
216     }
217 
218     if (results.empty()) {
219         // empty means there is no permission used type record, add it
220         ACCESSTOKEN_LOG_DEBUG(LABEL, "No exsit record, add it.");
221 
222         GenericValues recordValue;
223         recordValue.Put(PrivacyFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenId));
224         recordValue.Put(PrivacyFiledConst::FIELD_PERMISSION_CODE, opCode);
225         recordValue.Put(PrivacyFiledConst::FIELD_USED_TYPE, static_cast<int32_t>(inputType));
226 
227         std::vector<GenericValues> recordValues;
228         recordValues.emplace_back(recordValue);
229         if (!PermissionRecordRepository::GetInstance().Add(
230             PermissionUsedRecordDb::DataType::PERMISSION_USED_TYPE, recordValues)) {
231             return false;
232         }
233     } else {
234         // not empty means there is permission used type record exsit, update it if needed
235         uint32_t dbType = static_cast<uint32_t>(results[0].GetInt(PrivacyFiledConst::FIELD_USED_TYPE));
236         ACCESSTOKEN_LOG_DEBUG(LABEL, "Record exsit, type is %{public}u.", dbType);
237 
238         if ((dbType & inputType) == inputType) {
239             // true means visitTypeEnum has exsits, no need to add
240             ACCESSTOKEN_LOG_DEBUG(LABEL, "Used type has add.");
241             return true;
242         } else {
243             results[0].Remove(PrivacyFiledConst::FIELD_USED_TYPE);
244             dbType |= inputType;
245 
246             // false means visitTypeEnum not exsits, update record
247             ACCESSTOKEN_LOG_DEBUG(LABEL, "Used type not add, generate new %{public}u.", dbType);
248 
249             GenericValues newValue;
250             newValue.Put(PrivacyFiledConst::FIELD_USED_TYPE, static_cast<int32_t>(dbType));
251             return PermissionRecordRepository::GetInstance().Update(
252                 PermissionUsedRecordDb::DataType::PERMISSION_USED_TYPE, newValue, results[0]);
253         }
254     }
255 
256     return true;
257 }
258 
AddPermissionUsedRecord(const AddPermParamInfo & info)259 int32_t PermissionRecordManager::AddPermissionUsedRecord(const AddPermParamInfo& info)
260 {
261     ExecuteDeletePermissionRecordTask();
262 
263     if ((info.successCount == 0) && (info.failCount == 0)) {
264         return PrivacyError::ERR_PARAM_INVALID;
265     }
266 
267     PermissionRecord record;
268     int32_t result = GetPermissionRecord(info, record);
269     if (result != Constant::SUCCESS || record.status == PERM_INACTIVE) {
270         return result;
271     }
272 
273     AddRecord(record);
274     return AddOrUpdateUsedTypeIfNeeded(
275         info.tokenId, record.opCode, info.type) ? Constant::SUCCESS : Constant::FAILURE;
276 }
277 
RemovePermissionUsedType(AccessTokenID tokenId)278 void PermissionRecordManager::RemovePermissionUsedType(AccessTokenID tokenId)
279 {
280     GenericValues conditionValues;
281     conditionValues.Put(PrivacyFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenId));
282     PermissionRecordRepository::GetInstance().Remove(
283         PermissionUsedRecordDb::DataType::PERMISSION_USED_TYPE, conditionValues);
284 }
285 
RemovePermissionUsedRecords(AccessTokenID tokenId,const std::string & deviceID)286 void PermissionRecordManager::RemovePermissionUsedRecords(AccessTokenID tokenId, const std::string& deviceID)
287 {
288     // only support remove by tokenId(local)
289     std::string device = GetDeviceId(tokenId);
290     if (!deviceID.empty() && device != deviceID) {
291         ACCESSTOKEN_LOG_ERROR(LABEL, "deviceID mismatch");
292         return;
293     }
294 
295     Utils::UniqueWriteGuard<Utils::RWLock> lk(this->rwLock_);
296     PermissionUsedRecordCache::GetInstance().RemoveRecords(tokenId); // remove from cache and database
297     RemovePermissionUsedType(tokenId);
298 
299     RemoveRecordFromStartListByToken(tokenId);
300 }
301 
GetPermissionUsedRecords(const PermissionUsedRequest & request,PermissionUsedResult & result)302 int32_t PermissionRecordManager::GetPermissionUsedRecords(
303     const PermissionUsedRequest& request, PermissionUsedResult& result)
304 {
305     ExecuteDeletePermissionRecordTask();
306 
307     if (!request.isRemote && !GetRecordsFromLocalDB(request, result)) {
308         ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to GetRecordsFromLocalDB");
309         return  PrivacyError::ERR_PARAM_INVALID;
310     }
311     return Constant::SUCCESS;
312 }
313 
GetPermissionUsedRecordsAsync(const PermissionUsedRequest & request,const sptr<OnPermissionUsedRecordCallback> & callback)314 int32_t PermissionRecordManager::GetPermissionUsedRecordsAsync(
315     const PermissionUsedRequest& request, const sptr<OnPermissionUsedRecordCallback>& callback)
316 {
317     auto task = [request, callback]() {
318         ACCESSTOKEN_LOG_INFO(LABEL, "GetPermissionUsedRecordsAsync task called");
319         PermissionUsedResult result;
320         int32_t retCode = PermissionRecordManager::GetInstance().GetPermissionUsedRecords(request, result);
321         callback->OnQueried(retCode, result);
322     };
323     std::thread recordThread(task);
324     recordThread.detach();
325     return Constant::SUCCESS;
326 }
327 
GetLocalRecordTokenIdList(std::set<AccessTokenID> & tokenIdList)328 void PermissionRecordManager::GetLocalRecordTokenIdList(std::set<AccessTokenID>& tokenIdList)
329 {
330     std::vector<GenericValues> results;
331     {
332         Utils::UniqueReadGuard<Utils::RWLock> lk(this->rwLock_);
333         // find tokenId from cache
334         PermissionUsedRecordCache::GetInstance().FindTokenIdList(tokenIdList);
335         // find tokenId from database
336         PermissionRecordRepository::GetInstance().GetAllRecordValuesByKey(PrivacyFiledConst::FIELD_TOKEN_ID, results);
337     }
338     for (const auto& res : results) {
339         tokenIdList.emplace(res.GetInt(PrivacyFiledConst::FIELD_TOKEN_ID));
340     }
341 }
342 
AddDebugLog(const AccessTokenID tokenId,const BundleUsedRecord & bundleRecord,const int32_t currentCount,int32_t & totalSuccCount,int32_t & totalFailCount)343 static void AddDebugLog(const AccessTokenID tokenId, const BundleUsedRecord& bundleRecord, const int32_t currentCount,
344     int32_t& totalSuccCount, int32_t& totalFailCount)
345 {
346     int32_t tokenTotalSuccCount = 0;
347     int32_t tokenTotalFailCount = 0;
348     for (const auto& permissionRecord : bundleRecord.permissionRecords) {
349         tokenTotalSuccCount += permissionRecord.accessCount;
350         tokenTotalFailCount += permissionRecord.rejectCount;
351     }
352     ACCESSTOKEN_LOG_INFO(LABEL, "tokenId %{public}d[%{public}s] get %{public}d records, success %{public}d,"
353         " failure %{public}d", tokenId, bundleRecord.bundleName.c_str(), currentCount, tokenTotalSuccCount,
354         tokenTotalFailCount);
355     totalSuccCount += tokenTotalSuccCount;
356     totalFailCount += tokenTotalFailCount;
357 }
358 
GetRecordsFromLocalDB(const PermissionUsedRequest & request,PermissionUsedResult & result)359 bool PermissionRecordManager::GetRecordsFromLocalDB(const PermissionUsedRequest& request, PermissionUsedResult& result)
360 {
361     GenericValues andConditionValues;
362     if (DataTranslator::TranslationIntoGenericValues(request, andConditionValues)
363         != Constant::SUCCESS) {
364         ACCESSTOKEN_LOG_ERROR(LABEL, "query time or flag is invalid");
365         return false;
366     }
367 
368     std::set<AccessTokenID> tokenIdList;
369     if (request.tokenId == 0) {
370         GetLocalRecordTokenIdList(tokenIdList);
371     } else {
372         tokenIdList.emplace(request.tokenId);
373     }
374 
375     // sumarry don't limit querry data num, detail do
376     int32_t dataLimitNum = request.flag == FLAG_PERMISSION_USAGE_DETAIL ? MAX_ACCESS_RECORD_SIZE : recordSizeMaximum_;
377     int32_t totalSuccCount = 0;
378     int32_t totalFailCount = 0;
379 
380     Utils::UniqueReadGuard<Utils::RWLock> lk(this->rwLock_);
381     for (const auto& tokenId : tokenIdList) {
382         andConditionValues.Put(PrivacyFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenId));
383         std::vector<GenericValues> findRecordsValues;
384         PermissionUsedRecordCache::GetInstance().GetRecords(request.permissionList,
385             andConditionValues, findRecordsValues, dataLimitNum); // find records from cache and database
386         andConditionValues.Remove(PrivacyFiledConst::FIELD_TOKEN_ID);
387         uint32_t currentCount = findRecordsValues.size();
388         dataLimitNum -= static_cast<int32_t>(currentCount);
389         BundleUsedRecord bundleRecord;
390         if (!CreateBundleUsedRecord(tokenId, bundleRecord)) {
391             continue;
392         }
393 
394         if (currentCount > 0) {
395             GetRecords(request.flag, findRecordsValues, bundleRecord, result);
396             // add debug log when get exsit record
397             AddDebugLog(tokenId, bundleRecord, currentCount, totalSuccCount, totalFailCount);
398         }
399 
400         if (!bundleRecord.permissionRecords.empty()) {
401             result.bundleRecords.emplace_back(bundleRecord);
402         }
403     }
404 
405     if (request.flag == FLAG_PERMISSION_USAGE_SUMMARY) {
406         ACCESSTOKEN_LOG_INFO(LABEL, "total success count is %{public}d, total failure count is %{public}d",
407             totalSuccCount, totalFailCount);
408     }
409 
410     return true;
411 }
412 
CreateBundleUsedRecord(const AccessTokenID tokenId,BundleUsedRecord & bundleRecord)413 bool PermissionRecordManager::CreateBundleUsedRecord(const AccessTokenID tokenId, BundleUsedRecord& bundleRecord)
414 {
415     HapTokenInfo tokenInfo;
416     if (AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo) != Constant::SUCCESS) {
417         ACCESSTOKEN_LOG_ERROR(LABEL, "GetHapTokenInfo failed");
418         return false;
419     }
420     bundleRecord.tokenId = tokenId;
421     bundleRecord.isRemote = false;
422     bundleRecord.deviceId = GetDeviceId(tokenId);
423     bundleRecord.bundleName = tokenInfo.bundleName;
424     return true;
425 }
426 
GetRecords(int32_t flag,std::vector<GenericValues> recordValues,BundleUsedRecord & bundleRecord,PermissionUsedResult & result)427 void PermissionRecordManager::GetRecords(
428     int32_t flag, std::vector<GenericValues> recordValues, BundleUsedRecord& bundleRecord, PermissionUsedResult& result)
429 {
430     std::vector<PermissionUsedRecord> permissionRecords;
431     for (auto it = recordValues.rbegin(); it != recordValues.rend(); ++it) {
432         GenericValues record = *it;
433         PermissionUsedRecord tmpPermissionRecord;
434         int64_t timestamp = record.GetInt64(PrivacyFiledConst::FIELD_TIMESTAMP);
435         result.beginTimeMillis = ((result.beginTimeMillis == 0) || (timestamp < result.beginTimeMillis)) ?
436             timestamp : result.beginTimeMillis;
437         result.endTimeMillis = (timestamp > result.endTimeMillis) ? timestamp : result.endTimeMillis;
438 
439         record.Put(PrivacyFiledConst::FIELD_FLAG, flag);
440         if (DataTranslator::TranslationGenericValuesIntoPermissionUsedRecord(record, tmpPermissionRecord)
441             != Constant::SUCCESS) {
442             ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to transform opcode(%{public}d) into permission",
443                 record.GetInt(PrivacyFiledConst::FIELD_OP_CODE));
444             continue;
445         }
446 
447         auto iter = std::find_if(permissionRecords.begin(), permissionRecords.end(),
448             [tmpPermissionRecord](const PermissionUsedRecord& rec) {
449             return tmpPermissionRecord.permissionName == rec.permissionName;
450         });
451         if (iter != permissionRecords.end()) {
452             UpdateRecords(flag, tmpPermissionRecord, *iter);
453         } else {
454             permissionRecords.emplace_back(tmpPermissionRecord);
455         }
456     }
457     bundleRecord.permissionRecords = permissionRecords;
458 }
459 
UpdateRecords(int32_t flag,const PermissionUsedRecord & inBundleRecord,PermissionUsedRecord & outBundleRecord)460 void PermissionRecordManager::UpdateRecords(
461     int32_t flag, const PermissionUsedRecord& inBundleRecord, PermissionUsedRecord& outBundleRecord)
462 {
463     outBundleRecord.accessCount += inBundleRecord.accessCount;
464     outBundleRecord.rejectCount += inBundleRecord.rejectCount;
465     if (inBundleRecord.lastAccessTime > outBundleRecord.lastAccessTime) {
466         outBundleRecord.lastAccessTime = inBundleRecord.lastAccessTime;
467         outBundleRecord.lastAccessDuration = inBundleRecord.lastAccessDuration;
468     }
469     outBundleRecord.lastRejectTime = (inBundleRecord.lastRejectTime > outBundleRecord.lastRejectTime) ?
470         inBundleRecord.lastRejectTime : outBundleRecord.lastRejectTime;
471 
472     if (flag != FLAG_PERMISSION_USAGE_DETAIL) {
473         return;
474     }
475     if (inBundleRecord.lastAccessTime > 0) {
476         outBundleRecord.accessRecords.emplace_back(inBundleRecord.accessRecords[0]);
477     }
478     if (inBundleRecord.lastRejectTime > 0) {
479         outBundleRecord.rejectRecords.emplace_back(inBundleRecord.rejectRecords[0]);
480     }
481 }
482 
ExecuteDeletePermissionRecordTask()483 void PermissionRecordManager::ExecuteDeletePermissionRecordTask()
484 {
485     if (deleteTaskWorker_.GetCurTaskNum() > 1) {
486         ACCESSTOKEN_LOG_INFO(LABEL, "Already has delete task!");
487         return;
488     }
489 
490     auto deleteRecordsTask = [this]() {
491         ACCESSTOKEN_LOG_DEBUG(LABEL, "DeletePermissionRecord task called");
492         DeletePermissionRecord(recordAgingTime_);
493     };
494     deleteTaskWorker_.AddTask(deleteRecordsTask);
495 }
496 
DeletePermissionRecord(int32_t days)497 int32_t PermissionRecordManager::DeletePermissionRecord(int32_t days)
498 {
499     int64_t interval = days * Constant::ONE_DAY_MILLISECONDS;
500     GenericValues countValue;
501     PermissionRecordRepository::GetInstance().CountRecordValues(countValue);
502     int64_t total = countValue.GetInt64(FIELD_COUNT_NUMBER);
503     if (total > recordSizeMaximum_) {
504         uint32_t excessiveSize = static_cast<uint32_t>(total) - static_cast<uint32_t>(recordSizeMaximum_);
505         if (!PermissionRecordRepository::GetInstance().DeleteExcessiveSizeRecordValues(excessiveSize)) {
506             return Constant::FAILURE;
507         }
508     }
509     GenericValues andConditionValues;
510     int64_t deleteTimestamp = TimeUtil::GetCurrentTimestamp() - interval;
511     andConditionValues.Put(PrivacyFiledConst::FIELD_TIMESTAMP_END, deleteTimestamp);
512     if (!PermissionRecordRepository::GetInstance().DeleteExpireRecordsValues(andConditionValues)) {
513         return Constant::FAILURE;
514     }
515     return Constant::SUCCESS;
516 }
517 
AddRecordToStartList(const PermissionRecord & record)518 bool PermissionRecordManager::AddRecordToStartList(const PermissionRecord& record)
519 {
520     std::lock_guard<std::mutex> lock(startRecordListMutex_);
521     bool hasStarted = std::any_of(startRecordList_.begin(), startRecordList_.end(),
522         [record](const auto& rec) { return (rec.opCode == record.opCode) && (rec.tokenId == record.tokenId); });
523     if (hasStarted) {
524         ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId(%{public}d), opCode(%{public}d) has been started.",
525             record.tokenId, record.opCode);
526     } else {
527         ACCESSTOKEN_LOG_DEBUG(LABEL, "tokenId(%{public}d), opCode(%{public}d) add record.",
528             record.tokenId, record.opCode);
529         startRecordList_.emplace_back(record);
530     }
531     return hasStarted;
532 }
533 
ExecuteAndUpdateRecord(uint32_t tokenId,ActiveChangeType status)534 void PermissionRecordManager::ExecuteAndUpdateRecord(uint32_t tokenId, ActiveChangeType status)
535 {
536     std::vector<std::string> permList;
537     std::vector<std::string> camPermList;
538     std::lock_guard<std::mutex> lock(startRecordListMutex_);
539     for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) {
540         if ((it->tokenId == tokenId) && ((it->status) != PERM_INACTIVE) && ((it->status) != status)) {
541             std::string perm;
542             Constant::TransferOpcodeToPermission(it->opCode, perm);
543             if ((GetMuteStatus(perm, EDM)) || (!GetGlobalSwitchStatus(perm))) {
544                 continue;
545             }
546 
547             // app use camera background without float window
548             bool isShow = IsCameraWindowShow(tokenId);
549             if ((perm == CAMERA_PERMISSION_NAME) && (status == PERM_ACTIVE_IN_BACKGROUND) && (!isShow)) {
550                 ACCESSTOKEN_LOG_INFO(LABEL, "camera float window is close!");
551                 camPermList.emplace_back(perm);
552                 continue;
553             }
554             permList.emplace_back(perm);
555             int64_t curStamp = TimeUtil::GetCurrentTimestamp();
556 
557             // update status to input and timestamp to now in cache
558             it->status = status;
559             it->timestamp = curStamp;
560             ACCESSTOKEN_LOG_DEBUG(LABEL, "tokenId %{public}d get permission %{public}s.", tokenId, perm.c_str());
561         }
562     }
563 
564     if (!camPermList.empty()) {
565         ExecuteCameraCallbackAsync(tokenId);
566     }
567     // each permission sends a status change notice
568     for (const auto& perm : permList) {
569         CallbackExecute(tokenId, perm, status);
570     }
571 }
572 
573 /*
574  * when foreground change background or background change foreground,change accessDuration and store in database,
575  * change status and accessDuration and timestamp in cache
576 */
NotifyAppStateChange(AccessTokenID tokenId,ActiveChangeType status)577 void PermissionRecordManager::NotifyAppStateChange(AccessTokenID tokenId, ActiveChangeType status)
578 {
579     ACCESSTOKEN_LOG_INFO(LABEL, "tokenId %{public}d, status %{public}d", tokenId, status);
580     // find permissions from startRecordList_ by tokenId which status diff from currStatus
581     ExecuteAndUpdateRecord(tokenId, status);
582 }
583 
SetLockScreenStatus(int32_t lockScreenStatus)584 void PermissionRecordManager::SetLockScreenStatus(int32_t lockScreenStatus)
585 {
586     ACCESSTOKEN_LOG_INFO(LABEL, "lockScreenStatus %{public}d", lockScreenStatus);
587     std::lock_guard<std::mutex> lock(lockScreenStateMutex_);
588     lockScreenStatus_ = lockScreenStatus;
589 }
590 
GetLockScreenStatus()591 int32_t PermissionRecordManager::GetLockScreenStatus()
592 {
593     std::lock_guard<std::mutex> lock(lockScreenStateMutex_);
594     return lockScreenStatus_;
595 }
596 
IsScreenOn()597 bool PermissionRecordManager::IsScreenOn()
598 {
599     LibraryLoader loader(POWER_MANAGER_LIBPATH);
600     PowerManagerLoaderInterface* powerManagerLoader = loader.GetObject<PowerManagerLoaderInterface>();
601     if (powerManagerLoader == nullptr) {
602         ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to load powermanager so.");
603         return false;
604     }
605     return powerManagerLoader->IsScreenOn();
606 }
607 
RemoveRecordFromStartList(const PermissionRecord & record)608 void PermissionRecordManager::RemoveRecordFromStartList(const PermissionRecord& record)
609 {
610     ACCESSTOKEN_LOG_DEBUG(LABEL, "tokenId %{public}d, opCode %{public}d", record.tokenId, record.opCode);
611     std::lock_guard<std::mutex> lock(startRecordListMutex_);
612     for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) {
613         if ((it->opCode == record.opCode) && (it->tokenId == record.tokenId)) {
614             startRecordList_.erase(it);
615             return;
616         }
617     }
618 }
619 
RemoveRecordFromStartListByToken(const AccessTokenID tokenId)620 void PermissionRecordManager::RemoveRecordFromStartListByToken(const AccessTokenID tokenId)
621 {
622     ACCESSTOKEN_LOG_INFO(LABEL, "tokenId %{public}d", tokenId);
623     bool isUsingCamera = false;
624     {
625         std::vector<std::string> permList;
626         std::lock_guard<std::mutex> lock(startRecordListMutex_);
627         for (auto it = startRecordList_.begin(); it != startRecordList_.end();) {
628             if (it->tokenId != tokenId) {
629                 it++;
630                 continue;
631             }
632             isUsingCamera = (it->opCode == Constant::OP_CAMERA);
633             std::string perm;
634             Constant::TransferOpcodeToPermission(it->opCode, perm);
635             permList.emplace_back(perm);
636             it = startRecordList_.erase(it);
637         }
638         for (const auto& perm : permList) {
639             CallbackExecute(tokenId, perm, PERM_INACTIVE);
640         }
641     }
642     if (isUsingCamera) {
643         cameraCallbackMap_.Erase(tokenId);
644         UnRegisterWindowCallback(); // unregister window linstener
645     }
646 }
647 
RemoveRecordFromStartListByOp(int32_t opCode)648 void PermissionRecordManager::RemoveRecordFromStartListByOp(int32_t opCode)
649 {
650     ACCESSTOKEN_LOG_INFO(LABEL, "opCode %{public}d", opCode);
651     bool isUsingCamera = (opCode == Constant::OP_CAMERA);
652     std::string perm;
653     Constant::TransferOpcodeToPermission(opCode, perm);
654     {
655         std::vector<AccessTokenID> tokenList;
656         std::lock_guard<std::mutex> lock(startRecordListMutex_);
657         for (auto it = startRecordList_.begin(); it != startRecordList_.end();) {
658             if (it->opCode != opCode) {
659                 it++;
660                 continue;
661             }
662             tokenList.emplace_back(it->tokenId);
663             it = startRecordList_.erase(it);
664         }
665         for (size_t i = 0; i < tokenList.size(); ++i) {
666             CallbackExecute(tokenList[i], perm, PERM_INACTIVE);
667         }
668     }
669     if (isUsingCamera) {
670         UnRegisterWindowCallback(); // unregister window linstener
671     }
672 }
673 
GetRecordFromStartList(uint32_t tokenId,int32_t opCode,PermissionRecord & record)674 bool PermissionRecordManager::GetRecordFromStartList(uint32_t tokenId,  int32_t opCode, PermissionRecord& record)
675 {
676     std::lock_guard<std::mutex> lock(startRecordListMutex_);
677     for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) {
678         if ((it->opCode == opCode) && (it->tokenId == tokenId)) {
679             it->accessCount = 1;
680             record = *it;
681             record.accessDuration = TimeUtil::GetCurrentTimestamp() - record.timestamp;
682             startRecordList_.erase(it);
683             return true;
684         }
685     }
686     return false;
687 }
688 
CallbackExecute(AccessTokenID tokenId,const std::string & permissionName,int32_t status)689 void PermissionRecordManager::CallbackExecute(
690     AccessTokenID tokenId, const std::string& permissionName, int32_t status)
691 {
692     ACCESSTOKEN_LOG_INFO(LABEL,
693         "ExecuteCallbackAsync, tokenId %{public}d using permission %{public}s, status %{public}d",
694         tokenId, permissionName.c_str(), status);
695     ActiveStatusCallbackManager::GetInstance().ExecuteCallbackAsync(
696         tokenId, permissionName, GetDeviceId(tokenId), (ActiveChangeType)status);
697 }
698 
GetGlobalSwitchStatus(const std::string & permissionName)699 bool PermissionRecordManager::GetGlobalSwitchStatus(const std::string& permissionName)
700 {
701     bool isOpen = true;
702     // only manage camera and microphone global switch now, other default true
703     if (permissionName == MICROPHONE_PERMISSION_NAME) {
704         isOpen = !isMicMixMute_;
705     } else if (permissionName == CAMERA_PERMISSION_NAME) {
706         isOpen = !isCamMixMute_;
707     }
708 
709     ACCESSTOKEN_LOG_INFO(LABEL, "permission is %{public}s, status is %{public}d", permissionName.c_str(), isOpen);
710     return isOpen;
711 }
712 
713 /*
714  * StartUsing when close and choose open, update status to foreground or background from inactive
715  * StartUsing when open and choose close, update status to inactive and store in database
716  */
ExecuteAndUpdateRecordByPerm(const std::string & permissionName,bool switchStatus)717 void PermissionRecordManager::ExecuteAndUpdateRecordByPerm(const std::string& permissionName, bool switchStatus)
718 {
719     int32_t opCode;
720     Constant::TransferPermissionToOpcode(permissionName, opCode);
721     std::vector<PermissionRecord> recordList;
722     std::lock_guard<std::mutex> lock(startRecordListMutex_);
723     for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) {
724         PermissionRecord& record = *it;
725         if ((record.opCode) != static_cast<int32_t>(opCode)) {
726             continue;
727         }
728         if (switchStatus) {
729             ACCESSTOKEN_LOG_INFO(LABEL, "global switch is open, update record from inactive");
730             // no need to store in database when status from inactive to foreground or background
731             record.status = GetAppStatus(record.tokenId);
732         } else {
733             ACCESSTOKEN_LOG_INFO(LABEL, "global switch is close, update record to inactive");
734             record.status = PERM_INACTIVE;
735         }
736         recordList.emplace_back(*it);
737     }
738     // each permission sends a status change notice
739     for (const auto& record : recordList) {
740         CallbackExecute(record.tokenId, permissionName, record.status);
741     }
742 }
743 
NotifyMicChange(bool isMute)744 void PermissionRecordManager::NotifyMicChange(bool isMute)
745 {
746     ACCESSTOKEN_LOG_INFO(LABEL, "OnMicStateChange(%{public}d)", isMute);
747     if (SetPrivacyMutePolicy(MICROPHONE_PERMISSION_NAME, isMute) != RET_SUCCESS) {
748         return;
749     }
750     // find permissions from startRecordList_ by tokenId which status diff from currStatus
751     ExecuteAndUpdateRecordByPerm(MICROPHONE_PERMISSION_NAME, !isMute);
752 }
753 
NotifyCameraChange(bool isMute)754 void PermissionRecordManager::NotifyCameraChange(bool isMute)
755 {
756     ACCESSTOKEN_LOG_INFO(LABEL, "OnCameraStateChange(%{public}d)", isMute);
757     if (SetPrivacyMutePolicy(CAMERA_PERMISSION_NAME, isMute) != RET_SUCCESS) {
758         return;
759     }
760 
761     // find permissions from startRecordList_ by tokenId which status diff from currStatus
762     ExecuteAndUpdateRecordByPerm(CAMERA_PERMISSION_NAME, !isMute);
763 }
764 
ShowGlobalDialog(const std::string & permissionName)765 bool PermissionRecordManager::ShowGlobalDialog(const std::string& permissionName)
766 {
767     std::string resource;
768     if (permissionName == CAMERA_PERMISSION_NAME) {
769         resource = "camera";
770     } else if (permissionName == MICROPHONE_PERMISSION_NAME) {
771         resource = "microphone";
772     } else {
773         ACCESSTOKEN_LOG_INFO(LABEL, "invalid permissionName(%{public}s).", permissionName.c_str());
774         return true;
775     }
776 
777     AAFwk::Want want;
778     want.SetElementName(globalDialogBundleName_, globalDialogAbilityName_);
779     want.SetParam(RESOURCE_KEY, resource);
780     ErrCode err = AbilityManagerAccessClient::GetInstance().StartAbility(want, nullptr);
781     if (err != ERR_OK) {
782         ACCESSTOKEN_LOG_ERROR(LABEL, "Fail to StartAbility, err:%{public}d", err);
783         return false;
784     }
785     return true;
786 }
787 
StartUsingPermission(AccessTokenID tokenId,const std::string & permissionName)788 int32_t PermissionRecordManager::StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName)
789 {
790     ACCESSTOKEN_LOG_INFO(LABEL, "Entry, tokenId=0x%{public}x, permissionName=%{public}s",
791         tokenId, permissionName.c_str());
792     if (GetMuteStatus(permissionName, EDM)) {
793         ACCESSTOKEN_LOG_ERROR(LABEL, "EDM not allow.");
794         return PrivacyError::ERR_EDM_POLICY_CHECK_FAILED;
795     }
796     if (!Register()) {
797         return PrivacyError::ERR_MALLOC_FAILED;
798     }
799 
800     // instantaneous record accessCount set to zero in StartUsingPermission, wait for combine in StopUsingPermission
801     int32_t accessCount = 0;
802     int32_t failCount = 0;
803     AddPermParamInfo info;
804     info.tokenId = tokenId;
805     info.permissionName = permissionName;
806     info.successCount = accessCount;
807     info.failCount = failCount;
808 
809     PermissionRecord record = { 0 };
810     int32_t result = GetPermissionRecord(info, record);
811     if (result != Constant::SUCCESS) {
812         return result;
813     }
814 
815     if (AddRecordToStartList(record)) {
816         return PrivacyError::ERR_PERMISSION_ALREADY_START_USING;
817     }
818 
819     if (!GetGlobalSwitchStatus(permissionName)) {
820         if (!ShowGlobalDialog(permissionName)) {
821             ACCESSTOKEN_LOG_ERROR(LABEL, "show permission dialog failed.");
822             RemoveRecordFromStartList(record);
823             UnRegisterWindowCallback();
824             return ERR_SERVICE_ABNORMAL;
825         }
826     } else {
827         CallbackExecute(tokenId, permissionName, record.status);
828     }
829     return Constant::SUCCESS;
830 }
831 
ExecuteAllCameraExecuteCallback()832 void PermissionRecordManager::ExecuteAllCameraExecuteCallback()
833 {
834     std::vector<AccessTokenID> tokenList;
835     {
836         std::lock_guard<std::mutex> lock(startRecordListMutex_);
837         for (auto iter = startRecordList_.begin(); iter != startRecordList_.end(); ++iter) {
838             if (iter->opCode != Constant::OP_CAMERA) {
839                 continue;
840             }
841             tokenList.emplace_back(iter->tokenId);
842         }
843     }
844     for (size_t i = 0; i < tokenList.size(); ++i) {
845         ExecuteCameraCallbackAsync(tokenList[i]);
846     }
847 }
848 
ExecuteCameraCallbackAsync(AccessTokenID tokenId)849 void PermissionRecordManager::ExecuteCameraCallbackAsync(AccessTokenID tokenId)
850 {
851     ACCESSTOKEN_LOG_DEBUG(LABEL, "entry");
852     auto task = [tokenId, this]() {
853         ACCESSTOKEN_LOG_INFO(LABEL, "ExecuteCameraCallbackAsync task called");
854         auto it = [&](AccessTokenID id, sptr<IRemoteObject> cameraCallback) {
855             auto callback = iface_cast<IStateChangeCallback>(cameraCallback);
856             if ((tokenId == id) && (callback != nullptr)) {
857                 ACCESSTOKEN_LOG_INFO(
858                     LABEL, "CameraCallback tokenId %{public}d changeType %{public}d", tokenId, PERM_INACTIVE);
859                 callback->StateChangeNotify(tokenId, false);
860             }
861         };
862         this->cameraCallbackMap_.Iterate(it);
863     };
864     std::thread executeThread(task);
865     executeThread.detach();
866     ACCESSTOKEN_LOG_DEBUG(LABEL, "The cameraCallback execution is complete");
867 }
868 
StartUsingPermission(AccessTokenID tokenId,const std::string & permissionName,const sptr<IRemoteObject> & callback)869 int32_t PermissionRecordManager::StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName,
870     const sptr<IRemoteObject>& callback)
871 {
872     ACCESSTOKEN_LOG_INFO(LABEL, "Entry, tokenId=0x%{public}x, permissionName=%{public}s",
873         tokenId, permissionName.c_str());
874     if (permissionName != CAMERA_PERMISSION_NAME) {
875         ACCESSTOKEN_LOG_ERROR(LABEL, "ERR_PARAM_INVALID is null.");
876         return PrivacyError::ERR_PARAM_INVALID;
877     }
878 
879     if (!Register()) {
880         return PrivacyError::ERR_MALLOC_FAILED;
881     }
882 
883     // instantaneous record accessCount set to zero in StartUsingPermission, wait for combine in StopUsingPermission
884     int32_t accessCount = 0;
885     int32_t failCount = 0;
886     PermissionRecord record = { 0 };
887     AddPermParamInfo info;
888     info.tokenId = tokenId;
889     info.permissionName = permissionName;
890     info.successCount = accessCount;
891     info.failCount = failCount;
892     int32_t result = GetPermissionRecord(info, record);
893     if (result != Constant::SUCCESS) {
894         return result;
895     }
896     cameraCallbackMap_.EnsureInsert(tokenId, callback);
897     if (AddRecordToStartList(record)) {
898         cameraCallbackMap_.Erase(tokenId);
899         return PrivacyError::ERR_PERMISSION_ALREADY_START_USING;
900     }
901     if (!RegisterWindowCallback()) {
902         cameraCallbackMap_.Erase(tokenId);
903         return PrivacyError::ERR_WINDOW_CALLBACK_FAILED;
904     }
905     if (!GetGlobalSwitchStatus(permissionName)) {
906         if (!ShowGlobalDialog(permissionName)) {
907             ACCESSTOKEN_LOG_ERROR(LABEL, "show permission dialog failed.");
908             RemoveRecordFromStartList(record);
909             UnRegisterWindowCallback();
910             cameraCallbackMap_.Erase(tokenId);
911             return ERR_SERVICE_ABNORMAL;
912         }
913     } else {
914         CallbackExecute(tokenId, permissionName, record.status);
915     }
916     return Constant::SUCCESS;
917 }
918 
StopUsingPermission(AccessTokenID tokenId,const std::string & permissionName)919 int32_t PermissionRecordManager::StopUsingPermission(AccessTokenID tokenId, const std::string& permissionName)
920 {
921     ACCESSTOKEN_LOG_INFO(LABEL, "Entry, tokenId=0x%{public}x, permissionName=%{public}s",
922         tokenId, permissionName.c_str());
923     ExecuteDeletePermissionRecordTask();
924 
925     if (AccessTokenKit::GetTokenTypeFlag(tokenId) != TOKEN_HAP) {
926         ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenId(%{public}d)", tokenId);
927         return PrivacyError::ERR_PARAM_INVALID;
928     }
929     int32_t opCode;
930     if (!Constant::TransferPermissionToOpcode(permissionName, opCode)) {
931         ACCESSTOKEN_LOG_ERROR(LABEL, "invalid permission(%{public}s)", permissionName.c_str());
932         return PrivacyError::ERR_PERMISSION_NOT_EXIST;
933     }
934 
935     PermissionRecord record;
936     if (!GetRecordFromStartList(tokenId, opCode, record)) {
937         return PrivacyError::ERR_PERMISSION_NOT_START_USING;
938     }
939 
940     if (record.status != PERM_INACTIVE) {
941         CallbackExecute(tokenId, permissionName, PERM_INACTIVE);
942     }
943     // clear callback
944     UnRegisterWindowCallback();
945     return Constant::SUCCESS;
946 }
947 
PermListToString(const std::vector<std::string> & permList)948 void PermissionRecordManager::PermListToString(const std::vector<std::string>& permList)
949 {
950     std::string permStr;
951     permStr = accumulate(permList.begin(), permList.end(), std::string(" "));
952 
953     ACCESSTOKEN_LOG_INFO(LABEL, "permStr =%{public}s", permStr.c_str());
954 }
955 
PermissionListFilter(const std::vector<std::string> & listSrc,std::vector<std::string> & listRes)956 int32_t PermissionRecordManager::PermissionListFilter(
957     const std::vector<std::string>& listSrc, std::vector<std::string>& listRes)
958 {
959     // filter legal permissions
960     PermissionDef permissionDef;
961     std::set<std::string> permSet;
962     for (const auto& permissionName : listSrc) {
963         if (AccessTokenKit::GetDefPermission(permissionName, permissionDef) == Constant::SUCCESS &&
964             permSet.count(permissionName) == 0) {
965             listRes.emplace_back(permissionName);
966             permSet.insert(permissionName);
967             continue;
968         }
969         ACCESSTOKEN_LOG_ERROR(LABEL, "permission %{public}s invalid!", permissionName.c_str());
970     }
971     if ((listRes.empty()) && (!listSrc.empty())) {
972         ACCESSTOKEN_LOG_ERROR(LABEL, "valid permission size is 0!");
973         return PrivacyError::ERR_PARAM_INVALID;
974     }
975     PermListToString(listRes);
976     return Constant::SUCCESS;
977 }
978 
IsAllowedUsingCamera(AccessTokenID tokenId)979 bool PermissionRecordManager::IsAllowedUsingCamera(AccessTokenID tokenId)
980 {
981     int32_t status = GetAppStatus(tokenId);
982     bool isScreenOn = IsScreenOn();
983     ACCESSTOKEN_LOG_INFO(LABEL, "tokenId(%{public}d), appStatus(%{public}d), isScreenOn(%{public}d)",
984         tokenId, status, isScreenOn);
985 
986     return (status == ActiveChangeType::PERM_ACTIVE_IN_FOREGROUND) && isScreenOn;
987 }
988 
IsAllowedUsingMicrophone(AccessTokenID tokenId)989 bool PermissionRecordManager::IsAllowedUsingMicrophone(AccessTokenID tokenId)
990 {
991     bool isEdmMute = false;
992     if (!GetMuteParameter(EDM_MIC_MUTE_KEY, isEdmMute)) {
993         ACCESSTOKEN_LOG_ERROR(LABEL, "Get param failed");
994         return false;
995     }
996     if (isEdmMute) {
997         ACCESSTOKEN_LOG_ERROR(LABEL, "EDM not allow.");
998         return false;
999     }
1000 
1001     int32_t status = GetAppStatus(tokenId);
1002     ACCESSTOKEN_LOG_INFO(LABEL, "TokenId %{public}d, status is %{public}d", tokenId, status);
1003     if (status == ActiveChangeType::PERM_ACTIVE_IN_FOREGROUND) {
1004         return true;
1005     }
1006 
1007     bool isContinuousTaskExist = false;
1008 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
1009     std::vector<std::shared_ptr<ContinuousTaskCallbackInfo>> continuousTaskList;
1010     BackgourndTaskManagerAccessClient::GetInstance().GetContinuousTaskApps(continuousTaskList);
1011     for (const auto& callbackInfo : continuousTaskList) {
1012         if (callbackInfo == nullptr) {
1013             ACCESSTOKEN_LOG_ERROR(LABEL, "callbackInfo is NULL.");
1014             continue;
1015         }
1016         AccessTokenID conTaskTokenID = static_cast<AccessTokenID>(callbackInfo->tokenId_);
1017         ACCESSTOKEN_LOG_INFO(LABEL, "tokenId %{public}d, typeId is %{public}d", conTaskTokenID, callbackInfo->typeId_);
1018         if ((conTaskTokenID == tokenId) &&
1019             (static_cast<BackgroundMode>(callbackInfo->typeId_) == BackgroundMode::VOIP)) {
1020             isContinuousTaskExist = true;
1021             break;
1022         }
1023     }
1024 #endif
1025     return isContinuousTaskExist;
1026 }
1027 
IsAllowedUsingPermission(AccessTokenID tokenId,const std::string & permissionName)1028 bool PermissionRecordManager::IsAllowedUsingPermission(AccessTokenID tokenId, const std::string& permissionName)
1029 {
1030     if (AccessTokenKit::GetTokenTypeFlag(tokenId) != TOKEN_HAP) {
1031         ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId(%{public}d) is not hap.", tokenId);
1032         return false;
1033     }
1034 
1035     if (permissionName == CAMERA_PERMISSION_NAME) {
1036         return IsAllowedUsingCamera(tokenId);
1037     } else if (permissionName == MICROPHONE_PERMISSION_NAME) {
1038         return IsAllowedUsingMicrophone(tokenId);
1039     }
1040     ACCESSTOKEN_LOG_ERROR(LABEL, "Invalid permission(%{public}s).", permissionName.c_str());
1041     return false;
1042 }
1043 
SetMutePolicy(const PolicyType & policyType,const CallerType & callerType,bool isMute)1044 int32_t PermissionRecordManager::SetMutePolicy(const PolicyType& policyType, const CallerType& callerType, bool isMute)
1045 {
1046     ACCESSTOKEN_LOG_INFO(LABEL, "CallerType: %{public}d, isMute: %{public}d", callerType, isMute);
1047     std::string permissionName;
1048     if (callerType == MICROPHONE) {
1049         permissionName = MICROPHONE_PERMISSION_NAME;
1050     } else if (callerType == CAMERA) {
1051         permissionName = CAMERA_PERMISSION_NAME;
1052     } else {
1053         ACCESSTOKEN_LOG_ERROR(LABEL, "Invalid type: %{public}d.", callerType);
1054         return PrivacyError::ERR_PARAM_INVALID;
1055     }
1056 
1057     if (policyType == EDM) {
1058         return SetEdmMutePolicy(permissionName, isMute);
1059     }
1060 
1061     if (policyType == PRIVACY) {
1062         return SetPrivacyMutePolicy(permissionName, isMute);
1063     }
1064 
1065     if (policyType == TEMPORARY) {
1066         return SetTempMutePolicy(permissionName, isMute);
1067     }
1068     return RET_FAILED;
1069 }
1070 
SetEdmMutePolicy(const std::string permissionName,bool & isMute)1071 int32_t PermissionRecordManager::SetEdmMutePolicy(const std::string permissionName, bool& isMute)
1072 {
1073     if (isMute) {
1074         ModifyMuteStatus(permissionName, EDM, isMute);
1075         ModifyMuteStatus(permissionName, MIXED, isMute);
1076     } else {
1077         ModifyMuteStatus(permissionName, EDM, isMute);
1078         isMute = GetMuteStatus(permissionName, MIXED);
1079     }
1080     ACCESSTOKEN_LOG_INFO(LABEL, "permissionName: %{public}s, isMute: %{public}d", permissionName.c_str(), isMute);
1081     return RET_SUCCESS;
1082 }
1083 
SetPrivacyMutePolicy(const std::string permissionName,bool & isMute)1084 int32_t PermissionRecordManager::SetPrivacyMutePolicy(const std::string permissionName, bool& isMute)
1085 {
1086     if (isMute) {
1087         ModifyMuteStatus(permissionName, MIXED, isMute);
1088     } else {
1089         if (GetMuteStatus(permissionName, EDM)) {
1090             isMute = true;
1091             return PrivacyError::ERR_EDM_POLICY_CHECK_FAILED;
1092         }
1093         ModifyMuteStatus(permissionName, MIXED, isMute);
1094     }
1095     ACCESSTOKEN_LOG_INFO(LABEL, "permissionName: %{public}s, isMute: %{public}d", permissionName.c_str(), isMute);
1096     return RET_SUCCESS;
1097 }
1098 
SetTempMutePolicy(const std::string permissionName,bool & isMute)1099 int32_t PermissionRecordManager::SetTempMutePolicy(const std::string permissionName, bool& isMute)
1100 {
1101     if (!isMute) {
1102         if (GetMuteStatus(permissionName, EDM)) {
1103             return PrivacyError::ERR_EDM_POLICY_CHECK_FAILED;
1104         }
1105         if (GetMuteStatus(permissionName, MIXED)) {
1106             if (!ShowGlobalDialog(permissionName)) {
1107                 ACCESSTOKEN_LOG_ERROR(LABEL, "show permission dialog failed.");
1108                 return ERR_SERVICE_ABNORMAL;
1109             }
1110             isMute = true;
1111             return PrivacyError::ERR_PRIVACY_POLICY_CHECK_FAILED;
1112         }
1113     }
1114     ACCESSTOKEN_LOG_INFO(LABEL, "permissionName: %{public}s, isMute: %{public}d", permissionName.c_str(), isMute);
1115     return RET_SUCCESS;
1116 }
1117 
ModifyMuteStatus(const std::string & permissionName,int32_t index,bool isMute)1118 void PermissionRecordManager::ModifyMuteStatus(const std::string& permissionName, int32_t index, bool isMute)
1119 {
1120     if (permissionName == MICROPHONE_PERMISSION_NAME) {
1121         std::lock_guard<std::mutex> lock(micMuteMutex_);
1122         if (index == EDM) {
1123             isMicEdmMute_ = isMute;
1124         } else {
1125             isMicMixMute_ = isMute;
1126         }
1127     } else if (permissionName == CAMERA_PERMISSION_NAME) {
1128         std::lock_guard<std::mutex> lock(camMuteMutex_);
1129         if (index == EDM) {
1130             isCamEdmMute_ = isMute;
1131         } else {
1132             isCamMixMute_ = isMute;
1133         }
1134     }
1135     ACCESSTOKEN_LOG_INFO(LABEL, "permissionName: %{public}s, isMute: %{public}d, index: %{public}d",
1136         permissionName.c_str(), isMute, index);
1137 }
1138 
GetMuteStatus(const std::string & permissionName,int32_t index)1139 bool PermissionRecordManager::GetMuteStatus(const std::string& permissionName, int32_t index)
1140 {
1141     bool isMute = false;
1142     if (permissionName == MICROPHONE_PERMISSION_NAME) {
1143         std::lock_guard<std::mutex> lock(micMuteMutex_);
1144         isMute = (index == EDM) ? isMicEdmMute_ : isMicMixMute_;
1145     } else if (permissionName == CAMERA_PERMISSION_NAME) {
1146         std::lock_guard<std::mutex> lock(camMuteMutex_);
1147         isMute = (index == EDM) ? isCamEdmMute_ : isCamMixMute_;
1148     }
1149     ACCESSTOKEN_LOG_INFO(LABEL, "permissionName: %{public}s, isMute: %{public}d, index: %{public}d",
1150         permissionName.c_str(), isMute, index);
1151     return isMute;
1152 }
1153 
RegisterPermActiveStatusCallback(const std::vector<std::string> & permList,const sptr<IRemoteObject> & callback)1154 int32_t PermissionRecordManager::RegisterPermActiveStatusCallback(
1155     const std::vector<std::string>& permList, const sptr<IRemoteObject>& callback)
1156 {
1157     std::vector<std::string> permListRes;
1158     int32_t res = PermissionListFilter(permList, permListRes);
1159     if (res != Constant::SUCCESS) {
1160         return res;
1161     }
1162     return ActiveStatusCallbackManager::GetInstance().AddCallback(permListRes, callback);
1163 }
1164 
UnRegisterPermActiveStatusCallback(const sptr<IRemoteObject> & callback)1165 int32_t PermissionRecordManager::UnRegisterPermActiveStatusCallback(const sptr<IRemoteObject>& callback)
1166 {
1167     return ActiveStatusCallbackManager::GetInstance().RemoveCallback(callback);
1168 }
1169 
AddDataValueToResults(const GenericValues value,std::vector<PermissionUsedTypeInfo> & results)1170 void PermissionRecordManager::AddDataValueToResults(const GenericValues value,
1171     std::vector<PermissionUsedTypeInfo>& results)
1172 {
1173     PermissionUsedTypeInfo info;
1174     info.tokenId = static_cast<AccessTokenID>(value.GetInt(PrivacyFiledConst::FIELD_TOKEN_ID));
1175     Constant::TransferOpcodeToPermission(value.GetInt(PrivacyFiledConst::FIELD_PERMISSION_CODE), info.permissionName);
1176     uint32_t type = static_cast<uint32_t>(value.GetInt(PrivacyFiledConst::FIELD_USED_TYPE));
1177     if ((type & NORMAL_TYPE_ADD_VALUE) == NORMAL_TYPE_ADD_VALUE) { // normal first
1178         info.type = PermissionUsedType::NORMAL_TYPE;
1179         results.emplace_back(info);
1180     }
1181     if ((type & PICKER_TYPE_ADD_VALUE) == PICKER_TYPE_ADD_VALUE) { // picker second
1182         info.type = PermissionUsedType::PICKER_TYPE;
1183         results.emplace_back(info);
1184     }
1185     if ((type & SEC_COMPONENT_TYPE_ADD_VALUE) == SEC_COMPONENT_TYPE_ADD_VALUE) { // security component last
1186         info.type = PermissionUsedType::SECURITY_COMPONENT_TYPE;
1187         results.emplace_back(info);
1188     }
1189 }
1190 
GetPermissionUsedTypeInfos(AccessTokenID tokenId,const std::string & permissionName,std::vector<PermissionUsedTypeInfo> & results)1191 int32_t PermissionRecordManager::GetPermissionUsedTypeInfos(AccessTokenID tokenId, const std::string& permissionName,
1192     std::vector<PermissionUsedTypeInfo>& results)
1193 {
1194     GenericValues value;
1195 
1196     if (tokenId != INVALID_TOKENID) {
1197         HapTokenInfo tokenInfo;
1198         if (AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo) != Constant::SUCCESS) {
1199             ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenId(%{public}d)", tokenId);
1200             return PrivacyError::ERR_TOKENID_NOT_EXIST;
1201         }
1202         value.Put(PrivacyFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenId));
1203     }
1204 
1205     if (!permissionName.empty()) {
1206         int32_t opCode;
1207         if (!Constant::TransferPermissionToOpcode(permissionName, opCode)) {
1208             ACCESSTOKEN_LOG_ERROR(LABEL, "invalid (%{public}s)", permissionName.c_str());
1209             return PrivacyError::ERR_PERMISSION_NOT_EXIST;
1210         }
1211         value.Put(PrivacyFiledConst::FIELD_PERMISSION_CODE, opCode);
1212     }
1213 
1214     std::vector<GenericValues> valueResults;
1215     if (!PermissionRecordRepository::GetInstance().Query(
1216         PermissionUsedRecordDb::DataType::PERMISSION_USED_TYPE, value, valueResults)) {
1217         return Constant::FAILURE;
1218     }
1219 
1220     for (const auto& valueResult : valueResults) {
1221         AddDataValueToResults(valueResult, results);
1222     }
1223 
1224     ACCESSTOKEN_LOG_INFO(LABEL, "get %{public}zu permission used type records", results.size());
1225 
1226     return Constant::SUCCESS;
1227 }
1228 
GetDeviceId(AccessTokenID tokenId)1229 std::string PermissionRecordManager::GetDeviceId(AccessTokenID tokenId)
1230 {
1231     HapTokenInfo tokenInfo;
1232     if (AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo) != Constant::SUCCESS) {
1233         return "";
1234     }
1235     if (tokenInfo.deviceID == DEFAULT_DEVICEID) { // local
1236         return ConstantCommon::GetLocalDeviceId();
1237     }
1238     return tokenInfo.deviceID;
1239 }
1240 
GetAppStatus(AccessTokenID tokenId)1241 int32_t PermissionRecordManager::GetAppStatus(AccessTokenID tokenId)
1242 {
1243     int32_t status = PERM_ACTIVE_IN_BACKGROUND;
1244     std::vector<AppStateData> foreGroundAppList;
1245     AppManagerAccessClient::GetInstance().GetForegroundApplications(foreGroundAppList);
1246     if (std::any_of(foreGroundAppList.begin(), foreGroundAppList.end(),
1247         [=](const auto& foreGroundApp) { return foreGroundApp.accessTokenId == tokenId; })) {
1248         status = PERM_ACTIVE_IN_FOREGROUND;
1249     }
1250     return status;
1251 }
1252 
RegisterAppStatusListener()1253 bool PermissionRecordManager::RegisterAppStatusListener()
1254 {
1255     // app manager death callback register
1256     {
1257         std::lock_guard<std::mutex> lock(appManagerDeathMutex_);
1258         if (appManagerDeathCallback_ == nullptr) {
1259             appManagerDeathCallback_ = std::make_shared<PrivacyAppManagerDeathCallback>();
1260             if (appManagerDeathCallback_ == nullptr) {
1261                 ACCESSTOKEN_LOG_ERROR(LABEL, "register appManagerDeathCallback failed.");
1262                 return false;
1263             }
1264             AppManagerAccessClient::GetInstance().RegisterDeathCallbak(appManagerDeathCallback_);
1265         }
1266     }
1267     // app state change callback register
1268     {
1269         std::lock_guard<std::mutex> lock(appStateMutex_);
1270         if (appStateCallback_ == nullptr) {
1271             appStateCallback_ = new (std::nothrow) PrivacyAppStateObserver();
1272             if (appStateCallback_ == nullptr) {
1273                 ACCESSTOKEN_LOG_ERROR(LABEL, "register appStateCallback failed.");
1274                 return false;
1275             }
1276             AppManagerAccessClient::GetInstance().RegisterApplicationStateObserver(appStateCallback_);
1277         }
1278     }
1279     return true;
1280 }
1281 
1282 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
HasUsingCamera()1283 bool PermissionRecordManager::HasUsingCamera()
1284 {
1285     std::lock_guard<std::mutex> lock(startRecordListMutex_);
1286     bool hasCamera = std::any_of(startRecordList_.begin(), startRecordList_.end(),
1287         [](const auto& record) { return record.opCode == Constant::OP_CAMERA; });
1288     return hasCamera;
1289 }
1290 
UpdateCameraFloatWindowStatus(AccessTokenID tokenId,bool isShowing)1291 void UpdateCameraFloatWindowStatus(AccessTokenID tokenId, bool isShowing)
1292 {
1293     PermissionRecordManager::GetInstance().NotifyCameraWindowChange(false, tokenId, isShowing);
1294 }
1295 
UpdatePipWindowStatus(AccessTokenID tokenId,bool isShowing)1296 void UpdatePipWindowStatus(AccessTokenID tokenId, bool isShowing)
1297 {
1298     PermissionRecordManager::GetInstance().NotifyCameraWindowChange(true, tokenId, isShowing);
1299 }
1300 
1301 /* Handle window manager die */
HandleWindowDied()1302 void HandleWindowDied()
1303 {
1304     PermissionRecordManager::GetInstance().OnWindowMgrRemoteDied();
1305 }
1306 #endif
1307 
RegisterWindowCallback()1308 bool PermissionRecordManager::RegisterWindowCallback()
1309 {
1310 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
1311     std::lock_guard<std::mutex> lock(windowLoaderMutex_);
1312     ACCESSTOKEN_LOG_INFO(LABEL, "Begin to RegisterWindowCallback.");
1313     if (windowLoader_ != nullptr) {
1314         ACCESSTOKEN_LOG_INFO(LABEL, "WindowCallback has already been registered.");
1315         return true;
1316     }
1317     if (!HasUsingCamera()) {
1318         ACCESSTOKEN_LOG_INFO(LABEL, "Camera is not using.");
1319         return true;
1320     }
1321     windowLoader_ = new (std::nothrow) LibraryLoader(WINDOW_MANAGER_PATH);
1322     if (windowLoader_ == nullptr) {
1323         ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to new %{public}s.", WINDOW_MANAGER_PATH.c_str());
1324         return false;
1325     }
1326     WindowManagerLoaderInterface* winManagerLoader = windowLoader_->GetObject<WindowManagerLoaderInterface>();
1327     if (winManagerLoader == nullptr) {
1328         ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to dlopen %{public}s.", WINDOW_MANAGER_PATH.c_str());
1329         delete windowLoader_;
1330         windowLoader_ = nullptr;
1331         return false;
1332     }
1333     WindowChangeCallback floatCallback = UpdateCameraFloatWindowStatus;
1334     ErrCode err = winManagerLoader->RegisterFloatWindowListener(floatCallback);
1335     if (err != ERR_OK) {
1336         ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to register float window listener, err:%{public}d", err);
1337         delete windowLoader_;
1338         windowLoader_ = nullptr;
1339         return false;
1340     }
1341     WindowChangeCallback pipCallback = UpdatePipWindowStatus;
1342     err = winManagerLoader->RegisterPipWindowListener(pipCallback);
1343     if (err != ERR_OK) {
1344         ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to register pip window listener, err:%{public}d", err);
1345         winManagerLoader->UnregisterFloatWindowListener(floatCallback);
1346         delete windowLoader_;
1347         windowLoader_ = nullptr;
1348         return false;
1349     }
1350     winManagerLoader->AddDeathCallback(HandleWindowDied);
1351 #endif
1352     return true;
1353 }
1354 
UnRegisterWindowCallback()1355 bool PermissionRecordManager::UnRegisterWindowCallback()
1356 {
1357     bool isSuccess = true;
1358 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
1359     if (!isAutoClose) {
1360         return true;
1361     }
1362     ACCESSTOKEN_LOG_INFO(LABEL, "Begin to UnRegisterWindowCallback.");
1363     std::lock_guard<std::mutex> lock(windowLoaderMutex_);
1364     if (windowLoader_ == nullptr) {
1365         ACCESSTOKEN_LOG_INFO(LABEL, "WindowCallback has already been unregistered.");
1366         return true;
1367     }
1368     if (HasUsingCamera()) {
1369         ACCESSTOKEN_LOG_INFO(LABEL, "Camera is using.");
1370         return true;
1371     }
1372     WindowManagerLoaderInterface* winManagerLoader = windowLoader_->GetObject<WindowManagerLoaderInterface>();
1373     if (winManagerLoader == nullptr) {
1374         ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to dlopen %{public}s.", WINDOW_MANAGER_PATH.c_str());
1375         delete windowLoader_;
1376         windowLoader_ = nullptr;
1377         return false;
1378     }
1379     WindowChangeCallback floatCallback = UpdateCameraFloatWindowStatus;
1380     ErrCode err = winManagerLoader->UnregisterFloatWindowListener(floatCallback);
1381     if (err != ERR_OK) {
1382         ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to unregister float window, err:%{public}d", err);
1383         isSuccess = false;
1384     }
1385     WindowChangeCallback pipCallback = UpdatePipWindowStatus;
1386     err = winManagerLoader->UnregisterPipWindowListener(pipCallback);
1387     if (err != ERR_OK) {
1388         ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to unregister pip window, err:%{public}d", err);
1389         isSuccess = false;
1390     }
1391     delete windowLoader_;
1392     windowLoader_ = nullptr;
1393 #endif
1394     return isSuccess;
1395 }
1396 
Register()1397 bool PermissionRecordManager::Register()
1398 {
1399     // microphone mute
1400     {
1401         std::lock_guard<std::mutex> lock(micCallbackMutex_);
1402         if (micMuteCallback_ == nullptr) {
1403             micMuteCallback_ = new (std::nothrow) AudioRoutingManagerListenerStub();
1404             if (micMuteCallback_ == nullptr) {
1405                 ACCESSTOKEN_LOG_ERROR(LABEL, "register micMuteCallback failed.");
1406                 return false;
1407             }
1408             AudioManagerPrivacyClient::GetInstance().SetMicStateChangeCallback(micMuteCallback_);
1409             bool isMicMute = AudioManagerPrivacyClient::GetInstance().IsMicrophoneMute();
1410             ModifyMuteStatus(MICROPHONE_PERMISSION_NAME, MIXED, isMicMute);
1411             // get EDM
1412             bool isEdmMute = false;
1413             if (!GetMuteParameter(EDM_MIC_MUTE_KEY, isEdmMute)) {
1414                 ACCESSTOKEN_LOG_ERROR(LABEL, "Get param failed");
1415                 return false;
1416             }
1417             ModifyMuteStatus(MICROPHONE_PERMISSION_NAME, EDM, isEdmMute);
1418         }
1419     }
1420     // camera mute
1421     {
1422         std::lock_guard<std::mutex> lock(cameraCallbackMutex_);
1423         if (camMuteCallback_ == nullptr) {
1424             camMuteCallback_ = new (std::nothrow) CameraServiceCallbackStub();
1425             if (camMuteCallback_ == nullptr) {
1426                 ACCESSTOKEN_LOG_ERROR(LABEL, "register camMuteCallback failed.");
1427                 return false;
1428             }
1429             CameraManagerPrivacyClient::GetInstance().SetMuteCallback(camMuteCallback_);
1430             bool isCameraMute = CameraManagerPrivacyClient::GetInstance().IsCameraMuted();
1431             ModifyMuteStatus(CAMERA_PERMISSION_NAME, MIXED, isCameraMute);
1432         }
1433     }
1434     // app state change and lockscreen state change callback register
1435     return RegisterAppStatusListener();
1436 }
1437 
Unregister()1438 void PermissionRecordManager::Unregister()
1439 {
1440     // app state change callback unregister
1441     std::lock_guard<std::mutex> lock(appStateMutex_);
1442     if (appStateCallback_ != nullptr) {
1443         AppManagerAccessClient::GetInstance().UnregisterApplicationStateObserver(appStateCallback_);
1444         appStateCallback_= nullptr;
1445     }
1446 }
1447 
GetMuteParameter(const char * key,bool & isMute)1448 bool PermissionRecordManager::GetMuteParameter(const char* key, bool& isMute)
1449 {
1450     char value[VALUE_MAX_LEN] = {0};
1451     int32_t ret = GetParameter(key, "", value, VALUE_MAX_LEN - 1);
1452     if (ret < 0) {
1453         ACCESSTOKEN_LOG_ERROR(LABEL, "Return default value, ret=%{public}d", ret);
1454         return false;
1455     }
1456     isMute = false;
1457     if (strncmp(value, "true", VALUE_MAX_LEN) == 0) {
1458         ACCESSTOKEN_LOG_INFO(LABEL, "EDM not allow.");
1459         isMute = true;
1460     }
1461     return true;
1462 }
1463 
OnAppMgrRemoteDiedHandle()1464 void PermissionRecordManager::OnAppMgrRemoteDiedHandle()
1465 {
1466     std::lock_guard<std::mutex> lock(appStateMutex_);
1467     appStateCallback_ = nullptr;
1468 }
1469 
OnAudioMgrRemoteDiedHandle()1470 void PermissionRecordManager::OnAudioMgrRemoteDiedHandle()
1471 {
1472     {
1473         std::lock_guard<std::mutex> lock(micCallbackMutex_);
1474         micMuteCallback_ = nullptr;
1475     }
1476 }
1477 
OnCameraMgrRemoteDiedHandle()1478 void PermissionRecordManager::OnCameraMgrRemoteDiedHandle()
1479 {
1480     ACCESSTOKEN_LOG_INFO(LABEL, "Handle camera fwk died.");
1481 
1482     RemoveRecordFromStartListByOp(Constant::OP_CAMERA);
1483 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
1484     ClearWindowShowing();
1485     {
1486         std::lock_guard<std::mutex> lock(windowLoaderMutex_);
1487         if (windowLoader_ != nullptr) {
1488             delete windowLoader_;
1489             windowLoader_ = nullptr;
1490         }
1491     }
1492 #endif
1493 }
1494 
IsCameraWindowShow(AccessTokenID tokenId)1495 bool PermissionRecordManager::IsCameraWindowShow(AccessTokenID tokenId)
1496 {
1497     bool isShow = true;
1498 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
1499     std::lock_guard<std::mutex> lock(windowStausMutex_);
1500     isShow = (floatWindowTokenId_ == tokenId) && camFloatWindowShowing_;
1501     isShow |= ((pipWindowTokenId_ == tokenId) && pipWindowShowing_);
1502 #endif
1503     return isShow;
1504 }
1505 
1506 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
1507 /*
1508  * when camera float window is not show, notice camera service to use StopUsingPermission
1509  */
NotifyCameraWindowChange(bool isPip,AccessTokenID tokenId,bool isShowing)1510 void PermissionRecordManager::NotifyCameraWindowChange(bool isPip, AccessTokenID tokenId, bool isShowing)
1511 {
1512     ACCESSTOKEN_LOG_INFO(LABEL, "Update window, isPip(%{public}d), token(%{public}d), status(%{public}d)",
1513         isPip, tokenId, isShowing);
1514     {
1515         std::lock_guard<std::mutex> lock(windowStausMutex_);
1516         if (isPip) {
1517             pipWindowShowing_ = isShowing;
1518             pipWindowTokenId_ = tokenId;
1519         } else {
1520             camFloatWindowShowing_ = isShowing;
1521             floatWindowTokenId_ = tokenId;
1522         }
1523     }
1524     if (isShowing) {
1525         ACCESSTOKEN_LOG_INFO(LABEL, "camera float window is showing!");
1526     } else {
1527         if ((GetAppStatus(tokenId) == ActiveChangeType::PERM_ACTIVE_IN_BACKGROUND) &&
1528             !IsCameraWindowShow(tokenId)) {
1529             ACCESSTOKEN_LOG_INFO(LABEL, "Token(%{public}d) is background, pip and float window is not show.", tokenId);
1530             ExecuteCameraCallbackAsync(tokenId);
1531         }
1532     }
1533 }
1534 
ClearWindowShowing()1535 void PermissionRecordManager::ClearWindowShowing()
1536 {
1537     ACCESSTOKEN_LOG_INFO(LABEL, "Clear window show status.");
1538     {
1539         std::lock_guard<std::mutex> lock(windowStausMutex_);
1540         camFloatWindowShowing_ = false;
1541         floatWindowTokenId_ = 0;
1542 
1543         pipWindowShowing_ = false;
1544         pipWindowTokenId_ = 0;
1545     }
1546 }
1547 
1548 /* Handle window manager die */
OnWindowMgrRemoteDied()1549 void PermissionRecordManager::OnWindowMgrRemoteDied()
1550 {
1551     ACCESSTOKEN_LOG_INFO(LABEL, "Handle window manager died.");
1552     ClearWindowShowing();
1553 }
1554 #endif
1555 
SetDefaultConfigValue()1556 void PermissionRecordManager::SetDefaultConfigValue()
1557 {
1558     ACCESSTOKEN_LOG_INFO(LABEL, "no config file or config file is not valid, use default values");
1559 
1560     recordSizeMaximum_ = DEFAULT_PERMISSION_USED_RECORD_SIZE_MAXIMUM;
1561     recordAgingTime_ = DEFAULT_PERMISSION_USED_RECORD_AGING_TIME;
1562     globalDialogBundleName_ = DEFAULT_PERMISSION_MANAGER_BUNDLE_NAME;
1563     globalDialogAbilityName_ = DEFAULT_PERMISSION_MANAGER_DIALOG_ABILITY;
1564 }
1565 
GetConfigValue()1566 void PermissionRecordManager::GetConfigValue()
1567 {
1568     AccessTokenConfigPolicy policy;
1569     AccessTokenConfigValue value;
1570     if (policy.GetConfigValue(ServiceType::PRIVACY_SERVICE, value)) {
1571         // set value from config
1572         recordSizeMaximum_ = value.pConfig.sizeMaxImum;
1573         recordAgingTime_ = value.pConfig.agingTime;
1574         globalDialogBundleName_ = value.pConfig.globalDialogBundleName;
1575         globalDialogAbilityName_ = value.pConfig.globalDialogAbilityName;
1576     } else {
1577         SetDefaultConfigValue();
1578     }
1579 
1580     ACCESSTOKEN_LOG_INFO(LABEL, "recordSizeMaximum_ is %{public}d, recordAgingTime_ is %{public}d,"
1581         " globalDialogBundleName_ is %{public}s, globalDialogAbilityName_ is %{public}s.",
1582         recordSizeMaximum_, recordAgingTime_, globalDialogBundleName_.c_str(), globalDialogAbilityName_.c_str());
1583 }
1584 
Init()1585 void PermissionRecordManager::Init()
1586 {
1587     if (hasInited_) {
1588         return;
1589     }
1590     ACCESSTOKEN_LOG_INFO(LABEL, "init");
1591     deleteTaskWorker_.Start(1);
1592     hasInited_ = true;
1593 
1594     GetConfigValue();
1595 }
1596 } // namespace AccessToken
1597 } // namespace Security
1598 } // namespace OHOS