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