• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 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 "sensor_service.h"
17 
18 #include <charconv>
19 #include <cinttypes>
20 #include <string_ex.h>
21 #include <sys/time.h>
22 #include <tokenid_kit.h>
23 
24 #ifdef HIVIEWDFX_HISYSEVENT_ENABLE
25 #include "hisysevent.h"
26 #endif // HIVIEWDFX_HISYSEVENT_ENABLE
27 #include "iservice_registry.h"
28 #ifdef MEMMGR_ENABLE
29 #include "mem_mgr_client.h"
30 #endif // MEMMGR_ENABLE
31 #include "motion_plugin.h"
32 #include "ipc_skeleton.h"
33 #include "permission_util.h"
34 #include "parameters.h"
35 
36 #include "print_sensor_data.h"
37 #include "sensor_dump.h"
38 #include "system_ability_definition.h"
39 
40 #undef LOG_TAG
41 #define LOG_TAG "SensorService"
42 
43 namespace OHOS {
44 namespace Sensors {
45 using namespace OHOS::HiviewDFX;
46 namespace {
47 auto g_sensorService = SensorDelayedSpSingleton<SensorService>::GetInstance();
48 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(g_sensorService.GetRefPtr());
49 constexpr int32_t INVALID_PID = -1;
50 constexpr int64_t MAX_EVENT_COUNT = 1000;
51 constexpr int32_t SENSOR_ONLINE = 1;
52 std::atomic_bool g_isRegister = false;
53 constexpr int32_t SINGLE_DISPLAY_SMALL_FOLD = 4;
54 constexpr int32_t SINGLE_DISPLAY_THREE_FOLD = 6;
55 const std::string DEFAULTS_FOLD_TYPE = "0,0,0,0";
56 const std::set<int32_t> g_systemApiSensorCall = {
57     SENSOR_TYPE_ID_COLOR, SENSOR_TYPE_ID_SAR, SENSOR_TYPE_ID_HEADPOSTURE
58 };
59 } // namespace
60 
61 std::atomic_bool SensorService::isAccessTokenServiceActive_ = false;
62 std::atomic_bool SensorService::isMemoryMgrServiceActive_ = false;
63 std::atomic_bool SensorService::isCritical_ = false;
64 
SensorService()65 SensorService::SensorService()
66     : SystemAbility(SENSOR_SERVICE_ABILITY_ID, true), state_(SensorServiceState::STATE_STOPPED)
67 {
68     SEN_HILOGD("Add SystemAbility");
69 }
70 
~SensorService()71 SensorService::~SensorService()
72 {
73     UnloadMotionSensor();
74 }
75 
OnDump()76 void SensorService::OnDump()
77 {
78     SEN_HILOGI("OnDump");
79 }
80 
GetDmsDeviceStatus()81 std::string GetDmsDeviceStatus()
82 {
83     return OHOS::system::GetParameter("persist.dms.device.status", "0");
84 }
85 
IsNeedLoadMotionLib()86 bool SensorService::IsNeedLoadMotionLib()
87 {
88     std::string supportDevice = OHOS::system::GetParameter("const.window.foldscreen.type", DEFAULTS_FOLD_TYPE);
89     size_t index = supportDevice.find(',');
90     if (index != std::string::npos) {
91         std::string firstValue = supportDevice.substr(0, index);
92         SEN_HILOGI("firstValue:%{public}s", firstValue.c_str());
93         if (std::isdigit(firstValue[0]) == 0) {
94             SEN_HILOGI("firstValue is not number");
95             return false;
96         }
97         int32_t firstValueNum = 0;
98         auto res = std::from_chars(firstValue.data(), firstValue.data() + firstValue.size(), firstValueNum);
99         if (res.ec != std::errc()) {
100             SEN_HILOGE("Failed to convert string %{public}s to number", firstValue.c_str());
101             return false;
102         }
103         if (firstValueNum == SINGLE_DISPLAY_SMALL_FOLD || firstValueNum == SINGLE_DISPLAY_THREE_FOLD) {
104             return true;
105         }
106     }
107     SEN_HILOGI("Not support in this device");
108     return false;
109 }
110 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)111 void SensorService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
112 {
113     SEN_HILOGI("OnAddSystemAbility systemAbilityId:%{public}d", systemAbilityId);
114 #ifdef MEMMGR_ENABLE
115     if (systemAbilityId == MEMORY_MANAGER_SA_ID) {
116         Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(),
117             PROCESS_TYPE_SA, PROCESS_STATUS_STARTED, SENSOR_SERVICE_ABILITY_ID);
118         isMemoryMgrServiceActive_ = true;
119         SetCritical();
120     }
121 #endif // MEMMGR_ENABLE
122 #ifdef ACCESS_TOKEN_ENABLE
123     if (systemAbilityId == ACCESS_TOKEN_MANAGER_SERVICE_ID) {
124         isAccessTokenServiceActive_ = true;
125     }
126 #endif // ACCESS_TOKEN_ENABLE
127 #ifdef MSDP_MOTION_ENABLE
128     if (systemAbilityId == MSDP_MOTION_SERVICE_ID) {
129         if (!IsNeedLoadMotionLib()) {
130             SEN_HILOGI("No need to load motion lib");
131         } else if (!LoadMotionSensor()) {
132             SEN_HILOGI("LoadMotionSensor fail");
133         }
134     }
135 #endif // MSDP_MOTION_ENABLE
136     if (systemAbilityId == DISPLAY_MANAGER_SERVICE_SA_ID) {
137         std::string statusStr = GetDmsDeviceStatus();
138         int32_t statusNum;
139         auto res = std::from_chars(statusStr.data(), statusStr.data() + statusStr.size(), statusNum);
140         if (res.ec != std::errc()) {
141             SEN_HILOGE("Failed to convert string %{public}s to number", statusStr.c_str());
142             return;
143         }
144         uint32_t status = static_cast<uint32_t>(statusNum);
145         clientInfo_.SetDeviceStatus(status);
146         SEN_HILOGI("GetDeviceStatus, deviceStatus:%{public}d", status);
147     }
148 }
149 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)150 void SensorService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
151 {
152     SEN_HILOGI("OnRemoveSystemAbility systemAbilityId:%{public}d", systemAbilityId);
153 #ifdef ACCESS_TOKEN_ENABLE
154     if (systemAbilityId == ACCESS_TOKEN_MANAGER_SERVICE_ID) {
155         isAccessTokenServiceActive_ = false;
156     }
157 #endif // ACCESS_TOKEN_ENABLE
158 #ifdef MEMMGR_ENABLE
159     if (systemAbilityId == MEMORY_MANAGER_SA_ID) {
160         isMemoryMgrServiceActive_ = false;
161     }
162 #endif // MEMMGR_ENABLE
163 }
164 
OnStart()165 void SensorService::OnStart()
166 {
167     CALL_LOG_ENTER;
168     if (state_ == SensorServiceState::STATE_RUNNING) {
169         SEN_HILOGW("SensorService has already started");
170         return;
171     }
172 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
173     if (!InitInterface()) {
174         SEN_HILOGE("Init interface error");
175     }
176     if (!InitDataCallback()) {
177         SEN_HILOGE("Init data callback error");
178     }
179     if (!InitSensorList()) {
180         SEN_HILOGE("Init sensor list error");
181     }
182     if (!InitPlugCallback()) {
183         SEN_HILOGE("Init plug callback error");
184     }
185     sensorDataProcesser_ = new (std::nothrow) SensorDataProcesser(sensorMap_);
186     CHKPV(sensorDataProcesser_);
187 #endif // HDF_DRIVERS_INTERFACE_SENSOR
188     if (!InitSensorPolicy()) {
189         SEN_HILOGE("Init sensor policy error");
190     }
191 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
192     sensorManager_.InitSensorMap(sensorMap_, sensorDataProcesser_, reportDataCallback_);
193 #else
194     sensorManager_.InitSensorMap(sensorMap_);
195 #endif // HDF_DRIVERS_INTERFACE_SENSOR
196     if (!SystemAbility::Publish(SensorDelayedSpSingleton<SensorService>::GetInstance())) {
197         SEN_HILOGE("Publish SensorService error");
198         return;
199     }
200     state_ = SensorServiceState::STATE_RUNNING;
201 #ifdef MEMMGR_ENABLE
202     AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
203 #endif // MEMMGR_ENABLE
204 #ifdef ACCESS_TOKEN_ENABLE
205     AddSystemAbilityListener(ACCESS_TOKEN_MANAGER_SERVICE_ID);
206 #endif // ACCESS_TOKEN_ENABLE
207 #ifdef MSDP_MOTION_ENABLE
208     AddSystemAbilityListener(MSDP_MOTION_SERVICE_ID);
209 #endif // MSDP_MOTION_ENABLE
210     AddSystemAbilityListener(DISPLAY_MANAGER_SERVICE_SA_ID);
211 }
212 
213 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
InitInterface()214 bool SensorService::InitInterface()
215 {
216     auto ret = sensorHdiConnection_.ConnectHdi();
217     if (ret != ERR_OK) {
218         SEN_HILOGE("Connect hdi failed");
219         return false;
220     }
221     return true;
222 }
223 
InitPlugCallback()224 bool SensorService::InitPlugCallback()
225 {
226     auto ret = sensorHdiConnection_.RegSensorPlugCallback(
227         std::bind(&SensorService::ReportPlugEventCallback, this, std::placeholders::_1));
228     if (ret != ERR_OK) {
229         SEN_HILOGE("RegSensorPlugCallback failed");
230         return false;
231     }
232     return true;
233 }
234 
InitDataCallback()235 bool SensorService::InitDataCallback()
236 {
237     reportDataCallback_ = new (std::nothrow) ReportDataCallback();
238     CHKPF(reportDataCallback_);
239     ReportDataCb cb = &ReportDataCallback::ReportEventCallback;
240     auto ret = sensorHdiConnection_.RegisterDataReport(cb, reportDataCallback_);
241     if (ret != ERR_OK) {
242         SEN_HILOGE("RegisterDataReport failed");
243         return false;
244     }
245     return true;
246 }
247 
InitSensorList()248 bool SensorService::InitSensorList()
249 {
250     std::lock_guard<std::mutex> sensorLock(sensorsMutex_);
251     int32_t ret = sensorHdiConnection_.GetSensorList(sensors_);
252     if (ret != 0) {
253         SEN_HILOGE("GetSensorList is failed");
254         return false;
255     }
256     {
257         std::lock_guard<std::mutex> sensorMapLock(sensorMapMutex_);
258         for (const auto &it : sensors_) {
259             if (!(sensorMap_.insert(std::pair<SensorDescription, Sensor>({
260                 it.GetDeviceId(), it.GetSensorTypeId(), it.GetSensorId(), it.GetLocation()}, it)).second)) {
261                 SEN_HILOGW("sensorMap_ insert failed");
262             }
263         }
264     }
265     return true;
266 }
267 #endif // HDF_DRIVERS_INTERFACE_SENSOR
268 
InitSensorPolicy()269 bool SensorService::InitSensorPolicy()
270 {
271     return true;
272 }
273 
OnStop()274 void SensorService::OnStop()
275 {
276     CALL_LOG_ENTER;
277     if (state_ == SensorServiceState::STATE_STOPPED) {
278         SEN_HILOGW("Already stopped");
279         return;
280     }
281     state_ = SensorServiceState::STATE_STOPPED;
282 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
283     int32_t ret = sensorHdiConnection_.DestroyHdiConnection();
284     if (ret != ERR_OK) {
285         SEN_HILOGE("Destroy hdi connect fail");
286     }
287 #endif // HDF_DRIVERS_INTERFACE_SENSOR
288     UnregisterPermCallback();
289 #ifdef MEMMGR_ENABLE
290     Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), PROCESS_TYPE_SA, PROCESS_STATUS_DIED,
291         SENSOR_SERVICE_ABILITY_ID);
292 #endif // MEMMGR_ENABLE
293 }
294 
ReportSensorSysEvent(int32_t sensorType,bool enable,int32_t pid,int64_t samplingPeriodNs,int64_t maxReportDelayNs)295 void SensorService::ReportSensorSysEvent(int32_t sensorType, bool enable, int32_t pid, int64_t samplingPeriodNs,
296     int64_t maxReportDelayNs)
297 {
298     std::string packageName("");
299     AccessTokenID tokenId = clientInfo_.GetTokenIdByPid(pid);
300     sensorManager_.GetPackageName(tokenId, packageName, isAccessTokenServiceActive_);
301 #ifdef HIVIEWDFX_HISYSEVENT_ENABLE
302     const int logLevel = 4;
303     int32_t uid = clientInfo_.GetUidByPid(pid);
304 #endif // HIVIEWDFX_HISYSEVENT_ENABLE
305     if (enable) {
306 #ifdef HIVIEWDFX_HISYSEVENT_ENABLE
307         HiSysEventWrite(HiSysEvent::Domain::SENSOR, "ENABLE_SENSOR", HiSysEvent::EventType::STATISTIC,
308             "LEVEL", logLevel, "PKG_NAME", packageName, "TYPE", sensorType, "UID", uid, "PID", pid);
309 #endif // HIVIEWDFX_HISYSEVENT_ENABLE
310         SEN_HILOGI("PackageName:%{public}s open the sensor, sensorType:%{public}d, pid:%{public}d, "
311             "samplingPeriodNs:%{public}" PRId64 ", samplingPeriodNs:%{public}" PRId64, packageName.c_str(),
312             sensorType, pid, samplingPeriodNs, maxReportDelayNs);
313     } else {
314 #ifdef HIVIEWDFX_HISYSEVENT_ENABLE
315         HiSysEventWrite(HiSysEvent::Domain::SENSOR, "DISABLE_SENSOR", HiSysEvent::EventType::STATISTIC,
316             "LEVEL", logLevel, "TYPE", sensorType, "PKG_NAME", packageName, "UID", uid, "PID", pid);
317 #endif // HIVIEWDFX_HISYSEVENT_ENABLE
318         SEN_HILOGI("PackageName:%{public}s close the sensor, sensorType:%{public}d, pid:%{public}d",
319             packageName.c_str(), sensorType, pid);
320     }
321 }
322 
ReportOnChangeData(const SensorDescription & sensorDesc)323 void SensorService::ReportOnChangeData(const SensorDescription &sensorDesc)
324 {
325     std::lock_guard<std::mutex> sensorMapLock(sensorMapMutex_);
326     auto it = sensorMap_.find(sensorDesc);
327     if (it == sensorMap_.end()) {
328         SEN_HILOGE("sensorDesc is invalid");
329         return;
330     }
331     if ((SENSOR_ON_CHANGE & it->second.GetFlags()) != SENSOR_ON_CHANGE) {
332         SEN_HILOGW("The data has not changed , no need to report");
333         return;
334     }
335     SensorData sensorData;
336     auto ret = clientInfo_.GetStoreEvent(sensorDesc, sensorData);
337     if (ret != ERR_OK) {
338         SEN_HILOGE("There is no data to be reported");
339         return;
340     }
341     sptr<SensorBasicDataChannel> channel = clientInfo_.GetSensorChannelByPid(GetCallingPid());
342     CHKPV(channel);
343     auto sendRet = channel->SendData(&sensorData, sizeof(sensorData));
344     if (sendRet != ERR_OK) {
345         SEN_HILOGE("Send data failed");
346         return;
347     }
348 }
349 
SaveSubscriber(const SensorDescription & sensorDesc,int64_t samplingPeriodNs,int64_t maxReportDelayNs)350 ErrCode SensorService::SaveSubscriber(const SensorDescription &sensorDesc, int64_t samplingPeriodNs,
351     int64_t maxReportDelayNs)
352 {
353     SEN_HILOGI("In, deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d",
354         sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId);
355     if (!sensorManager_.SaveSubscriber(sensorDesc, GetCallingPid(), samplingPeriodNs, maxReportDelayNs)) {
356         SEN_HILOGE("SaveSubscriber failed");
357         return UPDATE_SENSOR_INFO_ERR;
358     }
359 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
360     sensorManager_.StartDataReportThread();
361     SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorDesc, GetCallingPid());
362     if (!sensorManager_.SetBestSensorParams(sensorDesc,
363         sensorInfo.GetSamplingPeriodNs(), sensorInfo.GetMaxReportDelayNs())) {
364         SEN_HILOGE("SetBestSensorParams failed");
365         clientInfo_.RemoveSubscriber(sensorDesc, GetCallingPid());
366         return SET_SENSOR_CONFIG_ERR;
367     }
368 #endif // HDF_DRIVERS_INTERFACE_SENSOR
369     SEN_HILOGI("Done, deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d",
370         sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId);
371     return ERR_OK;
372 }
373 
CheckSensorId(const SensorDescription & sensorDesc)374 bool SensorService::CheckSensorId(const SensorDescription &sensorDesc)
375 {
376     std::lock_guard<std::mutex> sensorMapLock(sensorMapMutex_);
377     auto it = sensorMap_.find(sensorDesc);
378     if (it == sensorMap_.end()) {
379         SEN_HILOGE("Invalid sensorDesc,"
380             "deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d, peripheralId:%{public}d",
381             sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, sensorDesc.location);
382         return false;
383     }
384     return true;
385 }
386 
IsSystemServiceCalling()387 bool SensorService::IsSystemServiceCalling()
388 {
389     const auto tokenId = IPCSkeleton::GetCallingTokenID();
390     const auto flag = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
391     if (flag == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
392         flag == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL) {
393         SEN_HILOGD("system service calling, flag: %{public}u", flag);
394         return true;
395     }
396     return false;
397 }
398 
IsSystemCalling()399 bool SensorService::IsSystemCalling()
400 {
401     if (IsSystemServiceCalling()) {
402         return true;
403     }
404     return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID());
405 }
406 
CheckAuthAndParameter(const SensorDescription & sensorDesc,int64_t samplingPeriodNs,int64_t maxReportDelayNs)407 ErrCode SensorService::CheckAuthAndParameter(const SensorDescription &sensorDesc, int64_t samplingPeriodNs,
408     int64_t maxReportDelayNs)
409 {
410     if (((g_systemApiSensorCall.find(sensorDesc.sensorType) != g_systemApiSensorCall.end()) ||
411         (sensorDesc.sensorType > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE)) && !IsSystemCalling()) {
412         SEN_HILOGE("Permission check failed. A non-system application uses the system API");
413         return NON_SYSTEM_API;
414     }
415     PermissionUtil &permissionUtil = PermissionUtil::GetInstance();
416     int32_t ret = permissionUtil.CheckSensorPermission(GetCallingTokenID(), sensorDesc.sensorType);
417     if (ret != PERMISSION_GRANTED) {
418 #ifdef HIVIEWDFX_HISYSEVENT_ENABLE
419         HiSysEventWrite(HiSysEvent::Domain::SENSOR, "VERIFY_ACCESS_TOKEN_FAIL", HiSysEvent::EventType::SECURITY,
420             "PKG_NAME", "SensorEnableInner", "ERROR_CODE", ret);
421 #endif // HIVIEWDFX_HISYSEVENT_ENABLE
422         SEN_HILOGE("sensorType:%{public}d grant failed, ret:%{public}d", sensorDesc.sensorType, ret);
423         return PERMISSION_DENIED;
424     }
425     if ((!CheckSensorId(sensorDesc)) || (maxReportDelayNs != 0L && samplingPeriodNs != 0L &&
426         ((maxReportDelayNs / samplingPeriodNs) > MAX_EVENT_COUNT))) {
427         SEN_HILOGE("sensorDesc is invalid or maxReportDelayNs exceeded the maximum value");
428         return ERR_NO_INIT;
429     }
430     return ERR_OK;
431 }
432 
EnableSensor(const SensorDescriptionIPC & SensorDescriptionIPC,int64_t samplingPeriodNs,int64_t maxReportDelayNs)433 ErrCode SensorService::EnableSensor(const SensorDescriptionIPC &SensorDescriptionIPC, int64_t samplingPeriodNs,
434     int64_t maxReportDelayNs)
435 {
436     CALL_LOG_ENTER;
437     SensorDescription sensorDesc {
438         .deviceId = SensorDescriptionIPC.deviceId,
439         .sensorType = SensorDescriptionIPC.sensorType,
440         .sensorId = SensorDescriptionIPC.sensorId,
441         .location = SensorDescriptionIPC.location
442     };
443     ErrCode checkResult = CheckAuthAndParameter(sensorDesc, samplingPeriodNs, maxReportDelayNs);
444     if (checkResult != ERR_OK) {
445         return checkResult;
446     }
447     int32_t pid = GetCallingPid();
448     std::lock_guard<std::mutex> serviceLock(serviceLock_);
449     if (clientInfo_.GetSensorState(sensorDesc)) {
450         return SensorReportEvent(sensorDesc, samplingPeriodNs, maxReportDelayNs, pid);
451     }
452     auto ret = SaveSubscriber(sensorDesc, samplingPeriodNs, maxReportDelayNs);
453     if (ret != ERR_OK) {
454         SEN_HILOGE("SaveSubscriber failed");
455         clientInfo_.RemoveSubscriber(sensorDesc, GetCallingPid());
456         return ret;
457     }
458 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
459     ret = sensorHdiConnection_.EnableSensor(sensorDesc);
460     if (ret != ERR_OK) {
461         SEN_HILOGE("EnableSensor failed");
462         clientInfo_.RemoveSubscriber(sensorDesc, GetCallingPid());
463         return ENABLE_SENSOR_ERR;
464     }
465 #endif // HDF_DRIVERS_INTERFACE_SENSOR
466     SetCritical();
467     if ((!g_isRegister) && (RegisterPermCallback(sensorDesc.sensorType))) {
468         g_isRegister = true;
469     }
470     ReportSensorSysEvent(sensorDesc.sensorType, true, pid, samplingPeriodNs, maxReportDelayNs);
471     if (isReportActiveInfo_) {
472         ReportActiveInfo(sensorDesc, pid);
473     }
474     PrintSensorData::GetInstance().ResetHdiCounter(sensorDesc.sensorType);
475     return ret;
476 }
477 
SensorReportEvent(const SensorDescription & sensorDesc,int64_t samplingPeriodNs,int64_t maxReportDelayNs,int32_t pid)478 ErrCode SensorService::SensorReportEvent(const SensorDescription &sensorDesc, int64_t samplingPeriodNs,
479     int64_t maxReportDelayNs, int32_t pid)
480 {
481     SEN_HILOGW("Sensor has been enabled already");
482     auto ret = SaveSubscriber(sensorDesc, samplingPeriodNs, maxReportDelayNs);
483     if (ret != ERR_OK) {
484         SEN_HILOGE("SaveSubscriber failed");
485         return ret;
486     }
487     ReportSensorSysEvent(sensorDesc.sensorType, true, pid, samplingPeriodNs, maxReportDelayNs);
488     if (ret != ERR_OK) {
489         SEN_HILOGE("ret:%{public}d", ret);
490     }
491     ReportOnChangeData(sensorDesc);
492     if (isReportActiveInfo_) {
493         ReportActiveInfo(sensorDesc, pid);
494     }
495     PrintSensorData::GetInstance().ResetHdiCounter(sensorDesc.sensorType);
496     SEN_HILOGI("Done, sensorTypeId:%{public}d", sensorDesc.sensorType);
497     return ERR_OK;
498 }
499 
DisableSensor(const SensorDescription & sensorDesc,int32_t pid)500 ErrCode SensorService::DisableSensor(const SensorDescription &sensorDesc, int32_t pid)
501 {
502     CALL_LOG_ENTER;
503     if ((!CheckSensorId(sensorDesc)) && (!clientInfo_.GetSensorState(sensorDesc))) {
504         SEN_HILOGE("sensorDesc is invalid");
505         return ERR_NO_INIT;
506     }
507     if (pid < 0) {
508         SEN_HILOGE("pid is invalid, pid:%{public}d", pid);
509         return CLIENT_PID_INVALID_ERR;
510     }
511     ReportSensorSysEvent(sensorDesc.sensorType, false, pid);
512     std::lock_guard<std::mutex> serviceLock(serviceLock_);
513     if (sensorManager_.IsOtherClientUsingSensor(sensorDesc, pid)) {
514         SEN_HILOGW("Other client is using this sensor now, can't disable");
515         return ERR_OK;
516     }
517 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
518     if (sensorHdiConnection_.DisableSensor(sensorDesc) != ERR_OK) {
519         if (CheckSensorId(sensorDesc)) {
520             SEN_HILOGE("DisableSensor is failed");
521             return DISABLE_SENSOR_ERR;
522         }
523         SEN_HILOGW("DisableSensor is failed, deviceIndex:%{public}d, sensorType:%{public}d, sensorId:%{public}d",
524             sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId);
525     }
526 #endif // HDF_DRIVERS_INTERFACE_SENSOR
527     PrintSensorData::GetInstance().ResetHdiTimes(sensorDesc.sensorType);
528     int32_t uid = clientInfo_.GetUidByPid(pid);
529     clientInfo_.DestroyCmd(uid);
530     clientInfo_.ClearDataQueue(sensorDesc);
531     int32_t ret = sensorManager_.AfterDisableSensor(sensorDesc);
532 #ifdef MEMMGR_ENABLE
533     if (isMemoryMgrServiceActive_ && !clientInfo_.IsSubscribe() && isCritical_) {
534         if (Memory::MemMgrClient::GetInstance().SetCritical(getpid(), false, SENSOR_SERVICE_ABILITY_ID) != ERR_OK) {
535             SEN_HILOGE("SetCritical failed");
536             return ret;
537         }
538         isCritical_ = false;
539     }
540 #endif // MEMMGR_ENABLE
541     return ret;
542 }
543 
DisableSensor(const SensorDescriptionIPC & SensorDescriptionIPC)544 ErrCode SensorService::DisableSensor(const SensorDescriptionIPC &SensorDescriptionIPC)
545 {
546     CALL_LOG_ENTER;
547     SensorDescription sensorDesc {
548         .deviceId = SensorDescriptionIPC.deviceId,
549         .sensorType = SensorDescriptionIPC.sensorType,
550         .sensorId = SensorDescriptionIPC.sensorId,
551         .location = SensorDescriptionIPC.location
552     };
553     if ((sensorDesc.sensorType == SENSOR_TYPE_ID_COLOR || sensorDesc.sensorType == SENSOR_TYPE_ID_SAR ||
554             sensorDesc.sensorType > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE) &&
555         !IsSystemCalling()) {
556         SEN_HILOGE("Permission check failed. A non-system application uses the system API");
557         return NON_SYSTEM_API;
558     }
559     PermissionUtil &permissionUtil = PermissionUtil::GetInstance();
560     int32_t ret = permissionUtil.CheckSensorPermission(GetCallingTokenID(), sensorDesc.sensorType);
561     if (ret != PERMISSION_GRANTED) {
562 #ifdef HIVIEWDFX_HISYSEVENT_ENABLE
563         HiSysEventWrite(HiSysEvent::Domain::SENSOR, "VERIFY_ACCESS_TOKEN_FAIL", HiSysEvent::EventType::SECURITY,
564             "PKG_NAME", "SensorDisableInner", "ERROR_CODE", ret);
565 #endif // HIVIEWDFX_HISYSEVENT_ENABLE
566         SEN_HILOGE("sensorType:%{public}d grant failed, ret:%{public}d", sensorDesc.sensorType, ret);
567         return PERMISSION_DENIED;
568     }
569     return DisableSensor(sensorDesc, GetCallingPid());
570 }
571 
GetSensorList(std::vector<Sensor> & sensorList)572 ErrCode SensorService::GetSensorList(std::vector<Sensor> &sensorList)
573 {
574     std::vector<Sensor> sensors = GetSensorList();
575     int32_t sensorCount = static_cast<int32_t>(sensors.size());
576     if (sensorCount > MAX_SENSOR_COUNT) {
577         SEN_HILOGD("SensorCount:%{public}u", sensorCount);
578         sensorCount = MAX_SENSOR_COUNT;
579     }
580     for (int32_t i = 0; i < sensorCount; ++i) {
581         sensorList.push_back(sensors[i]);
582     }
583     return ERR_OK;
584 }
585 
GetSensorListByDevice(int32_t deviceId,std::vector<Sensor> & singleDevSensors)586 ErrCode SensorService::GetSensorListByDevice(int32_t deviceId, std::vector<Sensor> &singleDevSensors)
587 {
588     CALL_LOG_ENTER;
589     {
590         std::lock_guard<std::mutex> sensorLock(sensorsMutex_);
591         for (const auto& sensor : sensors_) {
592             if (sensor.GetDeviceId() == deviceId) {
593                 SEN_HILOGD("Sensor found: id is %{public}d", deviceId);
594                 singleDevSensors.push_back(sensor);
595             }
596         }
597     }
598 
599     if (singleDevSensors.empty()) {
600         std::vector<Sensor> sensors = GetSensorListByDevice(deviceId);
601         int32_t sensorCount = static_cast<int32_t>(sensors.size());
602         for (int32_t i = 0; i < sensorCount; ++i) {
603             singleDevSensors.push_back(sensors[i]);
604         }
605     }
606     return ERR_OK;
607 }
608 
GetSensorListByDevice(int32_t deviceId)609 std::vector<Sensor> SensorService::GetSensorListByDevice(int32_t deviceId)
610 {
611     CALL_LOG_ENTER;
612     std::lock_guard<std::mutex> sensorLock(sensorsMutex_);
613 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
614     std::vector<Sensor> singleDevSensors;
615     int32_t ret = sensorHdiConnection_.GetSensorListByDevice(deviceId, singleDevSensors);
616     if (ret != 0 || singleDevSensors.empty()) {
617         SEN_HILOGW("GetSensorListByDevice is failed or empty");
618         return sensors_;
619     }
620     for (const auto& newSensor : singleDevSensors) {
621         bool found = false;
622         for (auto& oldSensor : sensors_) {
623             if (oldSensor.GetSensorId() == newSensor.GetSensorId() &&
624                 oldSensor.GetDeviceId() == newSensor.GetDeviceId() &&
625                 oldSensor.GetSensorTypeId() == newSensor.GetSensorTypeId()) {
626                 SEN_HILOGD("Sensor found in sensorList_");
627                 found = true;
628                 break;
629             }
630         }
631         if (!found) {
632             SEN_HILOGD("Sensor not found in sensorList_");
633                 found = true;
634             sensors_.push_back(newSensor);
635         }
636     }
637 #endif // HDF_DRIVERS_INTERFACE_SENSOR
638 
639     std::lock_guard<std::mutex> sensorMapLock(sensorMapMutex_);
640     for (const auto &it : sensors_) {
641         auto iter = sensorMap_.find({it.GetDeviceId(), it.GetSensorTypeId(), it.GetSensorId(), it.GetLocation()});
642         if (iter != sensorMap_.end()) {
643             iter->second = it;
644         } else {
645             sensorMap_.insert(std::pair<SensorDescription, Sensor>(
646                 {it.GetDeviceId(), it.GetSensorTypeId(), it.GetSensorId(), it.GetLocation()}, it));
647             if (sensorDataProcesser_ != nullptr) {
648                 sensorDataProcesser_->UpdateSensorMap(sensorMap_);
649             }
650         }
651     }
652     return singleDevSensors;
653 }
654 
GetSensorList()655 std::vector<Sensor> SensorService::GetSensorList()
656 {
657     std::lock_guard<std::mutex> sensorLock(sensorsMutex_);
658 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
659     int32_t ret = sensorHdiConnection_.GetSensorList(sensors_);
660     if (ret != 0) {
661         SEN_HILOGE("GetSensorList is failed");
662         return sensors_;
663     }
664 #endif // HDF_DRIVERS_INTERFACE_SENSOR
665     for (const auto &it : sensors_) {
666         std::lock_guard<std::mutex> sensorMapLock(sensorMapMutex_);
667         sensorMap_.insert(std::pair<SensorDescription, Sensor>({
668             it.GetDeviceId(), it.GetSensorTypeId(), it.GetSensorId(), it.GetLocation()}, it));
669     }
670     return sensors_;
671 }
672 
TransferDataChannel(int32_t sendFd,const sptr<IRemoteObject> & sensorClient)673 ErrCode SensorService::TransferDataChannel(int32_t sendFd, const sptr<IRemoteObject> &sensorClient)
674 {
675     SEN_HILOGI("In");
676     sptr<SensorBasicDataChannel> sensorBasicDataChannel = new (std::nothrow) SensorBasicDataChannel();
677     CHKPR(sensorBasicDataChannel, OBJECT_NULL);
678     auto ret = sensorBasicDataChannel->CreateSensorBasicChannelBySendFd(sendFd);
679     if (ret != ERR_OK) {
680         SEN_HILOGE("CreateSensorBasicChannelBySendFd ret:%{public}d", ret);
681         return OBJECT_NULL;
682     }
683     CHKPR(sensorBasicDataChannel, ERR_NO_INIT);
684     auto pid = GetCallingPid();
685     auto uid = GetCallingUid();
686     auto callerToken = GetCallingTokenID();
687     if (!clientInfo_.UpdateAppThreadInfo(pid, uid, callerToken)) {
688         SEN_HILOGE("UpdateUid is failed");
689         return UPDATE_UID_ERR;
690     }
691     if (!clientInfo_.UpdateSensorChannel(pid, sensorBasicDataChannel)) {
692         SEN_HILOGE("UpdateSensorChannel is failed");
693         return UPDATE_SENSOR_CHANNEL_ERR;
694     }
695     sensorBasicDataChannel->SetSensorStatus(true);
696     std::string packageName("");
697     sensorManager_.GetPackageName(callerToken, packageName, isAccessTokenServiceActive_);
698     SEN_HILOGI("Calling packageName:%{public}s", packageName.c_str());
699     sensorBasicDataChannel->SetPackageName(packageName);
700     RegisterClientDeathRecipient(sensorClient, pid);
701     SEN_HILOGI("Done");
702     return ERR_OK;
703 }
704 
DestroySensorChannel(const sptr<IRemoteObject> & sensorClient)705 ErrCode SensorService::DestroySensorChannel(const sptr<IRemoteObject> &sensorClient)
706 {
707     CALL_LOG_ENTER;
708     const int32_t clientPid = GetCallingPid();
709     if (clientPid < 0) {
710         SEN_HILOGE("clientPid is invalid, clientPid:%{public}d", clientPid);
711         return CLIENT_PID_INVALID_ERR;
712     }
713     std::lock_guard<std::mutex> serviceLock(serviceLock_);
714     bool destroyRet = clientInfo_.DestroySensorChannel(clientPid);
715     if (!destroyRet) {
716         SEN_HILOGE("DestroySensorChannel is failed");
717         return DESTROY_SENSOR_CHANNEL_ERR;
718     }
719     clientInfo_.DestroyCmd(GetCallingUid());
720     UnregisterClientDeathRecipient(sensorClient);
721     return ERR_OK;
722 }
723 
ProcessDeathObserver(const wptr<IRemoteObject> & object)724 void SensorService::ProcessDeathObserver(const wptr<IRemoteObject> &object)
725 {
726     CALL_LOG_ENTER;
727     sptr<IRemoteObject> client = object.promote();
728     CHKPV(client);
729     int32_t pid = clientInfo_.FindClientPid(client);
730     if (pid == INVALID_PID) {
731         SEN_HILOGE("pid is invalid");
732         return;
733     }
734     POWER_POLICY.DeleteDeathPidSensorInfo(pid);
735     SEN_HILOGI("pid is %{public}d", pid);
736     std::vector<SensorDescription> activeSensors = clientInfo_.GetSensorIdByPid(pid);
737     for (size_t i = 0; i < activeSensors.size(); ++i) {
738         int32_t ret = DisableSensor(activeSensors[i], pid);
739         if (ret != ERR_OK) {
740             SEN_HILOGE("DisableSensor failed, ret:%{public}d", ret);
741         }
742     }
743     DelSession(pid);
744     clientInfo_.DelActiveInfoCBPid(pid);
745     clientInfo_.DestroySensorChannel(pid);
746     clientInfo_.DestroyClientPid(client);
747     clientInfo_.DestroyCmd(clientInfo_.GetUidByPid(pid));
748 }
749 
RegisterClientDeathRecipient(sptr<IRemoteObject> sensorClient,int32_t pid)750 void SensorService::RegisterClientDeathRecipient(sptr<IRemoteObject> sensorClient, int32_t pid)
751 {
752     CALL_LOG_ENTER;
753     CHKPV(sensorClient);
754     std::lock_guard<std::mutex> clientDeathObserverLock(clientDeathObserverMutex_);
755     if (clientDeathObserver_ == nullptr) {
756         clientDeathObserver_ = new (std::nothrow) DeathRecipientTemplate(*const_cast<SensorService *>(this));
757         CHKPV(clientDeathObserver_);
758     }
759     sensorClient->AddDeathRecipient(clientDeathObserver_);
760     clientInfo_.SaveClientPid(sensorClient, pid);
761 }
762 
UnregisterClientDeathRecipient(sptr<IRemoteObject> sensorClient)763 void SensorService::UnregisterClientDeathRecipient(sptr<IRemoteObject> sensorClient)
764 {
765     CALL_LOG_ENTER;
766     CHKPV(sensorClient);
767     int32_t pid = clientInfo_.FindClientPid(sensorClient);
768     if (pid == INVALID_PID) {
769         SEN_HILOGE("Pid is invalid");
770         return;
771     }
772     if (!clientInfo_.CallingService(pid)) {
773         SEN_HILOGD("Can't unregister client death recipient");
774         return;
775     }
776     std::lock_guard<std::mutex> clientDeathObserverLock(clientDeathObserverMutex_);
777     sensorClient->RemoveDeathRecipient(clientDeathObserver_);
778     clientInfo_.DestroyClientPid(sensorClient);
779 }
780 
Dump(int32_t fd,const std::vector<std::u16string> & args)781 int32_t SensorService::Dump(int32_t fd, const std::vector<std::u16string> &args)
782 {
783     CALL_LOG_ENTER;
784     if (fd < 0) {
785         SEN_HILOGE("Invalid fd");
786         return DUMP_PARAM_ERR;
787     }
788     SensorDump &sensorDump = SensorDump::GetInstance();
789     if (args.empty()) {
790         SEN_HILOGE("Param cannot be empty");
791         dprintf(fd, "param cannot be empty\n");
792         sensorDump.DumpHelp(fd);
793         return DUMP_PARAM_ERR;
794     }
795     std::vector<std::string> argList = { "" };
796     std::transform(args.begin(), args.end(), std::back_inserter(argList),
797         [](const std::u16string &arg) {
798         return Str16ToStr8(arg);
799     });
800     std::lock_guard<std::mutex> sensorLock(sensorsMutex_);
801     sensorDump.ParseCommand(fd, argList, sensors_, clientInfo_);
802     return ERR_OK;
803 }
804 
SuspendSensors(int32_t pid)805 ErrCode SensorService::SuspendSensors(int32_t pid)
806 {
807     CALL_LOG_ENTER;
808     PermissionUtil &permissionUtil = PermissionUtil::GetInstance();
809     if (!permissionUtil.IsNativeToken(GetCallingTokenID())) {
810         SEN_HILOGE("TokenType is not TOKEN_NATIVE");
811         return PERMISSION_DENIED;
812     }
813     int32_t ret = permissionUtil.CheckManageSensorPermission(GetCallingTokenID());
814     if (ret != PERMISSION_GRANTED) {
815         SEN_HILOGE("Check manage sensor permission failed, ret:%{public}d", ret);
816         return PERMISSION_DENIED;
817     }
818     if (pid < 0) {
819         SEN_HILOGE("Pid is invalid");
820         return CLIENT_PID_INVALID_ERR;
821     }
822     return POWER_POLICY.SuspendSensors(pid);
823 }
824 
ResumeSensors(int32_t pid)825 ErrCode SensorService::ResumeSensors(int32_t pid)
826 {
827     CALL_LOG_ENTER;
828     PermissionUtil &permissionUtil = PermissionUtil::GetInstance();
829     if (!permissionUtil.IsNativeToken(GetCallingTokenID())) {
830         SEN_HILOGE("TokenType is not TOKEN_NATIVE");
831         return PERMISSION_DENIED;
832     }
833     int32_t ret = permissionUtil.CheckManageSensorPermission(GetCallingTokenID());
834     if (ret != PERMISSION_GRANTED) {
835         SEN_HILOGE("Check manage sensor permission failed, ret:%{public}d", ret);
836         return PERMISSION_DENIED;
837     }
838     if (pid < 0) {
839         SEN_HILOGE("Pid is invalid");
840         return CLIENT_PID_INVALID_ERR;
841     }
842     return POWER_POLICY.ResumeSensors(pid);
843 }
844 
GetActiveInfoList(int32_t pid,std::vector<ActiveInfo> & activeInfoList)845 ErrCode SensorService::GetActiveInfoList(int32_t pid, std::vector<ActiveInfo> &activeInfoList)
846 {
847     CALL_LOG_ENTER;
848     PermissionUtil &permissionUtil = PermissionUtil::GetInstance();
849     if (!permissionUtil.IsNativeToken(GetCallingTokenID())) {
850         SEN_HILOGE("TokenType is not TOKEN_NATIVE");
851         return PERMISSION_DENIED;
852     }
853     if (pid < 0) {
854         SEN_HILOGE("Pid is invalid");
855         return CLIENT_PID_INVALID_ERR;
856     }
857     activeInfoList = POWER_POLICY.GetActiveInfoList(pid);
858     uint32_t activeInfoCount = static_cast<uint32_t>(activeInfoList.size());
859     if (activeInfoCount > MAX_SENSOR_COUNT) {
860         SEN_HILOGD("ActiveInfoCount:%{public}u", activeInfoCount);
861         activeInfoList.erase(activeInfoList.begin() + MAX_SENSOR_COUNT, activeInfoList.begin() + activeInfoCount - 1);
862     }
863     return ERR_OK;
864 }
865 
CreateSocketChannel(const sptr<IRemoteObject> & sensorClient,int32_t & clientFd)866 ErrCode SensorService::CreateSocketChannel(const sptr<IRemoteObject> &sensorClient, int32_t &clientFd)
867 {
868     CALL_LOG_ENTER;
869     CHKPR(sensorClient, INVALID_POINTER);
870     PermissionUtil &permissionUtil = PermissionUtil::GetInstance();
871     if (!permissionUtil.IsNativeToken(GetCallingTokenID())) {
872         SEN_HILOGE("TokenType is not TOKEN_NATIVE");
873         return PERMISSION_DENIED;
874     }
875     int32_t serverFd = -1;
876     int32_t ret = AddSocketPairInfo(GetCallingUid(), GetCallingPid(),
877         AccessTokenKit::GetTokenTypeFlag(GetCallingTokenID()),
878         serverFd, std::ref(clientFd));
879     if (ret != ERR_OK) {
880         SEN_HILOGE("Add socket pair info failed, ret:%{public}d", ret);
881         return ret;
882     }
883     RegisterClientDeathRecipient(sensorClient, GetCallingPid());
884     return ERR_OK;
885 }
886 
DestroySocketChannel(const sptr<IRemoteObject> & sensorClient)887 ErrCode SensorService::DestroySocketChannel(const sptr<IRemoteObject> &sensorClient)
888 {
889     CALL_LOG_ENTER;
890     CHKPR(sensorClient, INVALID_POINTER);
891     PermissionUtil &permissionUtil = PermissionUtil::GetInstance();
892     if (!permissionUtil.IsNativeToken(GetCallingTokenID())) {
893         SEN_HILOGE("TokenType is not TOKEN_NATIVE");
894         return PERMISSION_DENIED;
895     }
896     DelSession(GetCallingPid());
897     UnregisterClientDeathRecipient(sensorClient);
898     return ERR_OK;
899 }
900 
EnableActiveInfoCB()901 ErrCode SensorService::EnableActiveInfoCB()
902 {
903     CALL_LOG_ENTER;
904     PermissionUtil &permissionUtil = PermissionUtil::GetInstance();
905     if (!permissionUtil.IsNativeToken(GetCallingTokenID())) {
906         SEN_HILOGE("TokenType is not TOKEN_NATIVE");
907         return PERMISSION_DENIED;
908     }
909     isReportActiveInfo_ = true;
910     return clientInfo_.AddActiveInfoCBPid(GetCallingPid());
911 }
912 
DisableActiveInfoCB()913 ErrCode SensorService::DisableActiveInfoCB()
914 {
915     CALL_LOG_ENTER;
916     PermissionUtil &permissionUtil = PermissionUtil::GetInstance();
917     if (!permissionUtil.IsNativeToken(GetCallingTokenID())) {
918         SEN_HILOGE("TokenType is not TOKEN_NATIVE");
919         return PERMISSION_DENIED;
920     }
921     isReportActiveInfo_ = false;
922     return clientInfo_.DelActiveInfoCBPid(GetCallingPid());
923 }
924 
ResetSensors()925 ErrCode SensorService::ResetSensors()
926 {
927     CALL_LOG_ENTER;
928     PermissionUtil &permissionUtil = PermissionUtil::GetInstance();
929     if (!permissionUtil.IsNativeToken(GetCallingTokenID())) {
930         SEN_HILOGE("TokenType is not TOKEN_NATIVE");
931         return PERMISSION_DENIED;
932     }
933     int32_t ret = permissionUtil.CheckManageSensorPermission(GetCallingTokenID());
934     if (ret != PERMISSION_GRANTED) {
935         SEN_HILOGE("Check manage sensor permission failed, ret:%{public}d", ret);
936         return PERMISSION_DENIED;
937     }
938     return POWER_POLICY.ResetSensors();
939 }
940 
ReportActiveInfo(const SensorDescription & sensorDesc,int32_t pid)941 void SensorService::ReportActiveInfo(const SensorDescription &sensorDesc, int32_t pid)
942 {
943     CALL_LOG_ENTER;
944     std::vector<SessionPtr> sessionList;
945     auto pidList = clientInfo_.GetActiveInfoCBPid();
946     for (const auto &pid : pidList) {
947         auto sess = GetSessionByPid(pid);
948         if (sess != nullptr) {
949             sessionList.push_back(sess);
950         }
951     }
952     SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorDesc, pid);
953     ActiveInfo activeInfo(pid, sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId,
954         sensorInfo.GetSamplingPeriodNs(), sensorInfo.GetMaxReportDelayNs());
955     POWER_POLICY.ReportActiveInfo(activeInfo, sessionList);
956 }
957 
RegisterPermCallback(int32_t sensorType)958 bool SensorService::RegisterPermCallback(int32_t sensorType)
959 {
960     CALL_LOG_ENTER;
961     if ((sensorType != SENSOR_TYPE_ID_PEDOMETER) && (sensorType != SENSOR_TYPE_ID_PEDOMETER_DETECTION) &&
962         (sensorType != SENSOR_TYPE_ID_HEART_RATE)) {
963         SEN_HILOGD("No need listen for the sensor permission changes");
964         return false;
965     }
966     Security::AccessToken::PermStateChangeScope scope = {
967         .permList = { ACTIVITY_MOTION_PERMISSION, READ_HEALTH_DATA_PERMISSION }
968     };
969     permStateChangeCb_ = std::make_shared<PermStateChangeCb>(scope, this);
970     int32_t ret = Security::AccessToken::AccessTokenKit::RegisterPermStateChangeCallback(permStateChangeCb_);
971     if (ret != ERR_OK) {
972         SEN_HILOGE("RegisterPermStateChangeCallback fail");
973         return false;
974     }
975     return true;
976 }
977 
UnregisterPermCallback()978 void SensorService::UnregisterPermCallback()
979 {
980     CALL_LOG_ENTER;
981     CHKPV(permStateChangeCb_);
982     int32_t ret = Security::AccessToken::AccessTokenKit::UnRegisterPermStateChangeCallback(permStateChangeCb_);
983     if (ret != ERR_OK) {
984         SEN_HILOGE("UnregisterPermStateChangeCallback fail");
985         return;
986     }
987     g_isRegister = false;
988 }
989 
PermStateChangeCallback(Security::AccessToken::PermStateChangeInfo & result)990 void SensorService::PermStateChangeCb::PermStateChangeCallback(Security::AccessToken::PermStateChangeInfo &result)
991 {
992     CALL_LOG_ENTER;
993     CHKPV(server_);
994     server_->clientInfo_.ChangeSensorPerm(result.tokenID, result.permissionName,
995         (result.permStateChangeType != 0));
996 }
997 
SetDeviceStatus(uint32_t deviceStatus)998 ErrCode SensorService::SetDeviceStatus(uint32_t deviceStatus)
999 {
1000     SEN_HILOGI("SetDeviceStatus in, deviceStatus:%{public}d", deviceStatus);
1001     PermissionUtil &permissionUtil = PermissionUtil::GetInstance();
1002     if (!permissionUtil.IsNativeToken(GetCallingTokenID())) {
1003         SEN_HILOGE("TokenType is not TOKEN_NATIVE");
1004         return PERMISSION_DENIED;
1005     }
1006     clientInfo_.SetDeviceStatus(deviceStatus);
1007     return ERR_OK;
1008 }
1009 
TransferClientRemoteObject(const sptr<IRemoteObject> & sensorClient)1010 ErrCode SensorService::TransferClientRemoteObject(const sptr<IRemoteObject> &sensorClient)
1011 {
1012     CALL_LOG_ENTER;
1013     clientInfo_.SaveSensorClient(sensorClient);
1014     return ERR_OK;
1015 }
1016 
DestroyClientRemoteObject(const sptr<IRemoteObject> & sensorClient)1017 ErrCode SensorService::DestroyClientRemoteObject(const sptr<IRemoteObject> &sensorClient)
1018 {
1019     CALL_LOG_ENTER;
1020     clientInfo_.DestroySensorClient(sensorClient);
1021     return ERR_OK;
1022 }
1023 
ReportPlugEventCallback(const SensorPlugInfo & info)1024 void SensorService::ReportPlugEventCallback(const SensorPlugInfo &info)
1025 {
1026     CALL_LOG_ENTER;
1027     if (info.status == SENSOR_ONLINE) {
1028         auto it = sensorMap_.find({info.deviceSensorInfo.deviceId, info.deviceSensorInfo.sensorType,
1029             info.deviceSensorInfo.sensorId, info.deviceSensorInfo.location});
1030         if (it == sensorMap_.end()) {
1031             GetSensorListByDevice(info.deviceSensorInfo.deviceId);
1032         }
1033     } else {
1034         if (!sensorHdiConnection_.PlugEraseSensorData(info)) {
1035             SEN_HILOGW("sensorHdiConnection Cache update failure");
1036         }
1037         std::lock_guard<std::mutex> sensorMapLock(sensorMapMutex_);
1038         auto it = std::find_if(sensors_.begin(), sensors_.end(), [&](const Sensor& sensor) {
1039             return sensor.GetDeviceId() == info.deviceSensorInfo.deviceId &&
1040                 sensor.GetSensorTypeId() == info.deviceSensorInfo.sensorType &&
1041                 sensor.GetSensorId() == info.deviceSensorInfo.sensorId;
1042         });
1043         if (it != sensors_.end()) {
1044             sensors_.erase(it);
1045         }
1046         auto iter = sensorMap_.find({info.deviceSensorInfo.deviceId, info.deviceSensorInfo.sensorType,
1047             info.deviceSensorInfo.sensorId, info.deviceSensorInfo.location});
1048         if (iter != sensorMap_.end()) {
1049             sensorMap_.erase(iter);
1050         }
1051     }
1052     struct timeval curTime;
1053     curTime.tv_sec = 0;
1054     curTime.tv_usec = 0;
1055     gettimeofday(&curTime, NULL);
1056     const SensorPlugData sensorPlugData = {
1057         .deviceId = info.deviceSensorInfo.deviceId,
1058         .sensorTypeId = info.deviceSensorInfo.sensorType,
1059         .sensorId = info.deviceSensorInfo.sensorId,
1060         .location = info.deviceSensorInfo.location,
1061         .deviceName = info.deviceName,
1062         .status = info.status,
1063         .reserved = info.reserved,
1064         .timestamp = static_cast<int64_t>(curTime.tv_sec * 1000 + curTime.tv_usec / 1000) //1000:milliSecond
1065     };
1066     clientInfo_.SendMsgToClient(sensorPlugData);
1067 }
1068 
SetCritical()1069 void SensorService::SetCritical()
1070 {
1071     CALL_LOG_ENTER;
1072     if (!isMemoryMgrServiceActive_) {
1073         SEN_HILOGE("Memory manager service is inactive");
1074         return;
1075     }
1076 #ifdef MEMMGR_ENABLE
1077     if (!isCritical_) {
1078         if (Memory::MemMgrClient::GetInstance().SetCritical(getpid(), true, SENSOR_SERVICE_ABILITY_ID) != ERR_OK) {
1079             SEN_HILOGE("setCritical failed");
1080         } else {
1081             isCritical_ = true;
1082         }
1083     }
1084 #endif // MEMMGR_ENABLE
1085 }
1086 } // namespace Sensors
1087 } // namespace OHOS
1088