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_client.h"
17 
18 #include <sys/socket.h>
19 #include <thread>
20 #include <unistd.h>
21 #include <vector>
22 
23 #include "death_recipient_template.h"
24 #include "hisysevent.h"
25 #include "hitrace_meter.h"
26 #include "ipc_skeleton.h"
27 #include "sensor_agent_proxy.h"
28 #include "sensor_errors.h"
29 #include "sensor_service_proxy.h"
30 #include "system_ability_definition.h"
31 #include "rust_binding.h"
32 
33 #undef LOG_TAG
34 #define LOG_TAG "SensorServiceClient"
35 
36 namespace OHOS {
37 namespace Sensors {
38 using namespace OHOS::HiviewDFX;
39 
40 namespace {
41 constexpr int32_t GET_SERVICE_MAX_COUNT = 3;
42 constexpr uint32_t WAIT_MS = 200;
43 #ifdef OHOS_BUILD_ENABLE_RUST
44 extern "C" {
45     void ReadClientPackets(RustStreamBuffer *, OHOS::Sensors::SensorServiceClient *,
46         void(*)(OHOS::Sensors::SensorServiceClient *, RustNetPacket *));
OnPacket(SensorServiceClient * object,RustNetPacket * cPkt)47     void OnPacket(SensorServiceClient *object, RustNetPacket *cPkt)
48     {
49         NetPacket pkt(cPkt->msgId);
50         pkt.streamBufferPtr_.reset(cPkt->streamBuffer);
51         object->HandleNetPacke(pkt);
52     }
53 }
54 #endif // OHOS_BUILD_ENABLE_RUST
55 }  // namespace
56 
~SensorServiceClient()57 SensorServiceClient::~SensorServiceClient()
58 {
59     if (sensorServer_ != nullptr && serviceDeathObserver_ != nullptr) {
60         auto remoteObject = sensorServer_->AsObject();
61         if (remoteObject != nullptr) {
62             remoteObject->RemoveDeathRecipient(serviceDeathObserver_);
63         }
64     }
65     Disconnect();
66 }
67 
InitServiceClient()68 int32_t SensorServiceClient::InitServiceClient()
69 {
70     CALL_LOG_ENTER;
71     std::lock_guard<std::mutex> clientLock(clientMutex_);
72     if (sensorServer_ != nullptr) {
73         SEN_HILOGD("Already init");
74         return ERR_OK;
75     }
76     if (sensorClientStub_ == nullptr) {
77         sensorClientStub_ = new (std::nothrow) SensorClientStub();
78     }
79     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
80     CHKPR(systemAbilityManager, SENSOR_NATIVE_SAM_ERR);
81     int32_t retry = 0;
82     while (retry < GET_SERVICE_MAX_COUNT) {
83         auto object = systemAbilityManager->GetSystemAbility(SENSOR_SERVICE_ABILITY_ID);
84         CHKPR(object, SENSOR_NATIVE_GET_SERVICE_ERR);
85         sensorServer_ = iface_cast<ISensorService>(object);
86         if (sensorServer_ != nullptr) {
87             SEN_HILOGD("Get service success, retry:%{public}d", retry);
88             serviceDeathObserver_ = new (std::nothrow) DeathRecipientTemplate(*const_cast<SensorServiceClient *>(this));
89             CHKPR(serviceDeathObserver_, SENSOR_NATIVE_GET_SERVICE_ERR);
90             auto remoteObject = sensorServer_->AsObject();
91             CHKPR(remoteObject, SENSOR_NATIVE_GET_SERVICE_ERR);
92             remoteObject->AddDeathRecipient(serviceDeathObserver_);
93             sensorList_ = sensorServer_->GetSensorList();
94             return ERR_OK;
95         }
96         SEN_HILOGW("Get service failed, retry:%{public}d", retry);
97         std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_MS));
98         retry++;
99     }
100     HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "SERVICE_EXCEPTION",
101         HiSysEvent::EventType::FAULT, "PKG_NAME", "InitServiceClient", "ERROR_CODE", SENSOR_NATIVE_GET_SERVICE_ERR);
102     SEN_HILOGE("Get service failed");
103     return SENSOR_NATIVE_GET_SERVICE_ERR;
104 }
105 
IsValid(int32_t sensorId)106 bool SensorServiceClient::IsValid(int32_t sensorId)
107 {
108     int32_t ret = InitServiceClient();
109     if (ret != ERR_OK) {
110         SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
111     }
112     std::lock_guard<std::mutex> clientLock(clientMutex_);
113     if (sensorList_.empty()) {
114         SEN_HILOGE("sensorList_ cannot be empty");
115         return false;
116     }
117     for (auto &sensor : sensorList_) {
118         if (sensor.GetSensorId() == sensorId) {
119             return true;
120         }
121     }
122     return false;
123 }
124 
EnableSensor(int32_t sensorId,int64_t samplingPeriod,int64_t maxReportDelay)125 int32_t SensorServiceClient::EnableSensor(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay)
126 {
127     CALL_LOG_ENTER;
128     int32_t ret = InitServiceClient();
129     if (ret != ERR_OK) {
130         SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
131         return ret;
132     }
133     std::lock_guard<std::mutex> clientLock(clientMutex_);
134     CHKPR(sensorServer_, ERROR);
135     StartTrace(HITRACE_TAG_SENSORS, "EnableSensor");
136     ret = sensorServer_->EnableSensor(sensorId, samplingPeriod, maxReportDelay);
137     FinishTrace(HITRACE_TAG_SENSORS);
138     if (ret == ERR_OK) {
139         UpdateSensorInfoMap(sensorId, samplingPeriod, maxReportDelay);
140     }
141     return ret;
142 }
143 
DisableSensor(int32_t sensorId)144 int32_t SensorServiceClient::DisableSensor(int32_t sensorId)
145 {
146     CALL_LOG_ENTER;
147     int32_t ret = InitServiceClient();
148     if (ret != ERR_OK) {
149         SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
150         return ret;
151     }
152     std::lock_guard<std::mutex> clientLock(clientMutex_);
153     CHKPR(sensorServer_, ERROR);
154     StartTrace(HITRACE_TAG_SENSORS, "DisableSensor");
155     ret = sensorServer_->DisableSensor(sensorId);
156     FinishTrace(HITRACE_TAG_SENSORS);
157     if (ret == ERR_OK) {
158         DeleteSensorInfoItem(sensorId);
159     }
160     return ret;
161 }
162 
GetSensorList()163 std::vector<Sensor> SensorServiceClient::GetSensorList()
164 {
165     CALL_LOG_ENTER;
166     int32_t ret = InitServiceClient();
167     if (ret != ERR_OK) {
168         SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
169         return {};
170     }
171     std::lock_guard<std::mutex> clientLock(clientMutex_);
172     if (sensorList_.empty()) {
173         SEN_HILOGE("sensorList_ cannot be empty");
174     }
175     return sensorList_;
176 }
177 
TransferDataChannel(sptr<SensorDataChannel> sensorDataChannel)178 int32_t SensorServiceClient::TransferDataChannel(sptr<SensorDataChannel> sensorDataChannel)
179 {
180     SEN_HILOGI("In");
181     CHKPR(sensorDataChannel, INVALID_POINTER);
182     {
183         std::lock_guard<std::mutex> channelLock(channelMutex_);
184         dataChannel_ = sensorDataChannel;
185     }
186     int32_t ret = InitServiceClient();
187     if (ret != ERR_OK) {
188         SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
189         return ret;
190     }
191     std::lock_guard<std::mutex> clientLock(clientMutex_);
192     CHKPR(sensorServer_, ERROR);
193     StartTrace(HITRACE_TAG_SENSORS, "TransferDataChannel");
194     CHKPR(sensorClientStub_, INVALID_POINTER);
195     auto remoteObject = sensorClientStub_->AsObject();
196     CHKPR(remoteObject, INVALID_POINTER);
197     ret = sensorServer_->TransferDataChannel(sensorDataChannel, remoteObject);
198     FinishTrace(HITRACE_TAG_SENSORS);
199     SEN_HILOGI("Done");
200     return ret;
201 }
202 
DestroyDataChannel()203 int32_t SensorServiceClient::DestroyDataChannel()
204 {
205     CALL_LOG_ENTER;
206     int32_t ret = InitServiceClient();
207     if (ret != ERR_OK) {
208         SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
209         return ret;
210     }
211     std::lock_guard<std::mutex> clientLock(clientMutex_);
212     CHKPR(sensorServer_, ERROR);
213     StartTrace(HITRACE_TAG_SENSORS, "DestroyDataChannel");
214     CHKPR(sensorClientStub_, INVALID_POINTER);
215     auto remoteObject = sensorClientStub_->AsObject();
216     CHKPR(remoteObject, INVALID_POINTER);
217     ret = sensorServer_->DestroySensorChannel(remoteObject);
218     FinishTrace(HITRACE_TAG_SENSORS);
219     return ret;
220 }
221 
ReenableSensor()222 void SensorServiceClient::ReenableSensor()
223 {
224     CALL_LOG_ENTER;
225     std::lock_guard<std::mutex> mapLock(mapMutex_);
226     for (const auto &it : sensorInfoMap_) {
227         std::lock_guard<std::mutex> clientLock(clientMutex_);
228         if (sensorServer_ != nullptr) {
229             sensorServer_->EnableSensor(it.first, it.second.GetSamplingPeriodNs(), it.second.GetMaxReportDelayNs());
230         }
231     }
232     if (!isConnected_) {
233         SEN_HILOGD("Previous socket channel status is false, not need retry creat socket channel");
234         return;
235     }
236     Disconnect();
237     CreateSocketChannel();
238 }
239 
ProcessDeathObserver(const wptr<IRemoteObject> & object)240 void SensorServiceClient::ProcessDeathObserver(const wptr<IRemoteObject> &object)
241 {
242     CALL_LOG_ENTER;
243     {
244         std::lock_guard<std::mutex> channelLock(channelMutex_);
245         if (dataChannel_ == nullptr) {
246             SEN_HILOGI("dataChannel_ is nullptr");
247             {
248                 std::lock_guard<std::mutex> clientLock(clientMutex_);
249                 sensorServer_ = nullptr;
250             }
251             if (InitServiceClient() != ERR_OK) {
252                 SEN_HILOGE("InitServiceClient failed");
253                 return;
254             }
255         } else {
256             SEN_HILOGI("dataChannel_ is not nullptr");
257             dataChannel_->DestroySensorDataChannel();
258             dataChannel_->RestoreSensorDataChannel();
259             {
260                 std::lock_guard<std::mutex> clientLock(clientMutex_);
261                 sensorServer_ = nullptr;
262             }
263             if (InitServiceClient() != ERR_OK) {
264                 SEN_HILOGE("InitServiceClient failed");
265                 dataChannel_->DestroySensorDataChannel();
266                 SENSOR_AGENT_IMPL->SetIsChannelCreated(false);
267                 return;
268             }
269             std::lock_guard<std::mutex> clientLock(clientMutex_);
270             if (sensorServer_ != nullptr && sensorClientStub_ != nullptr) {
271                 auto remoteObject = sensorClientStub_->AsObject();
272                 if (remoteObject != nullptr) {
273                     sensorServer_->TransferDataChannel(dataChannel_, remoteObject);
274                 }
275             }
276         }
277     }
278     ReenableSensor();
279 }
280 
UpdateSensorInfoMap(int32_t sensorId,int64_t samplingPeriod,int64_t maxReportDelay)281 void SensorServiceClient::UpdateSensorInfoMap(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay)
282 {
283     SEN_HILOGI("In");
284     SensorBasicInfo sensorInfo;
285     sensorInfo.SetSamplingPeriodNs(samplingPeriod);
286     sensorInfo.SetMaxReportDelayNs(maxReportDelay);
287     sensorInfo.SetSensorState(true);
288     std::lock_guard<std::mutex> mapLock(mapMutex_);
289     sensorInfoMap_[sensorId] = sensorInfo;
290     SEN_HILOGI("Done");
291     return;
292 }
293 
DeleteSensorInfoItem(int32_t sensorId)294 void SensorServiceClient::DeleteSensorInfoItem(int32_t sensorId)
295 {
296     SEN_HILOGI("In");
297     std::lock_guard<std::mutex> mapLock(mapMutex_);
298     auto it = sensorInfoMap_.find(sensorId);
299     if (it != sensorInfoMap_.end()) {
300         sensorInfoMap_.erase(it);
301     }
302     SEN_HILOGI("Done");
303     return;
304 }
305 
SuspendSensors(int32_t pid)306 int32_t SensorServiceClient::SuspendSensors(int32_t pid)
307 {
308     CALL_LOG_ENTER;
309     int32_t ret = InitServiceClient();
310     if (ret != ERR_OK) {
311         SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
312         return ret;
313     }
314     std::lock_guard<std::mutex> clientLock(clientMutex_);
315     CHKPR(sensorServer_, ERROR);
316     StartTrace(HITRACE_TAG_SENSORS, "SuspendSensors");
317     ret = sensorServer_->SuspendSensors(pid);
318     FinishTrace(HITRACE_TAG_SENSORS);
319     return ret;
320 }
321 
ResumeSensors(int32_t pid)322 int32_t SensorServiceClient::ResumeSensors(int32_t pid)
323 {
324     CALL_LOG_ENTER;
325     int32_t ret = InitServiceClient();
326     if (ret != ERR_OK) {
327         SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
328         return ret;
329     }
330     std::lock_guard<std::mutex> clientLock(clientMutex_);
331     CHKPR(sensorServer_, ERROR);
332     StartTrace(HITRACE_TAG_SENSORS, "ResumeSensors");
333     ret = sensorServer_->ResumeSensors(pid);
334     FinishTrace(HITRACE_TAG_SENSORS);
335     return ret;
336 }
337 
GetActiveInfoList(int32_t pid,std::vector<ActiveInfo> & activeInfoList)338 int32_t SensorServiceClient::GetActiveInfoList(int32_t pid, std::vector<ActiveInfo> &activeInfoList)
339 {
340     CALL_LOG_ENTER;
341     int32_t ret = InitServiceClient();
342     if (ret != ERR_OK) {
343         SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
344         return ret;
345     }
346     std::lock_guard<std::mutex> clientLock(clientMutex_);
347     CHKPR(sensorServer_, ERROR);
348     StartTrace(HITRACE_TAG_SENSORS, "GetActiveInfoList");
349     ret = sensorServer_->GetActiveInfoList(pid, activeInfoList);
350     FinishTrace(HITRACE_TAG_SENSORS);
351     return ret;
352 }
353 
Register(SensorActiveInfoCB callback,sptr<SensorDataChannel> sensorDataChannel)354 int32_t SensorServiceClient::Register(SensorActiveInfoCB callback, sptr<SensorDataChannel> sensorDataChannel)
355 {
356     CALL_LOG_ENTER;
357     if (!isConnected_) {
358         CHKPR(sensorDataChannel, INVALID_POINTER);
359         {
360             std::lock_guard<std::mutex> channelLock(channelMutex_);
361             dataChannel_ = sensorDataChannel;
362         }
363         int32_t ret = CreateSocketChannel();
364         if (ret != ERR_OK) {
365             SEN_HILOGE("Register sensor active info callback failed, ret:%{public}d", ret);
366             return ret;
367         }
368     }
369     std::lock_guard<std::mutex> activeInfoCBLock(activeInfoCBMutex_);
370     activeInfoCBSet_.insert(callback);
371     return ERR_OK;
372 }
373 
Unregister(SensorActiveInfoCB callback)374 int32_t SensorServiceClient::Unregister(SensorActiveInfoCB callback)
375 {
376     CALL_LOG_ENTER;
377     {
378         std::lock_guard<std::mutex> activeInfoCBLock(activeInfoCBMutex_);
379         activeInfoCBSet_.erase(callback);
380         if (!activeInfoCBSet_.empty()) {
381             return ERR_OK;
382         }
383     }
384     int32_t ret = InitServiceClient();
385     if (ret != ERR_OK) {
386         SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
387         return ret;
388     }
389     std::lock_guard<std::mutex> clientLock(clientMutex_);
390     CHKPR(sensorServer_, ERROR);
391     StartTrace(HITRACE_TAG_SENSORS, "DisableActiveInfoCB");
392     ret = sensorServer_->DisableActiveInfoCB();
393     FinishTrace(HITRACE_TAG_SENSORS);
394     if (ret != ERR_OK) {
395         SEN_HILOGE("Disable active info callback failed, ret:%{public}d", ret);
396         return ret;
397     }
398     Disconnect();
399     StartTrace(HITRACE_TAG_SENSORS, "DestroySocketChannel");
400     CHKPR(sensorClientStub_, INVALID_POINTER);
401     auto remoteObject = sensorClientStub_->AsObject();
402     CHKPR(remoteObject, INVALID_POINTER);
403     ret = sensorServer_->DestroySocketChannel(remoteObject);
404     FinishTrace(HITRACE_TAG_SENSORS);
405     if (ret != ERR_OK) {
406         SEN_HILOGE("Destroy socket channel failed, ret:%{public}d", ret);
407         return ret;
408     }
409     isConnected_ = false;
410     return ERR_OK;
411 }
412 
ResetSensors()413 int32_t SensorServiceClient::ResetSensors()
414 {
415     CALL_LOG_ENTER;
416     int32_t ret = InitServiceClient();
417     if (ret != ERR_OK) {
418         SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
419         return ret;
420     }
421     std::lock_guard<std::mutex> clientLock(clientMutex_);
422     CHKPR(sensorServer_, ERROR);
423     StartTrace(HITRACE_TAG_SENSORS, "ResetSensors");
424     ret = sensorServer_->ResetSensors();
425     FinishTrace(HITRACE_TAG_SENSORS);
426     return ret;
427 }
428 
ReceiveMessage(const char * buf,size_t size)429 void SensorServiceClient::ReceiveMessage(const char *buf, size_t size)
430 {
431     CHKPV(buf);
432     if (size == 0 || size > MAX_PACKET_BUF_SIZE) {
433         SEN_HILOGE("Invalid input param size. size:%{public}zu", size);
434         return;
435     }
436     if (!circBuf_.Write(buf, size)) {
437         SEN_HILOGE("Write data failed. size:%{public}zu", size);
438     }
439 #ifdef OHOS_BUILD_ENABLE_RUST
440     ReadClientPackets(circBuf_.streamBufferPtr_.get(), this, OnPacket);
441 #else
442     OnReadPackets(circBuf_, [this] (NetPacket &pkt) { this->HandleNetPacke(pkt); });
443 #endif // OHOS_BUILD_ENABLE_RUST
444 }
445 
HandleNetPacke(NetPacket & pkt)446 void SensorServiceClient::HandleNetPacke(NetPacket &pkt)
447 {
448     auto id = pkt.GetMsgId();
449     if (id != MessageId::ACTIVE_INFO) {
450         SEN_HILOGE("NetPacke message id is not ACTIVE_INFO");
451         return;
452     }
453     SensorActiveInfo sensorActiveInfo;
454     pkt >> sensorActiveInfo.pid >> sensorActiveInfo.sensorId >> sensorActiveInfo.samplingPeriodNs >>
455         sensorActiveInfo.maxReportDelayNs;
456 #ifdef OHOS_BUILD_ENABLE_RUST
457     if (StreamBufferChkRWError(pkt.streamBufferPtr_.get())) {
458 #else
459     if (pkt.ChkRWError()) {
460 #endif // OHOS_BUILD_ENABLE_RUST
461         SEN_HILOGE("Packet read type failed");
462         return;
463     }
464     std::lock_guard<std::mutex> activeInfoCBLock(activeInfoCBMutex_);
465     for (auto callback : activeInfoCBSet_) {
466         if (callback != nullptr) {
467             callback(sensorActiveInfo);
468         }
469     }
470 }
471 
472 void SensorServiceClient::Disconnect()
473 {
474     CALL_LOG_ENTER;
475     int32_t fd = GetFd();
476     if (fd < 0) {
477         return;
478     }
479     {
480         std::lock_guard<std::mutex> channelLock(channelMutex_);
481         if (dataChannel_ != nullptr) {
482             int32_t ret = dataChannel_->DelFdListener(fd);
483             if (ret != ERR_OK) {
484                 SEN_HILOGE("Delete fd listener failed, fd:%{public}d, ret:%{public}d", fd, ret);
485             }
486         }
487     }
488     Close();
489 }
490 
491 int32_t SensorServiceClient::CreateSocketChannel()
492 {
493     CALL_LOG_ENTER;
494     int32_t ret = InitServiceClient();
495     if (ret != ERR_OK) {
496         SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
497         return ret;
498     }
499     std::lock_guard<std::mutex> clientLock(clientMutex_);
500     CHKPR(sensorServer_, ERROR);
501     int32_t clientFd = -1;
502     StartTrace(HITRACE_TAG_SENSORS, "CreateSocketChannel");
503     CHKPR(sensorClientStub_, INVALID_POINTER);
504     auto remoteObject = sensorClientStub_->AsObject();
505     CHKPR(remoteObject, INVALID_POINTER);
506     ret = sensorServer_->CreateSocketChannel(remoteObject, clientFd);
507     FinishTrace(HITRACE_TAG_SENSORS);
508     if (ret != ERR_OK || clientFd < 0) {
509         Close();
510         SEN_HILOGE("Create socket channel failed, ret:%{public}d", ret);
511         return ret;
512     }
513 #ifdef OHOS_BUILD_ENABLE_RUST
514     StreamSocketSetFd(streamSocketPtr_.get(), clientFd);
515 #else
516     fd_ = clientFd;
517 #endif // OHOS_BUILD_ENABLE_RUST
518     {
519         std::lock_guard<std::mutex> channelLock(channelMutex_);
520         if (dataChannel_->AddFdListener(GetFd(),
521             [this] (const char *buf, size_t size) { this->ReceiveMessage(buf, size); },
522             [this] { this->Disconnect(); })!= ERR_OK) {
523             Close();
524             SEN_HILOGE("Add fd listener failed, fd:%{public}d", GetFd());
525             return ERROR;
526         }
527     }
528     StartTrace(HITRACE_TAG_SENSORS, "EnableActiveInfoCB");
529     ret = sensorServer_->EnableActiveInfoCB();
530     FinishTrace(HITRACE_TAG_SENSORS);
531     if (ret != ERR_OK) {
532         SEN_HILOGE("Enable active info callback failed, ret:%{public}d", ret);
533         Disconnect();
534         return ret;
535     }
536     isConnected_ = true;
537     return ERR_OK;
538 }
539 }  // namespace Sensors
540 }  // namespace OHOS
541