1 /*
2 * Copyright (c) 2022 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 "accesstoken_kit.h"
24 #include "accesstoken_log.h"
25 #include "active_status_callback_manager.h"
26 #include "app_manager_access_client.h"
27 #include "audio_manager_privacy_client.h"
28 #include "camera_manager_privacy_client.h"
29 #ifdef CUSTOMIZATION_CONFIG_POLICY_ENABLE
30 #include "config_policy_utils.h"
31 #include "json_parser.h"
32 #endif
33 #include "constant.h"
34 #include "constant_common.h"
35 #include "data_translator.h"
36 #include "i_state_change_callback.h"
37 #include "iservice_registry.h"
38 #ifdef COMMON_EVENT_SERVICE_ENABLE
39 #include "lockscreen_status_observer.h"
40 #endif //COMMON_EVENT_SERVICE_ENABLE
41 #include "parcel_utils.h"
42 #include "permission_record_repository.h"
43 #include "permission_used_record_cache.h"
44 #include "privacy_error.h"
45 #include "privacy_field_const.h"
46 #include "refbase.h"
47 #ifdef THEME_SCREENLOCK_MGR_ENABLE
48 #include "screenlock_manager.h"
49 #endif
50 #include "state_change_callback_proxy.h"
51 #include "system_ability_definition.h"
52 #include "time_util.h"
53 #include "want.h"
54 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
55 #include "window_manager_privacy_client.h"
56 #endif
57
58 namespace OHOS {
59 namespace Security {
60 namespace AccessToken {
61 namespace {
62 static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {
63 LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermissionRecordManager"
64 };
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 static const std::string PERMISSION_MANAGER_BUNDLE_NAME = "com.ohos.permissionmanager";
70 static const std::string PERMISSION_MANAGER_DIALOG_ABILITY = "com.ohos.permissionmanager.GlobalExtAbility";
71 static const std::string RESOURCE_KEY = "ohos.sensitive.resource";
72 static const int32_t DEFAULT_PERMISSION_USED_RECORD_SIZE_MAXIMUM = 500000;
73 static const int32_t DEFAULT_PERMISSION_USED_RECORD_AGING_TIME = 7;
74 #ifdef CUSTOMIZATION_CONFIG_POLICY_ENABLE
75 static const std::string ACCESSTOKEN_CONFIG_FILE = "/etc/access_token/accesstoken_config.json";
76 static const std::string RECORD_SIZE_MAXIMUM_KEY = "permission_used_record_size_maximum";
77 static const std::string RECORD_AGING_TIME_KEY = "permission_used_record_aging_time";
78 #endif
79 }
GetInstance()80 PermissionRecordManager& PermissionRecordManager::GetInstance()
81 {
82 static PermissionRecordManager instance;
83 return instance;
84 }
85
PermissionRecordManager()86 PermissionRecordManager::PermissionRecordManager() : deleteTaskWorker_("DeleteRecord"), hasInited_(false) {}
87
~PermissionRecordManager()88 PermissionRecordManager::~PermissionRecordManager()
89 {
90 if (!hasInited_) {
91 return;
92 }
93 deleteTaskWorker_.Stop();
94 hasInited_ = false;
95 Unregister();
96 }
97
OnForegroundApplicationChanged(const AppStateData & appStateData)98 void PrivacyAppStateObserver::OnForegroundApplicationChanged(const AppStateData &appStateData)
99 {
100 ACCESSTOKEN_LOG_DEBUG(LABEL, "OnChange(accessTokenId=%{public}d, state=%{public}d)",
101 appStateData.accessTokenId, appStateData.state);
102
103 uint32_t tokenId = appStateData.accessTokenId;
104
105 ActiveChangeType status = PERM_INACTIVE;
106 if (appStateData.state == static_cast<int32_t>(ApplicationState::APP_STATE_FOREGROUND)) {
107 status = PERM_ACTIVE_IN_FOREGROUND;
108 } else if (appStateData.state == static_cast<int32_t>(ApplicationState::APP_STATE_BACKGROUND)) {
109 status = PERM_ACTIVE_IN_BACKGROUND;
110 }
111 PermissionRecordManager::GetInstance().NotifyAppStateChange(tokenId, status);
112 }
113
NotifyAppManagerDeath()114 void PrivacyAppManagerDeathCallback::NotifyAppManagerDeath()
115 {
116 ACCESSTOKEN_LOG_INFO(LABEL, "PermissionRecordManager AppManagerDeath called");
117
118 PermissionRecordManager::GetInstance().OnAppMgrRemoteDiedHandle();
119 }
120
AddRecord(const PermissionRecord & record)121 void PermissionRecordManager::AddRecord(const PermissionRecord& record)
122 {
123 Utils::UniqueWriteGuard<Utils::RWLock> lk(this->rwLock_);
124 ACCESSTOKEN_LOG_INFO(LABEL,
125 "add record: tokenId %{public}d, opCode %{public}d, status: %{public}d, \
126 lockScreenStatus: %{public}d, timestamp: %{public}" PRId64,
127 record.tokenId, record.opCode, record.status, record.lockScreenStatus, record.timestamp);
128 PermissionUsedRecordCache::GetInstance().AddRecordToBuffer(record);
129 }
130
GetPermissionRecord(AccessTokenID tokenId,const std::string & permissionName,int32_t successCount,int32_t failCount,PermissionRecord & record)131 int32_t PermissionRecordManager::GetPermissionRecord(AccessTokenID tokenId, const std::string& permissionName,
132 int32_t successCount, int32_t failCount, PermissionRecord& record)
133 {
134 HapTokenInfo tokenInfo;
135 if (AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo) != Constant::SUCCESS) {
136 ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenId(%{public}d)", tokenId);
137 return PrivacyError::ERR_TOKENID_NOT_EXIST;
138 }
139 int32_t opCode;
140 if (!Constant::TransferPermissionToOpcode(permissionName, opCode)) {
141 ACCESSTOKEN_LOG_ERROR(LABEL, "invalid (%{public}s)", permissionName.c_str());
142 return PrivacyError::ERR_PERMISSION_NOT_EXIST;
143 }
144
145 record.status = GetAppStatus(tokenId);
146 #ifdef THEME_SCREENLOCK_MGR_ENABLE
147 int32_t lockScreenStatus = ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked() ?
148 LockScreenStatusChangeType::PERM_ACTIVE_IN_LOCKED : LockScreenStatusChangeType::PERM_ACTIVE_IN_UNLOCKED;
149 record.lockScreenStatus = lockScreenStatus;
150 #endif
151 record.tokenId = tokenId;
152 record.accessCount = successCount;
153 record.rejectCount = failCount;
154 record.opCode = opCode;
155 record.timestamp = TimeUtil::GetCurrentTimestamp();
156 record.accessDuration = 0;
157 ACCESSTOKEN_LOG_DEBUG(LABEL, "record status: %{public}d", record.status);
158 return Constant::SUCCESS;
159 }
160
AddPermissionUsedRecord(AccessTokenID tokenId,const std::string & permissionName,int32_t successCount,int32_t failCount)161 int32_t PermissionRecordManager::AddPermissionUsedRecord(AccessTokenID tokenId, const std::string& permissionName,
162 int32_t successCount, int32_t failCount)
163 {
164 ExecuteDeletePermissionRecordTask();
165
166 if ((successCount == 0) && (failCount == 0)) {
167 return PrivacyError::ERR_PARAM_INVALID;
168 }
169
170 PermissionRecord record;
171 int32_t result = GetPermissionRecord(tokenId, permissionName, successCount, failCount, record);
172 if (result != Constant::SUCCESS) {
173 return result;
174 }
175
176 AddRecord(record);
177 return Constant::SUCCESS;
178 }
179
RemovePermissionUsedRecords(AccessTokenID tokenId,const std::string & deviceID)180 void PermissionRecordManager::RemovePermissionUsedRecords(AccessTokenID tokenId, const std::string& deviceID)
181 {
182 // only support remove by tokenId(local)
183 std::string device = GetDeviceId(tokenId);
184 if (device.empty()) {
185 ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenId = %{public}d", tokenId);
186 return;
187 }
188
189 if (!deviceID.empty() && device != deviceID) {
190 ACCESSTOKEN_LOG_ERROR(LABEL, "deviceID mismatch");
191 return;
192 }
193
194 Utils::UniqueWriteGuard<Utils::RWLock> lk(this->rwLock_);
195 PermissionUsedRecordCache::GetInstance().RemoveRecords(tokenId); // remove from cache and database
196 }
197
GetPermissionUsedRecords(const PermissionUsedRequest & request,PermissionUsedResult & result)198 int32_t PermissionRecordManager::GetPermissionUsedRecords(
199 const PermissionUsedRequest& request, PermissionUsedResult& result)
200 {
201 ExecuteDeletePermissionRecordTask();
202
203 if (!request.isRemote && !GetRecordsFromLocalDB(request, result)) {
204 ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to GetRecordsFromLocalDB");
205 return PrivacyError::ERR_PARAM_INVALID;
206 }
207 return Constant::SUCCESS;
208 }
209
GetPermissionUsedRecordsAsync(const PermissionUsedRequest & request,const sptr<OnPermissionUsedRecordCallback> & callback)210 int32_t PermissionRecordManager::GetPermissionUsedRecordsAsync(
211 const PermissionUsedRequest& request, const sptr<OnPermissionUsedRecordCallback>& callback)
212 {
213 auto task = [request, callback]() {
214 ACCESSTOKEN_LOG_INFO(LABEL, "GetPermissionUsedRecordsAsync task called");
215 PermissionUsedResult result;
216 int32_t retCode = PermissionRecordManager::GetInstance().GetPermissionUsedRecords(request, result);
217 callback->OnQueried(retCode, result);
218 };
219 std::thread recordThread(task);
220 recordThread.detach();
221 return Constant::SUCCESS;
222 }
223
GetLocalRecordTokenIdList(std::set<AccessTokenID> & tokenIdList)224 void PermissionRecordManager::GetLocalRecordTokenIdList(std::set<AccessTokenID>& tokenIdList)
225 {
226 std::vector<GenericValues> results;
227 {
228 Utils::UniqueReadGuard<Utils::RWLock> lk(this->rwLock_);
229 // find tokenId from cache
230 PermissionUsedRecordCache::GetInstance().FindTokenIdList(tokenIdList);
231 // find tokenId from database
232 PermissionRecordRepository::GetInstance().GetAllRecordValuesByKey(PrivacyFiledConst::FIELD_TOKEN_ID, results);
233 }
234 for (const auto& res : results) {
235 tokenIdList.emplace(res.GetInt(PrivacyFiledConst::FIELD_TOKEN_ID));
236 }
237 }
238
AddDebugLog(const AccessTokenID tokenId,const BundleUsedRecord & bundleRecord,const int32_t currentCount,int32_t & totalSuccCount,int32_t & totalFailCount)239 static void AddDebugLog(const AccessTokenID tokenId, const BundleUsedRecord& bundleRecord, const int32_t currentCount,
240 int32_t& totalSuccCount, int32_t& totalFailCount)
241 {
242 int32_t tokenTotalSuccCount = 0;
243 int32_t tokenTotalFailCount = 0;
244 for (const auto& PermissionRecord : bundleRecord.permissionRecords) {
245 tokenTotalSuccCount += PermissionRecord.accessCount;
246 tokenTotalFailCount += PermissionRecord.rejectCount;
247 }
248 ACCESSTOKEN_LOG_INFO(LABEL, "tokenId %{public}d[%{public}s] get %{public}d records, success %{public}d,"
249 " failure %{public}d", tokenId, bundleRecord.bundleName.c_str(), currentCount, tokenTotalSuccCount,
250 tokenTotalFailCount);
251 totalSuccCount += tokenTotalSuccCount;
252 totalFailCount += tokenTotalFailCount;
253 }
254
GetRecordsFromLocalDB(const PermissionUsedRequest & request,PermissionUsedResult & result)255 bool PermissionRecordManager::GetRecordsFromLocalDB(const PermissionUsedRequest& request, PermissionUsedResult& result)
256 {
257 GenericValues andConditionValues;
258 if (DataTranslator::TranslationIntoGenericValues(request, andConditionValues)
259 != Constant::SUCCESS) {
260 ACCESSTOKEN_LOG_ERROR(LABEL, "query time or flag is invalid");
261 return false;
262 }
263
264 std::set<AccessTokenID> tokenIdList;
265 if (request.tokenId == 0) {
266 GetLocalRecordTokenIdList(tokenIdList);
267 } else {
268 tokenIdList.emplace(request.tokenId);
269 }
270
271 // sumarry don't limit querry data num, detail do
272 int32_t dataLimitNum = request.flag == FLAG_PERMISSION_USAGE_DETAIL ? MAX_ACCESS_RECORD_SIZE : recordSizeMaximum_;
273 int32_t totalSuccCount = 0;
274 int32_t totalFailCount = 0;
275
276 Utils::UniqueReadGuard<Utils::RWLock> lk(this->rwLock_);
277 for (const auto& tokenId : tokenIdList) {
278 andConditionValues.Put(PrivacyFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenId));
279 std::vector<GenericValues> findRecordsValues;
280 PermissionUsedRecordCache::GetInstance().GetRecords(request.permissionList,
281 andConditionValues, findRecordsValues, dataLimitNum); // find records from cache and database
282 andConditionValues.Remove(PrivacyFiledConst::FIELD_TOKEN_ID);
283 uint32_t currentCount = findRecordsValues.size();
284 dataLimitNum -= currentCount;
285 BundleUsedRecord bundleRecord;
286 if (!CreateBundleUsedRecord(tokenId, bundleRecord)) {
287 continue;
288 }
289
290 if (currentCount > 0) {
291 GetRecords(request.flag, findRecordsValues, bundleRecord, result);
292 // add debug log when get exsit record
293 AddDebugLog(tokenId, bundleRecord, currentCount, totalSuccCount, totalFailCount);
294 }
295
296 if (!bundleRecord.permissionRecords.empty()) {
297 result.bundleRecords.emplace_back(bundleRecord);
298 }
299 }
300
301 if (request.flag == FLAG_PERMISSION_USAGE_SUMMARY) {
302 ACCESSTOKEN_LOG_INFO(LABEL, "total success count is %{public}d, total failure count is %{public}d",
303 totalSuccCount, totalFailCount);
304 }
305
306 return true;
307 }
308
CreateBundleUsedRecord(const AccessTokenID tokenId,BundleUsedRecord & bundleRecord)309 bool PermissionRecordManager::CreateBundleUsedRecord(const AccessTokenID tokenId, BundleUsedRecord& bundleRecord)
310 {
311 HapTokenInfo tokenInfo;
312 if (AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo) != Constant::SUCCESS) {
313 ACCESSTOKEN_LOG_ERROR(LABEL, "GetHapTokenInfo failed");
314 return false;
315 }
316 bundleRecord.tokenId = tokenId;
317 bundleRecord.isRemote = false;
318 bundleRecord.deviceId = GetDeviceId(tokenId);
319 bundleRecord.bundleName = tokenInfo.bundleName;
320 return true;
321 }
322
GetRecords(int32_t flag,std::vector<GenericValues> recordValues,BundleUsedRecord & bundleRecord,PermissionUsedResult & result)323 void PermissionRecordManager::GetRecords(
324 int32_t flag, std::vector<GenericValues> recordValues, BundleUsedRecord& bundleRecord, PermissionUsedResult& result)
325 {
326 std::vector<PermissionUsedRecord> permissionRecords;
327 for (auto it = recordValues.rbegin(); it != recordValues.rend(); ++it) {
328 GenericValues record = *it;
329 PermissionUsedRecord tmpPermissionRecord;
330 int64_t timestamp = record.GetInt64(PrivacyFiledConst::FIELD_TIMESTAMP);
331 result.beginTimeMillis = ((result.beginTimeMillis == 0) || (timestamp < result.beginTimeMillis)) ?
332 timestamp : result.beginTimeMillis;
333 result.endTimeMillis = (timestamp > result.endTimeMillis) ? timestamp : result.endTimeMillis;
334
335 record.Put(PrivacyFiledConst::FIELD_FLAG, flag);
336 if (DataTranslator::TranslationGenericValuesIntoPermissionUsedRecord(record, tmpPermissionRecord)
337 != Constant::SUCCESS) {
338 ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to transform opcode(%{public}d) into permission",
339 record.GetInt(PrivacyFiledConst::FIELD_OP_CODE));
340 continue;
341 }
342
343 auto iter = std::find_if(permissionRecords.begin(), permissionRecords.end(),
344 [tmpPermissionRecord](const PermissionUsedRecord& rec) {
345 return tmpPermissionRecord.permissionName == rec.permissionName;
346 });
347 if (iter != permissionRecords.end()) {
348 UpdateRecords(flag, tmpPermissionRecord, *iter);
349 } else {
350 permissionRecords.emplace_back(tmpPermissionRecord);
351 }
352 }
353 bundleRecord.permissionRecords = permissionRecords;
354 }
355
UpdateRecords(int32_t flag,const PermissionUsedRecord & inBundleRecord,PermissionUsedRecord & outBundleRecord)356 void PermissionRecordManager::UpdateRecords(
357 int32_t flag, const PermissionUsedRecord& inBundleRecord, PermissionUsedRecord& outBundleRecord)
358 {
359 outBundleRecord.accessCount += inBundleRecord.accessCount;
360 outBundleRecord.rejectCount += inBundleRecord.rejectCount;
361 if (inBundleRecord.lastAccessTime > outBundleRecord.lastAccessTime) {
362 outBundleRecord.lastAccessTime = inBundleRecord.lastAccessTime;
363 outBundleRecord.lastAccessDuration = inBundleRecord.lastAccessDuration;
364 }
365 outBundleRecord.lastRejectTime = (inBundleRecord.lastRejectTime > outBundleRecord.lastRejectTime) ?
366 inBundleRecord.lastRejectTime : outBundleRecord.lastRejectTime;
367
368 if (flag != FLAG_PERMISSION_USAGE_DETAIL) {
369 return;
370 }
371 if (inBundleRecord.lastAccessTime > 0) {
372 outBundleRecord.accessRecords.emplace_back(inBundleRecord.accessRecords[0]);
373 }
374 if (inBundleRecord.lastRejectTime > 0) {
375 outBundleRecord.rejectRecords.emplace_back(inBundleRecord.rejectRecords[0]);
376 }
377 }
378
ExecuteDeletePermissionRecordTask()379 void PermissionRecordManager::ExecuteDeletePermissionRecordTask()
380 {
381 if (deleteTaskWorker_.GetCurTaskNum() > 1) {
382 ACCESSTOKEN_LOG_INFO(LABEL, "Already has delete task!");
383 return;
384 }
385
386 auto deleteRecordsTask = [this]() {
387 ACCESSTOKEN_LOG_DEBUG(LABEL, "DeletePermissionRecord task called");
388 DeletePermissionRecord(recordAgingTime_);
389 };
390 deleteTaskWorker_.AddTask(deleteRecordsTask);
391 }
392
DeletePermissionRecord(int32_t days)393 int32_t PermissionRecordManager::DeletePermissionRecord(int32_t days)
394 {
395 int64_t interval = days * Constant::ONE_DAY_MILLISECONDS;
396 Utils::UniqueWriteGuard<Utils::RWLock> lk(this->rwLock_);
397 GenericValues countValue;
398 PermissionRecordRepository::GetInstance().CountRecordValues(countValue);
399 int64_t total = countValue.GetInt64(FIELD_COUNT_NUMBER);
400 if (total > recordSizeMaximum_) {
401 uint32_t excessiveSize = total - recordSizeMaximum_;
402 if (!PermissionRecordRepository::GetInstance().DeleteExcessiveSizeRecordValues(excessiveSize)) {
403 return Constant::FAILURE;
404 }
405 }
406 GenericValues andConditionValues;
407 int64_t deleteTimestamp = TimeUtil::GetCurrentTimestamp() - interval;
408 andConditionValues.Put(PrivacyFiledConst::FIELD_TIMESTAMP_END, deleteTimestamp);
409 if (!PermissionRecordRepository::GetInstance().DeleteExpireRecordsValues(andConditionValues)) {
410 return Constant::FAILURE;
411 }
412 return Constant::SUCCESS;
413 }
414
AddRecordToStartList(const PermissionRecord & record)415 bool PermissionRecordManager::AddRecordToStartList(const PermissionRecord& record)
416 {
417 std::lock_guard<std::mutex> lock(startRecordListMutex_);
418 bool hasStarted = std::any_of(startRecordList_.begin(), startRecordList_.end(),
419 [record](const auto& rec) { return (rec.opCode == record.opCode) && (rec.tokenId == record.tokenId); });
420 if (hasStarted) {
421 ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId(%{public}d), opCode(%{public}d) has been started.",
422 record.tokenId, record.opCode);
423 } else {
424 ACCESSTOKEN_LOG_DEBUG(LABEL, "tokenId(%{public}d), opCode(%{public}d) add record.",
425 record.tokenId, record.opCode);
426 startRecordList_.emplace_back(record);
427 }
428 return hasStarted;
429 }
430
FindRecordsToUpdateAndExecuted(uint32_t tokenId,ActiveChangeType status)431 void PermissionRecordManager::FindRecordsToUpdateAndExecuted(
432 uint32_t tokenId, ActiveChangeType status)
433 {
434 std::vector<std::string> permList;
435 std::vector<std::string> camPermList;
436 {
437 std::lock_guard<std::mutex> lock(startRecordListMutex_);
438 for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) {
439 if ((it->tokenId == tokenId) && ((it->status) != status)) {
440 std::string perm;
441 Constant::TransferOpcodeToPermission(it->opCode, perm);
442 if (!GetGlobalSwitchStatus(perm)) {
443 continue;
444 }
445
446 // app use camera background without float window
447 bool isShow = true;
448 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
449 isShow = IsFlowWindowShow(tokenId);
450 #endif
451 if ((perm == CAMERA_PERMISSION_NAME) && (status == PERM_ACTIVE_IN_BACKGROUND) && (!isShow)) {
452 ACCESSTOKEN_LOG_INFO(LABEL, "camera float window is close!");
453 camPermList.emplace_back(perm);
454 continue;
455 }
456 permList.emplace_back(perm);
457 int64_t curStamp = TimeUtil::GetCurrentTimestamp();
458 // update accessDuration and store in database
459 it->accessDuration = curStamp - it->timestamp;
460 int32_t lockScreenStatus = it->lockScreenStatus;
461 if (it->status == PERM_ACTIVE_IN_FOREGROUND && lockScreenStatus == PERM_ACTIVE_IN_LOCKED) {
462 ACCESSTOKEN_LOG_DEBUG(LABEL, "foreground & locked convert into background & unlocked");
463 it->status = PERM_ACTIVE_IN_BACKGROUND;
464 it->lockScreenStatus = PERM_ACTIVE_IN_UNLOCKED;
465 }
466 AddRecord(*it);
467
468 // update status to input, accessDuration to 0 and timestamp to now in cache
469 it->status = status;
470 it->lockScreenStatus = lockScreenStatus;
471 it->accessDuration = 0;
472 it->timestamp = curStamp;
473 ACCESSTOKEN_LOG_DEBUG(LABEL, "tokenId %{public}d get permission %{public}s.", tokenId, perm.c_str());
474 }
475 }
476 }
477
478 if (!camPermList.empty()) {
479 ExecuteCameraCallbackAsync(tokenId);
480 }
481 // each permission sends a status change notice
482 for (const auto& perm : permList) {
483 CallbackExecute(tokenId, perm, status);
484 }
485 }
486
487 /*
488 * when foreground change background or background change foreground,change accessDuration and store in database,
489 * change status and accessDuration and timestamp in cache
490 */
NotifyAppStateChange(AccessTokenID tokenId,ActiveChangeType status)491 void PermissionRecordManager::NotifyAppStateChange(AccessTokenID tokenId, ActiveChangeType status)
492 {
493 ACCESSTOKEN_LOG_INFO(LABEL, "tokenId %{public}d, status %{public}d", tokenId, status);
494 // find permissions from startRecordList_ by tokenId which status diff from currStatus
495 FindRecordsToUpdateAndExecuted(tokenId, status);
496 }
497
GenerateRecordsWhenScreenStatusChanged(LockScreenStatusChangeType lockScreenStatus)498 void PermissionRecordManager::GenerateRecordsWhenScreenStatusChanged(LockScreenStatusChangeType lockScreenStatus)
499 {
500 std::lock_guard<std::mutex> lock(startRecordListMutex_);
501 for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) {
502 std::string perm;
503 Constant::TransferOpcodeToPermission(it->opCode, perm);
504 if (!GetGlobalSwitchStatus(perm)) {
505 continue;
506 }
507 if ((perm == CAMERA_PERMISSION_NAME) &&
508 (lockScreenStatus == LockScreenStatusChangeType::PERM_ACTIVE_IN_LOCKED)) {
509 continue;
510 }
511
512 // update accessDuration and store in databases
513 int64_t curStamp = TimeUtil::GetCurrentTimestamp();
514 it->accessDuration = curStamp - it->timestamp;
515
516 int32_t tempStatus = it->status;
517 if (tempStatus == PERM_ACTIVE_IN_FOREGROUND && it->lockScreenStatus == PERM_ACTIVE_IN_LOCKED) {
518 ACCESSTOKEN_LOG_DEBUG(LABEL, "foreground & locked convert into background & unlocked");
519 it->status = PERM_ACTIVE_IN_BACKGROUND;
520 it->lockScreenStatus = PERM_ACTIVE_IN_UNLOCKED;
521 }
522 AddRecord(*it);
523
524 // update lockScreenStatus to input, accessDuration to 0 and timestamp to now in cache
525 it->status = tempStatus;
526 it->lockScreenStatus = lockScreenStatus;
527 it->accessDuration = 0;
528 it->timestamp = curStamp;
529 ACCESSTOKEN_LOG_DEBUG(LABEL, "get target permission %{public}s.", perm.c_str());
530 }
531 }
532
NotifyLockScreenStatusChange(LockScreenStatusChangeType lockScreenStatus)533 void PermissionRecordManager::NotifyLockScreenStatusChange(LockScreenStatusChangeType lockScreenStatus)
534 {
535 ACCESSTOKEN_LOG_INFO(LABEL, "lockScreenStatus %{public}d", lockScreenStatus);
536 GenerateRecordsWhenScreenStatusChanged(lockScreenStatus);
537 }
538
RemoveRecordFromStartList(const PermissionRecord & record)539 void PermissionRecordManager::RemoveRecordFromStartList(const PermissionRecord& record)
540 {
541 ACCESSTOKEN_LOG_DEBUG(LABEL, "tokenId %{public}d, opCode %{public}d", record.tokenId, record.opCode);
542 std::lock_guard<std::mutex> lock(startRecordListMutex_);
543 for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) {
544 if ((it->opCode == record.opCode) && (it->tokenId == record.tokenId)) {
545 startRecordList_.erase(it);
546 return;
547 }
548 }
549 }
550
UpdateRecord(const PermissionRecord & record)551 void PermissionRecordManager::UpdateRecord(const PermissionRecord& record)
552 {
553 ACCESSTOKEN_LOG_DEBUG(LABEL, "tokenId %{public}d, opCode %{public}d", record.tokenId, record.opCode);
554 std::lock_guard<std::mutex> lock(startRecordListMutex_);
555 for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) {
556 if ((it->opCode == record.opCode) && (it->tokenId == record.tokenId)) {
557 it->status = record.status;
558 return;
559 }
560 }
561 }
562
GetRecordFromStartList(uint32_t tokenId,int32_t opCode,PermissionRecord & record)563 bool PermissionRecordManager::GetRecordFromStartList(uint32_t tokenId, int32_t opCode, PermissionRecord& record)
564 {
565 std::lock_guard<std::mutex> lock(startRecordListMutex_);
566 for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) {
567 if ((it->opCode == opCode) && (it->tokenId == tokenId)) {
568 it->accessCount = 1;
569 record = *it;
570 record.accessDuration = TimeUtil::GetCurrentTimestamp() - record.timestamp;
571 startRecordList_.erase(it);
572 return true;
573 }
574 }
575 return false;
576 }
577
CallbackExecute(AccessTokenID tokenId,const std::string & permissionName,int32_t status)578 void PermissionRecordManager::CallbackExecute(
579 AccessTokenID tokenId, const std::string& permissionName, int32_t status)
580 {
581 ACCESSTOKEN_LOG_INFO(LABEL, "entry ExecuteCallbackAsync, int32_t status is %{public}d", status);
582 ActiveStatusCallbackManager::GetInstance().ExecuteCallbackAsync(
583 tokenId, permissionName, GetDeviceId(tokenId), (ActiveChangeType)status);
584 }
585
GetGlobalSwitchStatus(const std::string & permissionName)586 bool PermissionRecordManager::GetGlobalSwitchStatus(const std::string& permissionName)
587 {
588 bool isOpen = true;
589 // only manage camera and microphone global switch now, other default true
590 if (permissionName == MICROPHONE_PERMISSION_NAME) {
591 isOpen = !isMicMute_;
592 } else if (permissionName == CAMERA_PERMISSION_NAME) {
593 isOpen = !isCameraMute_;
594 }
595
596 ACCESSTOKEN_LOG_INFO(LABEL, "permission is %{public}s, status is %{public}d", permissionName.c_str(), isOpen);
597 return isOpen;
598 }
599
600 /*
601 * StartUsing when close and choose open, update status to foreground or background from inactive
602 * StartUsing when open and choose close, update status to inactive and store in database
603 */
SavePermissionRecords(const std::string & permissionName,PermissionRecord & record,bool switchStatus)604 void PermissionRecordManager::SavePermissionRecords(
605 const std::string& permissionName, PermissionRecord& record, bool switchStatus)
606 {
607 int64_t curStamp = TimeUtil::GetCurrentTimestamp();
608 if (switchStatus) {
609 ACCESSTOKEN_LOG_INFO(LABEL, "global switch is open, update record from inactive");
610 // no need to store in database when status from inactive to foreground or background
611 record.status = GetAppStatus(record.tokenId);
612 record.timestamp = curStamp;
613 } else {
614 ACCESSTOKEN_LOG_INFO(LABEL, "global switch is close, update record to inactive");
615 if (record.status != PERM_INACTIVE) {
616 // update accessDuration and store in database
617 record.accessDuration = curStamp - record.timestamp;
618 AddRecord(record);
619 // update status to input, accessDuration to 0 and timestamp to now in cache
620 record.status = PERM_INACTIVE;
621 record.accessDuration = 0;
622 record.timestamp = curStamp;
623 }
624 }
625 CallbackExecute(record.tokenId, permissionName, record.status);
626 }
627
NotifyMicChange(bool switchStatus)628 void PermissionRecordManager::NotifyMicChange(bool switchStatus)
629 {
630 ACCESSTOKEN_LOG_INFO(LABEL, "===========OnMicStateChange(%{public}d)", switchStatus);
631 {
632 std::lock_guard<std::mutex> lock(micMuteMutex_);
633 isMicMute_ = !switchStatus;
634 }
635 std::lock_guard<std::mutex> lock(startRecordListMutex_);
636 for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) {
637 if ((it->opCode) != Constant::OP_MICROPHONE) {
638 continue;
639 }
640 SavePermissionRecords("ohos.permission.MICROPHONE", *it, switchStatus);
641 }
642 }
643
NotifyCameraChange(bool switchStatus)644 void PermissionRecordManager::NotifyCameraChange(bool switchStatus)
645 {
646 ACCESSTOKEN_LOG_INFO(LABEL, "=========OnCameraStateChange(%{public}d)", switchStatus);
647 {
648 std::lock_guard<std::mutex> lock(camMuteMutex_);
649 isCameraMute_ = !switchStatus;
650 }
651
652 std::lock_guard<std::mutex> lock(startRecordListMutex_);
653 for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) {
654 if ((it->opCode) != Constant::OP_CAMERA) {
655 continue;
656 }
657 SavePermissionRecords("ohos.permission.CAMERA", *it, switchStatus);
658 }
659 }
660
ShowGlobalDialog(const std::string & permissionName)661 bool PermissionRecordManager::ShowGlobalDialog(const std::string& permissionName)
662 {
663 std::string resource;
664 if (permissionName == CAMERA_PERMISSION_NAME) {
665 resource = "camera";
666 } else if (permissionName == MICROPHONE_PERMISSION_NAME) {
667 resource = "microphone";
668 } else {
669 ACCESSTOKEN_LOG_INFO(LABEL, "invalid permissionName(%{public}s).", permissionName.c_str());
670 return true;
671 }
672
673 AAFwk::Want want;
674 want.SetElementName(PERMISSION_MANAGER_BUNDLE_NAME, PERMISSION_MANAGER_DIALOG_ABILITY);
675 want.SetParam(RESOURCE_KEY, resource);
676 ErrCode err = AbilityManagerAccessClient::GetInstance().StartAbility(want, nullptr);
677 if (err != ERR_OK) {
678 ACCESSTOKEN_LOG_ERROR(LABEL, "Fail to StartAbility, err:%{public}d", err);
679 return false;
680 }
681 return true;
682 }
683
StartUsingPermission(AccessTokenID tokenId,const std::string & permissionName)684 int32_t PermissionRecordManager::StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName)
685 {
686 ACCESSTOKEN_LOG_INFO(LABEL, "Entry, tokenId=0x%{public}x, permissionName=%{public}s",
687 tokenId, permissionName.c_str());
688 if (!Register()) {
689 return PrivacyError::ERR_MALLOC_FAILED;
690 }
691
692 // instantaneous record accessCount set to zero in StartUsingPermission, wait for combine in StopUsingPermission
693 int32_t accessCount = 0;
694 int32_t failCount = 0;
695
696 PermissionRecord record = { 0 };
697 int32_t result = GetPermissionRecord(tokenId, permissionName, accessCount, failCount, record);
698 if (result != Constant::SUCCESS) {
699 return result;
700 }
701
702 if (AddRecordToStartList(record)) {
703 return PrivacyError::ERR_PERMISSION_ALREADY_START_USING;
704 }
705
706 if (!GetGlobalSwitchStatus(permissionName)) {
707 if (!ShowGlobalDialog(permissionName)) {
708 ACCESSTOKEN_LOG_ERROR(LABEL, "show permission dialog failed.");
709 RemoveRecordFromStartList(record);
710 return ERR_SERVICE_ABNORMAL;
711 }
712 record.status = PERM_INACTIVE;
713 } else {
714 CallbackExecute(tokenId, permissionName, record.status);
715 }
716 UpdateRecord(record);
717 return Constant::SUCCESS;
718 }
719
SetCameraCallback(sptr<IRemoteObject> callback)720 void PermissionRecordManager::SetCameraCallback(sptr<IRemoteObject> callback)
721 {
722 std::lock_guard<std::mutex> lock(cameraMutex_);
723 cameraCallback_ = callback;
724 }
725
ExecuteCameraCallbackAsync(AccessTokenID tokenId)726 void PermissionRecordManager::ExecuteCameraCallbackAsync(AccessTokenID tokenId)
727 {
728 ACCESSTOKEN_LOG_DEBUG(LABEL, "entry");
729 auto task = [tokenId, this]() {
730 ACCESSTOKEN_LOG_INFO(LABEL, "ExecuteCameraCallbackAsync task called");
731 sptr<IRemoteObject> cameraCallback = nullptr;
732 {
733 std::lock_guard<std::mutex> lock(this->cameraMutex_);
734 cameraCallback = this->cameraCallback_;
735 if (cameraCallback == nullptr) {
736 ACCESSTOKEN_LOG_ERROR(LABEL, "cameraCallback is null");
737 return;
738 }
739 }
740 auto callback = iface_cast<IStateChangeCallback>(cameraCallback);
741 if (callback != nullptr) {
742 ACCESSTOKEN_LOG_INFO(LABEL, "callback excute changeType %{public}d", PERM_INACTIVE);
743 callback->StateChangeNotify(tokenId, false);
744 SetCameraCallback(nullptr);
745 }
746 };
747 std::thread executeThread(task);
748 executeThread.detach();
749 ACCESSTOKEN_LOG_DEBUG(LABEL, "The callback execution is complete");
750 }
751
StartUsingPermission(AccessTokenID tokenId,const std::string & permissionName,const sptr<IRemoteObject> & callback)752 int32_t PermissionRecordManager::StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName,
753 const sptr<IRemoteObject>& callback)
754 {
755 ACCESSTOKEN_LOG_INFO(LABEL, "Entry, tokenId=0x%{public}x, permissionName=%{public}s",
756 tokenId, permissionName.c_str());
757 if (permissionName != CAMERA_PERMISSION_NAME) {
758 ACCESSTOKEN_LOG_ERROR(LABEL, "ERR_PARAM_INVALID is null.");
759 return PrivacyError::ERR_PARAM_INVALID;
760 }
761 if (!Register()) {
762 return PrivacyError::ERR_MALLOC_FAILED;
763 }
764
765 // instantaneous record accessCount set to zero in StartUsingPermission, wait for combine in StopUsingPermission
766 int32_t accessCount = 0;
767 int32_t failCount = 0;
768 PermissionRecord record = { 0 };
769 int32_t result = GetPermissionRecord(tokenId, permissionName, accessCount, failCount, record);
770 if (result != Constant::SUCCESS) {
771 return result;
772 }
773 if (AddRecordToStartList(record)) {
774 return PrivacyError::ERR_PERMISSION_ALREADY_START_USING;
775 }
776 if (!GetGlobalSwitchStatus(permissionName)) {
777 if (!ShowGlobalDialog(permissionName)) {
778 ACCESSTOKEN_LOG_ERROR(LABEL, "show permission dialog failed.");
779 RemoveRecordFromStartList(record);
780 return ERR_SERVICE_ABNORMAL;
781 }
782 record.status = PERM_INACTIVE;
783 } else {
784 CallbackExecute(tokenId, permissionName, record.status);
785 }
786 SetCameraCallback(callback);
787 UpdateRecord(record);
788 return Constant::SUCCESS;
789 }
790
StopUsingPermission(AccessTokenID tokenId,const std::string & permissionName)791 int32_t PermissionRecordManager::StopUsingPermission(AccessTokenID tokenId, const std::string& permissionName)
792 {
793 ACCESSTOKEN_LOG_INFO(LABEL, "Entry, tokenId=0x%{public}x, permissionName=%{public}s",
794 tokenId, permissionName.c_str());
795 ExecuteDeletePermissionRecordTask();
796
797 if (AccessTokenKit::GetTokenTypeFlag(tokenId) != TOKEN_HAP) {
798 ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenId(%{public}d)", tokenId);
799 return PrivacyError::ERR_TOKENID_NOT_EXIST;
800 }
801 int32_t opCode;
802 if (!Constant::TransferPermissionToOpcode(permissionName, opCode)) {
803 ACCESSTOKEN_LOG_ERROR(LABEL, "invalid permission(%{public}s)", permissionName.c_str());
804 return PrivacyError::ERR_PERMISSION_NOT_EXIST;
805 }
806
807 PermissionRecord record;
808 if (!GetRecordFromStartList(tokenId, opCode, record)) {
809 return PrivacyError::ERR_PERMISSION_NOT_START_USING;
810 }
811
812 if (record.status != PERM_INACTIVE) {
813 CallbackExecute(tokenId, permissionName, PERM_INACTIVE);
814 }
815 return Constant::SUCCESS;
816 }
817
PermListToString(const std::vector<std::string> & permList)818 void PermissionRecordManager::PermListToString(const std::vector<std::string>& permList)
819 {
820 std::string permStr;
821 permStr = accumulate(permList.begin(), permList.end(), std::string(" "));
822
823 ACCESSTOKEN_LOG_INFO(LABEL, "permStr =%{public}s", permStr.c_str());
824 }
825
PermissionListFilter(const std::vector<std::string> & listSrc,std::vector<std::string> & listRes)826 int32_t PermissionRecordManager::PermissionListFilter(
827 const std::vector<std::string>& listSrc, std::vector<std::string>& listRes)
828 {
829 // filter legal permissions
830 PermissionDef permissionDef;
831 std::set<std::string> permSet;
832 for (const auto& permissionName : listSrc) {
833 if (AccessTokenKit::GetDefPermission(permissionName, permissionDef) == Constant::SUCCESS &&
834 permSet.count(permissionName) == 0) {
835 listRes.emplace_back(permissionName);
836 permSet.insert(permissionName);
837 continue;
838 }
839 ACCESSTOKEN_LOG_ERROR(LABEL, "permission %{public}s invalid!", permissionName.c_str());
840 }
841 if ((listRes.empty()) && (!listSrc.empty())) {
842 ACCESSTOKEN_LOG_ERROR(LABEL, "valid permission size is 0!");
843 return PrivacyError::ERR_PARAM_INVALID;
844 }
845 PermListToString(listRes);
846 return Constant::SUCCESS;
847 }
848
IsAllowedUsingPermission(AccessTokenID tokenId,const std::string & permissionName)849 bool PermissionRecordManager::IsAllowedUsingPermission(AccessTokenID tokenId, const std::string& permissionName)
850 {
851 // when app in foreground, return true, only for camera and microphone
852 if ((permissionName != CAMERA_PERMISSION_NAME) && (permissionName != MICROPHONE_PERMISSION_NAME)) {
853 return false;
854 }
855
856 HapTokenInfo tokenInfo;
857 if (AccessTokenKit::GetTokenTypeFlag(tokenId) != TOKEN_HAP) {
858 ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenId(%{public}d)", tokenId);
859 return false;
860 }
861
862 int32_t status = GetAppStatus(tokenId);
863 ACCESSTOKEN_LOG_INFO(LABEL, "tokenId %{public}d, status is %{public}d", tokenId, status);
864
865 if (status == ActiveChangeType::PERM_ACTIVE_IN_FOREGROUND) {
866 return true;
867 }
868 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
869 if (permissionName == CAMERA_PERMISSION_NAME) {
870 return IsFlowWindowShow(tokenId);
871 }
872 #endif
873 return false;
874 }
875
RegisterPermActiveStatusCallback(const std::vector<std::string> & permList,const sptr<IRemoteObject> & callback)876 int32_t PermissionRecordManager::RegisterPermActiveStatusCallback(
877 const std::vector<std::string>& permList, const sptr<IRemoteObject>& callback)
878 {
879 std::vector<std::string> permListRes;
880 int32_t res = PermissionListFilter(permList, permListRes);
881 if (res != Constant::SUCCESS) {
882 return res;
883 }
884 return ActiveStatusCallbackManager::GetInstance().AddCallback(permListRes, callback);
885 }
886
UnRegisterPermActiveStatusCallback(const sptr<IRemoteObject> & callback)887 int32_t PermissionRecordManager::UnRegisterPermActiveStatusCallback(const sptr<IRemoteObject>& callback)
888 {
889 return ActiveStatusCallbackManager::GetInstance().RemoveCallback(callback);
890 }
891
GetDeviceId(AccessTokenID tokenId)892 std::string PermissionRecordManager::GetDeviceId(AccessTokenID tokenId)
893 {
894 HapTokenInfo tokenInfo;
895 if (AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo) != Constant::SUCCESS) {
896 return "";
897 }
898 if (tokenInfo.deviceID == DEFAULT_DEVICEID) { // local
899 return ConstantCommon::GetLocalDeviceId();
900 }
901 return tokenInfo.deviceID;
902 }
903
GetAppStatus(AccessTokenID tokenId)904 int32_t PermissionRecordManager::GetAppStatus(AccessTokenID tokenId)
905 {
906 int32_t status = PERM_INACTIVE;
907 HapTokenInfo tokenInfo;
908 if (AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo) != Constant::SUCCESS) {
909 ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenId(%{public}d)", tokenId);
910 return status;
911 }
912 status = PERM_ACTIVE_IN_BACKGROUND;
913 std::vector<AppStateData> foreGroundAppList;
914 AppManagerAccessClient::GetInstance().GetForegroundApplications(foreGroundAppList);
915 if (std::any_of(foreGroundAppList.begin(), foreGroundAppList.end(),
916 [=](const auto& foreGroundApp) { return foreGroundApp.bundleName == tokenInfo.bundleName; })) {
917 status = PERM_ACTIVE_IN_FOREGROUND;
918 }
919 return status;
920 }
921
RegisterAppStatusAndLockScreenStatusListener()922 bool PermissionRecordManager::RegisterAppStatusAndLockScreenStatusListener()
923 {
924 // app manager death callback register
925 {
926 std::lock_guard<std::mutex> lock(appManagerDeathMutex_);
927 if (appManagerDeathCallback_ == nullptr) {
928 appManagerDeathCallback_ = std::make_shared<PrivacyAppManagerDeathCallback>();
929 if (appManagerDeathCallback_ == nullptr) {
930 ACCESSTOKEN_LOG_ERROR(LABEL, "register appManagerDeathCallback failed.");
931 return false;
932 }
933 AppManagerAccessClient::GetInstance().RegisterDeathCallbak(appManagerDeathCallback_);
934 }
935 }
936 // app state change callback register
937 {
938 std::lock_guard<std::mutex> lock(appStateMutex_);
939 if (appStateCallback_ == nullptr) {
940 appStateCallback_ = new(std::nothrow) PrivacyAppStateObserver();
941 if (appStateCallback_ == nullptr) {
942 ACCESSTOKEN_LOG_ERROR(LABEL, "register appStateCallback failed.");
943 return false;
944 }
945 AppManagerAccessClient::GetInstance().RegisterApplicationStateObserver(appStateCallback_);
946 }
947 }
948 #ifdef THEME_SCREENLOCK_MGR_ENABLE
949 // lockscreen status change call back register
950 #ifdef COMMON_EVENT_SERVICE_ENABLE
951 {
952 std::lock_guard<std::mutex> lock(lockScreenStateMutex_);
953 LockscreenObserver::RegisterEvent();
954 }
955 #endif //COMMON_EVENT_SERVICE_ENABLE
956 #endif
957 return true;
958 }
959
Register()960 bool PermissionRecordManager::Register()
961 {
962 // microphone mute
963 {
964 std::lock_guard<std::mutex> lock(micCallbackMutex_);
965 if (micMuteCallback_ == nullptr) {
966 micMuteCallback_ = new(std::nothrow) AudioRoutingManagerListenerStub();
967 if (micMuteCallback_ == nullptr) {
968 ACCESSTOKEN_LOG_ERROR(LABEL, "register micMuteCallback failed.");
969 return false;
970 }
971 AudioManagerPrivacyClient::GetInstance().SetMicStateChangeCallback(micMuteCallback_);
972 }
973 }
974
975 // camera mute
976 {
977 std::lock_guard<std::mutex> lock(cameraCallbackMutex_);
978 if (camMuteCallback_ == nullptr) {
979 camMuteCallback_ = new(std::nothrow) CameraServiceCallbackStub();
980 if (camMuteCallback_ == nullptr) {
981 ACCESSTOKEN_LOG_ERROR(LABEL, "register camMuteCallback failed.");
982 return false;
983 }
984 CameraManagerPrivacyClient::GetInstance().SetMuteCallback(camMuteCallback_);
985 }
986 }
987 {
988 std::lock_guard<std::mutex> lock(micMuteMutex_);
989 isMicMute_ = AudioManagerPrivacyClient::GetInstance().IsMicrophoneMute();
990 }
991 {
992 std::lock_guard<std::mutex> lock(camMuteMutex_);
993 isCameraMute_ = CameraManagerPrivacyClient::GetInstance().IsCameraMuted();
994 }
995 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
996 // float window status change callback register
997 {
998 std::lock_guard<std::mutex> lock(floatWinMutex_);
999 if (floatWindowCallback_ == nullptr) {
1000 floatWindowCallback_ = new(std::nothrow) WindowManagerPrivacyAgent();
1001 if (floatWindowCallback_ == nullptr) {
1002 ACCESSTOKEN_LOG_ERROR(LABEL, "register floatWindowCallback failed.");
1003 return false;
1004 }
1005 WindowManagerPrivacyClient::GetInstance().RegisterWindowManagerAgent(
1006 WindowManagerAgentType::WINDOW_MANAGER_AGENT_TYPE_CAMERA_FLOAT, floatWindowCallback_);
1007 }
1008 }
1009 #endif
1010 // app state change and lockscreen state change callback register
1011 return RegisterAppStatusAndLockScreenStatusListener();
1012 }
1013
Unregister()1014 void PermissionRecordManager::Unregister()
1015 {
1016 // app state change callback unregister
1017 {
1018 std::lock_guard<std::mutex> lock(appStateMutex_);
1019 if (appStateCallback_ != nullptr) {
1020 AppManagerAccessClient::GetInstance().UnregisterApplicationStateObserver(appStateCallback_);
1021 appStateCallback_= nullptr;
1022 }
1023 }
1024
1025 #ifdef THEME_SCREENLOCK_MGR_ENABLE
1026 // screen state change callback unregister
1027 #ifdef COMMON_EVENT_SERVICE_ENABLE
1028 {
1029 std::lock_guard<std::mutex> lock(lockScreenStateMutex_);
1030 LockscreenObserver::UnRegisterEvent();
1031 }
1032 #endif //COMMON_EVENT_SERVICE_ENABLE
1033 #endif
1034
1035 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
1036 // float window status change callback unregister
1037 {
1038 std::lock_guard<std::mutex> lock(floatWinMutex_);
1039 if (floatWindowCallback_ != nullptr) {
1040 WindowManagerPrivacyClient::GetInstance().UnregisterWindowManagerAgent(
1041 WindowManagerAgentType::WINDOW_MANAGER_AGENT_TYPE_CAMERA_FLOAT, floatWindowCallback_);
1042 floatWindowCallback_ = nullptr;
1043 }
1044 }
1045 #endif
1046 }
1047
OnAppMgrRemoteDiedHandle()1048 void PermissionRecordManager::OnAppMgrRemoteDiedHandle()
1049 {
1050 std::lock_guard<std::mutex> lock(appStateMutex_);
1051 appStateCallback_ = nullptr;
1052 }
1053
OnAudioMgrRemoteDiedHandle()1054 void PermissionRecordManager::OnAudioMgrRemoteDiedHandle()
1055 {
1056 {
1057 std::lock_guard<std::mutex> lock(micMuteMutex_);
1058 isMicMute_ = false;
1059 }
1060 {
1061 std::lock_guard<std::mutex> lock(micCallbackMutex_);
1062 micMuteCallback_ = nullptr;
1063 }
1064 }
1065
OnCameraMgrRemoteDiedHandle()1066 void PermissionRecordManager::OnCameraMgrRemoteDiedHandle()
1067 {
1068 {
1069 std::lock_guard<std::mutex> lock(camMuteMutex_);
1070 isCameraMute_ = false;
1071 }
1072 {
1073 std::lock_guard<std::mutex> lock(cameraCallbackMutex_);
1074 camMuteCallback_ = nullptr;
1075 }
1076 }
1077
1078 #ifdef CAMERA_FLOAT_WINDOW_ENABLE
1079 /*
1080 * when camera float window is not show, notice camera service to use StopUsingPermission
1081 */
NotifyCameraFloatWindowChange(AccessTokenID tokenId,bool isShowing)1082 void PermissionRecordManager::NotifyCameraFloatWindowChange(AccessTokenID tokenId, bool isShowing)
1083 {
1084 camFloatWindowShowing_ = isShowing;
1085 floatWindowTokenId_ = tokenId;
1086 if ((GetAppStatus(tokenId) == ActiveChangeType::PERM_ACTIVE_IN_BACKGROUND) && !isShowing) {
1087 ACCESSTOKEN_LOG_INFO(LABEL, "camera float window is close!");
1088 ExecuteCameraCallbackAsync(tokenId);
1089 } else {
1090 ACCESSTOKEN_LOG_INFO(LABEL, "camera float window is show!");
1091 }
1092 }
1093
OnWindowMgrRemoteDiedHandle()1094 void PermissionRecordManager::OnWindowMgrRemoteDiedHandle()
1095 {
1096 std::lock_guard<std::mutex> lock(floatWinMutex_);
1097 floatWindowCallback_ = nullptr;
1098 }
1099
IsFlowWindowShow(AccessTokenID tokenId)1100 bool PermissionRecordManager::IsFlowWindowShow(AccessTokenID tokenId)
1101 {
1102 return floatWindowTokenId_ == tokenId && camFloatWindowShowing_;
1103 }
1104 #endif
1105
1106 #ifdef CUSTOMIZATION_CONFIG_POLICY_ENABLE
GetConfigFilePathList(std::vector<std::string> & pathList)1107 void PermissionRecordManager::GetConfigFilePathList(std::vector<std::string>& pathList)
1108 {
1109 CfgDir *dirs = GetCfgDirList(); // malloc a CfgDir point, need to free later
1110 if (dirs != nullptr) {
1111 for (const auto& path : dirs->paths) {
1112 if (path == nullptr) {
1113 continue;
1114 }
1115
1116 ACCESSTOKEN_LOG_INFO(LABEL, "accesstoken cfg dir: %{public}s", path);
1117 pathList.emplace_back(path);
1118 }
1119
1120 FreeCfgDirList(dirs); // free
1121 } else {
1122 ACCESSTOKEN_LOG_ERROR(LABEL, "can't get cfg file path");
1123 }
1124 }
1125
1126 // nlohmann json need the function named from_json to parse
from_json(const nlohmann::json & j,PermissionRecordConfig & p)1127 void from_json(const nlohmann::json& j, PermissionRecordConfig& p)
1128 {
1129 if (!JsonParser::GetIntFromJson(j, RECORD_SIZE_MAXIMUM_KEY, p.sizeMaxImum)) {
1130 return;
1131 }
1132
1133 if (!JsonParser::GetIntFromJson(j, RECORD_AGING_TIME_KEY, p.agingTime)) {
1134 return;
1135 }
1136 }
1137
GetConfigValueFromFile(std::string & fileContent)1138 bool PermissionRecordManager::GetConfigValueFromFile(std::string& fileContent)
1139 {
1140 nlohmann::json jsonRes = nlohmann::json::parse(fileContent, nullptr, false);
1141 if (jsonRes.is_discarded()) {
1142 ACCESSTOKEN_LOG_ERROR(LABEL, "jsonRes is invalid.");
1143 return false;
1144 }
1145
1146 if ((jsonRes.find("privacy") != jsonRes.end()) && (jsonRes.at("privacy").is_object())) {
1147 PermissionRecordConfig p = jsonRes.at("privacy").get<nlohmann::json>();
1148 recordSizeMaximum_ = p.sizeMaxImum;
1149 recordAgingTime_ = p.agingTime;
1150 } else {
1151 return false;
1152 }
1153
1154 return true;
1155 }
1156 #endif
1157
SetDefaultConfigValue()1158 void PermissionRecordManager::SetDefaultConfigValue()
1159 {
1160 ACCESSTOKEN_LOG_INFO(LABEL, "no config file or config file is not valid, use default values");
1161
1162 recordSizeMaximum_ = DEFAULT_PERMISSION_USED_RECORD_SIZE_MAXIMUM;
1163 recordAgingTime_ = DEFAULT_PERMISSION_USED_RECORD_AGING_TIME;
1164 }
1165
GetConfigValue()1166 void PermissionRecordManager::GetConfigValue()
1167 {
1168 #ifdef CUSTOMIZATION_CONFIG_POLICY_ENABLE
1169 std::vector<std::string> pathList;
1170 GetConfigFilePathList(pathList);
1171
1172 for (const auto& path : pathList) {
1173 if (!JsonParser::IsDirExsit(path)) {
1174 continue;
1175 }
1176
1177 std::string filePath = path + ACCESSTOKEN_CONFIG_FILE;
1178 std::string fileContent;
1179 int32_t res = JsonParser::ReadCfgFile(filePath, fileContent);
1180 if (res != Constant::SUCCESS) {
1181 continue;
1182 }
1183
1184 if (GetConfigValueFromFile(fileContent)) {
1185 break; // once get the config value, break the loop
1186 }
1187 }
1188 #endif
1189 // when config file list empty or can not get two value from config file, set default value
1190 if ((recordSizeMaximum_ == 0) || (recordAgingTime_ == 0)) {
1191 SetDefaultConfigValue();
1192 }
1193
1194 ACCESSTOKEN_LOG_INFO(LABEL, "recordSizeMaximum_ is %{public}d, recordAgingTime_ is %{public}d",
1195 recordSizeMaximum_, recordAgingTime_);
1196 }
1197
GetRecordSizeMaxImum()1198 int32_t PermissionRecordManager::GetRecordSizeMaxImum()
1199 {
1200 return recordSizeMaximum_;
1201 }
1202
GetRecordAgingTime()1203 int32_t PermissionRecordManager::GetRecordAgingTime()
1204 {
1205 return recordAgingTime_;
1206 }
1207
Init()1208 void PermissionRecordManager::Init()
1209 {
1210 if (hasInited_) {
1211 return;
1212 }
1213 ACCESSTOKEN_LOG_INFO(LABEL, "init");
1214 deleteTaskWorker_.Start(1);
1215 hasInited_ = true;
1216
1217 GetConfigValue();
1218 }
1219 } // namespace AccessToken
1220 } // namespace Security
1221 } // namespace OHOS