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