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 <cinttypes>
19 #include <string_ex.h>
20 #include <sys/socket.h>
21 #include <unistd.h>
22 
23 #ifdef HIVIEWDFX_HISYSEVENT_ENABLE
24 #include "hisysevent.h"
25 #endif // HIVIEWDFX_HISYSEVENT_ENABLE
26 #include "iservice_registry.h"
27 #ifdef MEMMGR_ENABLE
28 #include "mem_mgr_client.h"
29 #endif // MEMMGR_ENABLE
30 #include "permission_util.h"
31 
32 #include "print_sensor_data.h"
33 #include "securec.h"
34 #include "sensor.h"
35 #include "sensor_dump.h"
36 #include "sensor_errors.h"
37 #include "system_ability_definition.h"
38 
39 #undef LOG_TAG
40 #define LOG_TAG "SensorService"
41 
42 namespace OHOS {
43 namespace Sensors {
44 using namespace OHOS::HiviewDFX;
45 namespace {
46 auto g_sensorService = SensorDelayedSpSingleton<SensorService>::GetInstance();
47 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(g_sensorService.GetRefPtr());
48 constexpr int32_t INVALID_PID = -1;
49 constexpr int64_t MAX_EVENT_COUNT = 1000;
50 std::atomic_bool g_isRegister = false;
51 } // namespace
52 
SensorService()53 SensorService::SensorService()
54     : SystemAbility(SENSOR_SERVICE_ABILITY_ID, true), state_(SensorServiceState::STATE_STOPPED)
55 {
56     SEN_HILOGD("Add SystemAbility");
57 }
58 
~SensorService()59 SensorService::~SensorService() {}
60 
OnDump()61 void SensorService::OnDump()
62 {
63     SEN_HILOGI("OnDump");
64 }
65 
OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)66 void SensorService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
67 {
68     SEN_HILOGI("OnAddSystemAbility systemAbilityId:%{public}d", systemAbilityId);
69 #ifdef MEMMGR_ENABLE
70     if (systemAbilityId == MEMORY_MANAGER_SA_ID) {
71         Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(),
72             PROCESS_TYPE_SA, PROCESS_STATUS_STARTED, SENSOR_SERVICE_ABILITY_ID);
73     }
74 #endif // MEMMGR_ENABLE
75 }
76 
OnStart()77 void SensorService::OnStart()
78 {
79     CALL_LOG_ENTER;
80     if (state_ == SensorServiceState::STATE_RUNNING) {
81         SEN_HILOGW("SensorService has already started");
82         return;
83     }
84 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
85     if (!InitInterface()) {
86         SEN_HILOGE("Init interface error");
87     }
88     if (!InitDataCallback()) {
89         SEN_HILOGE("Init data callback error");
90     }
91     if (!InitSensorList()) {
92         SEN_HILOGE("Init sensor list error");
93     }
94     sensorDataProcesser_ = new (std::nothrow) SensorDataProcesser(sensorMap_);
95     CHKPV(sensorDataProcesser_);
96 #endif // HDF_DRIVERS_INTERFACE_SENSOR
97     if (!InitSensorPolicy()) {
98         SEN_HILOGE("Init sensor policy error");
99     }
100 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
101     sensorManager_.InitSensorMap(sensorMap_, sensorDataProcesser_, reportDataCallback_);
102 #else
103     sensorManager_.InitSensorMap(sensorMap_);
104 #endif // HDF_DRIVERS_INTERFACE_SENSOR
105     if (!SystemAbility::Publish(SensorDelayedSpSingleton<SensorService>::GetInstance())) {
106         SEN_HILOGE("Publish SensorService error");
107         return;
108     }
109     state_ = SensorServiceState::STATE_RUNNING;
110 #ifdef MEMMGR_ENABLE
111     AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
112 #endif // MEMMGR_ENABLE
113 }
114 
115 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
InitInterface()116 bool SensorService::InitInterface()
117 {
118     auto ret = sensorHdiConnection_.ConnectHdi();
119     if (ret != ERR_OK) {
120         SEN_HILOGE("Connect hdi failed");
121         return false;
122     }
123     return true;
124 }
125 
InitDataCallback()126 bool SensorService::InitDataCallback()
127 {
128     reportDataCallback_ = new (std::nothrow) ReportDataCallback();
129     CHKPF(reportDataCallback_);
130     ReportDataCb cb = &ReportDataCallback::ReportEventCallback;
131     auto ret = sensorHdiConnection_.RegisterDataReport(cb, reportDataCallback_);
132     if (ret != ERR_OK) {
133         SEN_HILOGE("RegisterDataReport failed");
134         return false;
135     }
136     return true;
137 }
138 
InitSensorList()139 bool SensorService::InitSensorList()
140 {
141     std::lock_guard<std::mutex> sensorLock(sensorsMutex_);
142     int32_t ret = sensorHdiConnection_.GetSensorList(sensors_);
143     if (ret != 0) {
144         SEN_HILOGE("GetSensorList is failed");
145         return false;
146     }
147     {
148         std::lock_guard<std::mutex> sensorMapLock(sensorMapMutex_);
149         for (const auto &it : sensors_) {
150             if (!(sensorMap_.insert(std::make_pair(it.GetSensorId(), it)).second)) {
151                 SEN_HILOGW("sensorMap_ insert failed");
152             }
153         }
154     }
155     return true;
156 }
157 #endif // HDF_DRIVERS_INTERFACE_SENSOR
158 
InitSensorPolicy()159 bool SensorService::InitSensorPolicy()
160 {
161     return true;
162 }
163 
OnStop()164 void SensorService::OnStop()
165 {
166     CALL_LOG_ENTER;
167     if (state_ == SensorServiceState::STATE_STOPPED) {
168         SEN_HILOGW("Already stopped");
169         return;
170     }
171     state_ = SensorServiceState::STATE_STOPPED;
172 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
173     int32_t ret = sensorHdiConnection_.DestroyHdiConnection();
174     if (ret != ERR_OK) {
175         SEN_HILOGE("Destroy hdi connect fail");
176     }
177 #endif // HDF_DRIVERS_INTERFACE_SENSOR
178     UnregisterPermCallback();
179 #ifdef MEMMGR_ENABLE
180     Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), PROCESS_TYPE_SA, PROCESS_STATUS_DIED,
181         SENSOR_SERVICE_ABILITY_ID);
182 #endif // MEMMGR_ENABLE
183 }
184 
ReportSensorSysEvent(int32_t sensorId, bool enable, int32_t pid)185 void SensorService::ReportSensorSysEvent(int32_t sensorId, bool enable, int32_t pid)
186 {
187     std::string packageName("");
188     AccessTokenID tokenId = clientInfo_.GetTokenIdByPid(pid);
189     sensorManager_.GetPackageName(tokenId, packageName);
190 #ifdef HIVIEWDFX_HISYSEVENT_ENABLE
191     const int logLevel = 4;
192     int32_t uid = clientInfo_.GetUidByPid(pid);
193 #endif // HIVIEWDFX_HISYSEVENT_ENABLE
194     if (enable) {
195 #ifdef HIVIEWDFX_HISYSEVENT_ENABLE
196         HiSysEventWrite(HiSysEvent::Domain::SENSOR, "ENABLE_SENSOR", HiSysEvent::EventType::STATISTIC,
197             "LEVEL", logLevel, "UID", uid, "PKG_NAME", packageName, "TYPE", sensorId);
198 #endif // HIVIEWDFX_HISYSEVENT_ENABLE
199         SEN_HILOGI("PackageName:%{public}s open the sensor, sensorId:%{public}d", packageName.c_str(), sensorId);
200     } else {
201 #ifdef HIVIEWDFX_HISYSEVENT_ENABLE
202         HiSysEventWrite(HiSysEvent::Domain::SENSOR, "DISABLE_SENSOR", HiSysEvent::EventType::STATISTIC,
203             "LEVEL", logLevel, "UID", uid, "PKG_NAME", packageName, "TYPE", sensorId);
204 #endif // HIVIEWDFX_HISYSEVENT_ENABLE
205         SEN_HILOGI("PackageName:%{public}s close the sensor, sensorId:%{public}d", packageName.c_str(), sensorId);
206     }
207 }
208 
ReportOnChangeData(int32_t sensorId)209 void SensorService::ReportOnChangeData(int32_t sensorId)
210 {
211     std::lock_guard<std::mutex> sensorMapLock(sensorMapMutex_);
212     auto it = sensorMap_.find(sensorId);
213     if (it == sensorMap_.end()) {
214         SEN_HILOGE("sensorId is invalid");
215         return;
216     }
217     if ((SENSOR_ON_CHANGE & it->second.GetFlags()) != SENSOR_ON_CHANGE) {
218         SEN_HILOGW("The data has not changed , no need to report");
219         return;
220     }
221     SensorData sensorData;
222     auto ret = clientInfo_.GetStoreEvent(sensorId, sensorData);
223     if (ret != ERR_OK) {
224         SEN_HILOGE("There is no data to be reported");
225         return;
226     }
227     sptr<SensorBasicDataChannel> channel = clientInfo_.GetSensorChannelByPid(GetCallingPid());
228     CHKPV(channel);
229     auto sendRet = channel->SendData(&sensorData, sizeof(sensorData));
230     if (sendRet != ERR_OK) {
231         SEN_HILOGE("Send data failed");
232         return;
233     }
234 }
235 
SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs)236 ErrCode SensorService::SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs)
237 {
238     if (!sensorManager_.SaveSubscriber(sensorId, GetCallingPid(), samplingPeriodNs, maxReportDelayNs)) {
239         SEN_HILOGE("SaveSubscriber failed");
240         return UPDATE_SENSOR_INFO_ERR;
241     }
242 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
243     sensorManager_.StartDataReportThread();
244     SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, GetCallingPid());
245     if (!sensorManager_.SetBestSensorParams(sensorId,
246         sensorInfo.GetSamplingPeriodNs(), sensorInfo.GetMaxReportDelayNs())) {
247         SEN_HILOGE("SetBestSensorParams failed");
248         clientInfo_.RemoveSubscriber(sensorId, GetCallingPid());
249         return SET_SENSOR_CONFIG_ERR;
250     }
251 #endif // HDF_DRIVERS_INTERFACE_SENSOR
252     return ERR_OK;
253 }
254 
CheckSensorId(int32_t sensorId)255 bool SensorService::CheckSensorId(int32_t sensorId)
256 {
257     std::lock_guard<std::mutex> sensorMapLock(sensorMapMutex_);
258     auto it = sensorMap_.find(sensorId);
259     if (it == sensorMap_.end()) {
260         SEN_HILOGE("Invalid sensorId, sensorId:%{public}d", sensorId);
261         return false;
262     }
263     return true;
264 }
265 
CheckParameter(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs)266 bool SensorService::CheckParameter(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs)
267 {
268     if ((!CheckSensorId(sensorId)) ||
269         ((samplingPeriodNs != 0L) && ((maxReportDelayNs / samplingPeriodNs) > MAX_EVENT_COUNT))) {
270         SEN_HILOGE("sensorId is invalid or maxReportDelayNs exceeded the maximum value");
271         return false;
272     }
273     return true;
274 }
275 
EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs)276 ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs)
277 {
278     CALL_LOG_ENTER;
279     if (!CheckParameter(sensorId, samplingPeriodNs, maxReportDelayNs)) {
280         SEN_HILOGE("sensorId, samplingPeriodNs or maxReportDelayNs is invalid");
281         return ERR_NO_INIT;
282     }
283     int32_t pid = GetCallingPid();
284     std::lock_guard<std::mutex> serviceLock(serviceLock_);
285     if (clientInfo_.GetSensorState(sensorId)) {
286         SEN_HILOGW("Sensor has been enabled already");
287         auto ret = SaveSubscriber(sensorId, samplingPeriodNs, maxReportDelayNs);
288         if (ret != ERR_OK) {
289             SEN_HILOGE("SaveSubscriber failed");
290             return ret;
291         }
292         ReportSensorSysEvent(sensorId, true, pid);
293         if (ret != ERR_OK) {
294             SEN_HILOGE("ret:%{public}d", ret);
295         }
296         ReportOnChangeData(sensorId);
297         if (isReportActiveInfo_) {
298             ReportActiveInfo(sensorId, pid);
299         }
300         PrintSensorData::GetInstance().ResetHdiCounter(sensorId);
301         return ERR_OK;
302     }
303     auto ret = SaveSubscriber(sensorId, samplingPeriodNs, maxReportDelayNs);
304     if (ret != ERR_OK) {
305         SEN_HILOGE("SaveSubscriber failed");
306         clientInfo_.RemoveSubscriber(sensorId, GetCallingPid());
307         return ret;
308     }
309 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
310     ret = sensorHdiConnection_.EnableSensor(sensorId);
311     if (ret != ERR_OK) {
312         SEN_HILOGE("EnableSensor failed");
313         clientInfo_.RemoveSubscriber(sensorId, GetCallingPid());
314         return ENABLE_SENSOR_ERR;
315     }
316 #endif // HDF_DRIVERS_INTERFACE_SENSOR
317     if ((!g_isRegister) && (RegisterPermCallback(sensorId))) {
318         g_isRegister = true;
319     }
320     ReportSensorSysEvent(sensorId, true, pid);
321     if (isReportActiveInfo_) {
322         ReportActiveInfo(sensorId, pid);
323     }
324     PrintSensorData::GetInstance().ResetHdiCounter(sensorId);
325     return ret;
326 }
327 
DisableSensor(int32_t sensorId, int32_t pid)328 ErrCode SensorService::DisableSensor(int32_t sensorId, int32_t pid)
329 {
330     CALL_LOG_ENTER;
331     if (!CheckSensorId(sensorId)) {
332         SEN_HILOGE("sensorId is invalid");
333         return ERR_NO_INIT;
334     }
335     if (pid < 0) {
336         SEN_HILOGE("pid is invalid, pid:%{public}d", pid);
337         return CLIENT_PID_INVALID_ERR;
338     }
339     ReportSensorSysEvent(sensorId, false, pid);
340     std::lock_guard<std::mutex> serviceLock(serviceLock_);
341     if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) {
342         SEN_HILOGW("Other client is using this sensor now, can't disable");
343         return ERR_OK;
344     }
345 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
346     if (sensorHdiConnection_.DisableSensor(sensorId) != ERR_OK) {
347         SEN_HILOGE("DisableSensor is failed");
348         return DISABLE_SENSOR_ERR;
349     }
350 #endif // HDF_DRIVERS_INTERFACE_SENSOR
351     int32_t uid = clientInfo_.GetUidByPid(pid);
352     clientInfo_.DestroyCmd(uid);
353     clientInfo_.ClearDataQueue(sensorId);
354     return sensorManager_.AfterDisableSensor(sensorId);
355 }
356 
DisableSensor(int32_t sensorId)357 ErrCode SensorService::DisableSensor(int32_t sensorId)
358 {
359     CALL_LOG_ENTER;
360     return DisableSensor(sensorId, GetCallingPid());
361 }
362 
GetSensorList()363 std::vector<Sensor> SensorService::GetSensorList()
364 {
365     std::lock_guard<std::mutex> sensorLock(sensorsMutex_);
366 #ifdef HDF_DRIVERS_INTERFACE_SENSOR
367     int32_t ret = sensorHdiConnection_.GetSensorList(sensors_);
368     if (ret != 0) {
369         SEN_HILOGE("GetSensorList is failed");
370         return sensors_;
371     }
372 #endif // HDF_DRIVERS_INTERFACE_SENSOR
373     for (const auto &it : sensors_) {
374         std::lock_guard<std::mutex> sensorMapLock(sensorMapMutex_);
375         sensorMap_.insert(std::make_pair(it.GetSensorId(), it));
376     }
377     return sensors_;
378 }
379 
TransferDataChannel(const sptr<SensorBasicDataChannel> &sensorBasicDataChannel, const sptr<IRemoteObject> &sensorClient)380 ErrCode SensorService::TransferDataChannel(const sptr<SensorBasicDataChannel> &sensorBasicDataChannel,
381                                            const sptr<IRemoteObject> &sensorClient)
382 {
383     CHKPR(sensorBasicDataChannel, ERR_NO_INIT);
384     auto pid = GetCallingPid();
385     auto uid = GetCallingUid();
386     auto callerToken = GetCallingTokenID();
387     if (!clientInfo_.UpdateAppThreadInfo(pid, uid, callerToken)) {
388         SEN_HILOGE("UpdateUid is failed");
389         return UPDATE_UID_ERR;
390     }
391     if (!clientInfo_.UpdateSensorChannel(pid, sensorBasicDataChannel)) {
392         SEN_HILOGE("UpdateSensorChannel is failed");
393         return UPDATE_SENSOR_CHANNEL_ERR;
394     }
395     sensorBasicDataChannel->SetSensorStatus(true);
396     RegisterClientDeathRecipient(sensorClient, pid);
397     return ERR_OK;
398 }
399 
DestroySensorChannel(sptr<IRemoteObject> sensorClient)400 ErrCode SensorService::DestroySensorChannel(sptr<IRemoteObject> sensorClient)
401 {
402     CALL_LOG_ENTER;
403     const int32_t clientPid = GetCallingPid();
404     if (clientPid < 0) {
405         SEN_HILOGE("clientPid is invalid, clientPid:%{public}d", clientPid);
406         return CLIENT_PID_INVALID_ERR;
407     }
408     std::lock_guard<std::mutex> serviceLock(serviceLock_);
409     bool destroyRet = clientInfo_.DestroySensorChannel(clientPid);
410     if (!destroyRet) {
411         SEN_HILOGE("DestroySensorChannel is failed");
412         return DESTROY_SENSOR_CHANNEL_ERR;
413     }
414     clientInfo_.DestroyCmd(GetCallingUid());
415     UnregisterClientDeathRecipient(sensorClient);
416     return ERR_OK;
417 }
418 
ProcessDeathObserver(const wptr<IRemoteObject> &object)419 void SensorService::ProcessDeathObserver(const wptr<IRemoteObject> &object)
420 {
421     CALL_LOG_ENTER;
422     sptr<IRemoteObject> client = object.promote();
423     CHKPV(client);
424     int32_t pid = clientInfo_.FindClientPid(client);
425     if (pid == INVALID_PID) {
426         SEN_HILOGE("pid is invalid");
427         return;
428     }
429     SEN_HILOGI("pid is %{public}d", pid);
430     std::vector<int32_t> activeSensors = clientInfo_.GetSensorIdByPid(pid);
431     for (size_t i = 0; i < activeSensors.size(); ++i) {
432         int32_t ret = DisableSensor(activeSensors[i], pid);
433         if (ret != ERR_OK) {
434             SEN_HILOGE("DisableSensor failed, ret:%{public}d", ret);
435         }
436     }
437     DelSession(pid);
438     clientInfo_.DelActiveInfoCBPid(pid);
439     clientInfo_.DestroySensorChannel(pid);
440     clientInfo_.DestroyClientPid(client);
441     clientInfo_.DestroyCmd(clientInfo_.GetUidByPid(pid));
442 }
443 
RegisterClientDeathRecipient(sptr<IRemoteObject> sensorClient, int32_t pid)444 void SensorService::RegisterClientDeathRecipient(sptr<IRemoteObject> sensorClient, int32_t pid)
445 {
446     CALL_LOG_ENTER;
447     CHKPV(sensorClient);
448     std::lock_guard<std::mutex> clientDeathObserverLock(clientDeathObserverMutex_);
449     if (clientDeathObserver_ == nullptr) {
450         clientDeathObserver_ = new (std::nothrow) DeathRecipientTemplate(*const_cast<SensorService *>(this));
451         CHKPV(clientDeathObserver_);
452     }
453     sensorClient->AddDeathRecipient(clientDeathObserver_);
454     clientInfo_.SaveClientPid(sensorClient, pid);
455 }
456 
UnregisterClientDeathRecipient(sptr<IRemoteObject> sensorClient)457 void SensorService::UnregisterClientDeathRecipient(sptr<IRemoteObject> sensorClient)
458 {
459     CALL_LOG_ENTER;
460     CHKPV(sensorClient);
461     int32_t pid = clientInfo_.FindClientPid(sensorClient);
462     if (pid == INVALID_PID) {
463         SEN_HILOGE("Pid is invalid");
464         return;
465     }
466     if (!clientInfo_.CallingService(pid)) {
467         SEN_HILOGD("Can't unregister client death recipient");
468         return;
469     }
470     std::lock_guard<std::mutex> clientDeathObserverLock(clientDeathObserverMutex_);
471     sensorClient->RemoveDeathRecipient(clientDeathObserver_);
472     clientInfo_.DestroyClientPid(sensorClient);
473 }
474 
Dump(int32_t fd, const std::vector<std::u16string> &args)475 int32_t SensorService::Dump(int32_t fd, const std::vector<std::u16string> &args)
476 {
477     CALL_LOG_ENTER;
478     if (fd < 0) {
479         SEN_HILOGE("Invalid fd");
480         return DUMP_PARAM_ERR;
481     }
482     SensorDump &sensorDump = SensorDump::GetInstance();
483     if (args.empty()) {
484         SEN_HILOGE("Param cannot be empty");
485         dprintf(fd, "param cannot be empty\n");
486         sensorDump.DumpHelp(fd);
487         return DUMP_PARAM_ERR;
488     }
489     std::vector<std::string> argList = { "" };
490     std::transform(args.begin(), args.end(), std::back_inserter(argList),
491         [](const std::u16string &arg) {
492         return Str16ToStr8(arg);
493     });
494     sensorDump.ParseCommand(fd, argList, sensors_, clientInfo_);
495     return ERR_OK;
496 }
497 
SuspendSensors(int32_t pid)498 ErrCode SensorService::SuspendSensors(int32_t pid)
499 {
500     CALL_LOG_ENTER;
501     if (pid < 0) {
502         SEN_HILOGE("Pid is invalid");
503         return CLIENT_PID_INVALID_ERR;
504     }
505     return POWER_POLICY.SuspendSensors(pid);
506 }
507 
ResumeSensors(int32_t pid)508 ErrCode SensorService::ResumeSensors(int32_t pid)
509 {
510     CALL_LOG_ENTER;
511     if (pid < 0) {
512         SEN_HILOGE("Pid is invalid");
513         return CLIENT_PID_INVALID_ERR;
514     }
515     return POWER_POLICY.ResumeSensors(pid);
516 }
517 
GetActiveInfoList(int32_t pid, std::vector<ActiveInfo> &activeInfoList)518 ErrCode SensorService::GetActiveInfoList(int32_t pid, std::vector<ActiveInfo> &activeInfoList)
519 {
520     CALL_LOG_ENTER;
521     if (pid < 0) {
522         SEN_HILOGE("Pid is invalid");
523         return CLIENT_PID_INVALID_ERR;
524     }
525     activeInfoList = POWER_POLICY.GetActiveInfoList(pid);
526     return ERR_OK;
527 }
528 
CreateSocketChannel(sptr<IRemoteObject> sensorClient, int32_t &clientFd)529 ErrCode SensorService::CreateSocketChannel(sptr<IRemoteObject> sensorClient, int32_t &clientFd)
530 {
531     CALL_LOG_ENTER;
532     CHKPR(sensorClient, INVALID_POINTER);
533     int32_t serverFd = -1;
534     int32_t ret = AddSocketPairInfo(GetCallingUid(), GetCallingPid(),
535         AccessTokenKit::GetTokenTypeFlag(GetCallingTokenID()),
536         serverFd, std::ref(clientFd));
537     if (ret != ERR_OK) {
538         SEN_HILOGE("Add socket pair info failed, ret:%{public}d", ret);
539         return ret;
540     }
541     RegisterClientDeathRecipient(sensorClient, GetCallingPid());
542     return ERR_OK;
543 }
544 
DestroySocketChannel(sptr<IRemoteObject> sensorClient)545 ErrCode SensorService::DestroySocketChannel(sptr<IRemoteObject> sensorClient)
546 {
547     CALL_LOG_ENTER;
548     CHKPR(sensorClient, INVALID_POINTER);
549     DelSession(GetCallingPid());
550     UnregisterClientDeathRecipient(sensorClient);
551     return ERR_OK;
552 }
553 
EnableActiveInfoCB()554 ErrCode SensorService::EnableActiveInfoCB()
555 {
556     CALL_LOG_ENTER;
557     isReportActiveInfo_ = true;
558     return clientInfo_.AddActiveInfoCBPid(GetCallingPid());
559 }
560 
DisableActiveInfoCB()561 ErrCode SensorService::DisableActiveInfoCB()
562 {
563     CALL_LOG_ENTER;
564     isReportActiveInfo_ = false;
565     return clientInfo_.DelActiveInfoCBPid(GetCallingPid());
566 }
567 
ResetSensors()568 ErrCode SensorService::ResetSensors()
569 {
570     CALL_LOG_ENTER;
571     return POWER_POLICY.ResetSensors();
572 }
573 
ReportActiveInfo(int32_t sensorId, int32_t pid)574 void SensorService::ReportActiveInfo(int32_t sensorId, int32_t pid)
575 {
576     CALL_LOG_ENTER;
577     std::vector<SessionPtr> sessionList;
578     auto pidList = clientInfo_.GetActiveInfoCBPid();
579     for (const auto &pid : pidList) {
580         auto sess = GetSessionByPid(pid);
581         if (sess != nullptr) {
582             sessionList.push_back(sess);
583         }
584     }
585     SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid);
586     ActiveInfo activeInfo(pid, sensorId, sensorInfo.GetSamplingPeriodNs(),
587         sensorInfo.GetMaxReportDelayNs());
588     POWER_POLICY.ReportActiveInfo(activeInfo, sessionList);
589 }
590 
RegisterPermCallback(int32_t sensorId)591 bool SensorService::RegisterPermCallback(int32_t sensorId)
592 {
593     CALL_LOG_ENTER;
594     if ((sensorId != SENSOR_TYPE_ID_PEDOMETER) && (sensorId != SENSOR_TYPE_ID_PEDOMETER_DETECTION) &&
595         (sensorId != SENSOR_TYPE_ID_HEART_RATE)) {
596         SEN_HILOGD("No need listen for the sensor permission changes");
597         return false;
598     }
599     Security::AccessToken::PermStateChangeScope scope = {
600         .permList = { ACTIVITY_MOTION_PERMISSION, READ_HEALTH_DATA_PERMISSION }
601     };
602     permStateChangeCb_ = std::make_shared<PermStateChangeCb>(scope, this);
603     int32_t ret = Security::AccessToken::AccessTokenKit::RegisterPermStateChangeCallback(permStateChangeCb_);
604     if (ret != ERR_OK) {
605         SEN_HILOGE("RegisterPermStateChangeCallback fail");
606         return false;
607     }
608     return true;
609 }
610 
UnregisterPermCallback()611 void SensorService::UnregisterPermCallback()
612 {
613     CALL_LOG_ENTER;
614     CHKPV(permStateChangeCb_);
615     int32_t ret = Security::AccessToken::AccessTokenKit::UnRegisterPermStateChangeCallback(permStateChangeCb_);
616     if (ret != ERR_OK) {
617         SEN_HILOGE("UnregisterPermStateChangeCallback fail");
618         return;
619     }
620     g_isRegister = false;
621 }
622 
PermStateChangeCallback(Security::AccessToken::PermStateChangeInfo &result)623 void SensorService::PermStateChangeCb::PermStateChangeCallback(Security::AccessToken::PermStateChangeInfo &result)
624 {
625     CALL_LOG_ENTER;
626     CHKPV(server_);
627     server_->clientInfo_.ChangeSensorPerm(result.tokenID, result.permissionName,
628         (result.permStateChangeType != 0));
629 }
630 } // namespace Sensors
631 } // namespace OHOS
632