1 /*
2  * Copyright (c) 2021-2024 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 "dcamera_sink_controller.h"
17 
18 #include <securec.h>
19 #include <thread>
20 
21 #include "anonymous_string.h"
22 #include "dcamera_channel_sink_impl.h"
23 #include "dcamera_client.h"
24 #include "dcamera_metadata_setting_cmd.h"
25 #include "dcamera_protocol.h"
26 #include "dcamera_utils_tools.h"
27 
28 #include "dcamera_sink_access_control.h"
29 #include "dcamera_sink_controller_channel_listener.h"
30 #include "dcamera_sink_controller_state_callback.h"
31 #include "dcamera_sink_output.h"
32 #include "dcamera_sink_service_ipc.h"
33 
34 #include "distributed_camera_constants.h"
35 #include "distributed_camera_errno.h"
36 #include "distributed_hardware_log.h"
37 #include "device_security_defines.h"
38 #include "device_security_info.h"
39 #include "idistributed_camera_source.h"
40 #include "ipc_skeleton.h"
41 #include "dcamera_low_latency.h"
42 #include <sys/prctl.h>
43 
44 namespace OHOS {
45 namespace DistributedHardware {
46 const int DEFAULT_DEVICE_SECURITY_LEVEL = -1;
47 const std::string PAGE_SUBTYPE = "camera";
48 
DCameraSinkController(std::shared_ptr<ICameraSinkAccessControl> & accessControl,const sptr<IDCameraSinkCallback> & sinkCallback)49 DCameraSinkController::DCameraSinkController(std::shared_ptr<ICameraSinkAccessControl>& accessControl,
50     const sptr<IDCameraSinkCallback> &sinkCallback)
51     : isInit_(false), sessionState_(DCAMERA_CHANNEL_STATE_DISCONNECTED), accessControl_(accessControl),
52       sinkCallback_(sinkCallback)
53 {
54 }
55 
~DCameraSinkController()56 DCameraSinkController::~DCameraSinkController()
57 {
58     if (isInit_) {
59         UnInit();
60     }
61 }
62 
StartCapture(std::vector<std::shared_ptr<DCameraCaptureInfo>> & captureInfos,int32_t sceneMode)63 int32_t DCameraSinkController::StartCapture(std::vector<std::shared_ptr<DCameraCaptureInfo>>& captureInfos,
64     int32_t sceneMode)
65 {
66     DHLOGI("StartCapture dhId: %{public}s, mode: %{public}d", GetAnonyString(dhId_).c_str(), sceneMode);
67     std::string accessType = "";
68     CHECK_AND_RETURN_RET_LOG(accessControl_ == nullptr, DCAMERA_BAD_VALUE, "accessControl_ is null.");
69     if ((accessControl_->IsSensitiveSrcAccess(SRC_TYPE)) &&
70         (accessControl_->GetAccessControlType(accessType) == DCAMERA_SAME_ACCOUNT)) {
71         int32_t ret = StartCaptureInner(captureInfos);
72         if (ret == DCAMERA_OK) {
73             accessControl_->NotifySensitiveSrc(SRC_TYPE);
74         }
75         return ret;
76     } else {
77         std::shared_ptr<std::string> param = std::make_shared<std::string>("");
78         std::shared_ptr<std::vector<std::shared_ptr<DCameraCaptureInfo>>> infos =
79             std::make_shared<std::vector<std::shared_ptr<DCameraCaptureInfo>>>(captureInfos);
80         CHECK_AND_RETURN_RET_LOG(sinkCotrEventHandler_ == nullptr, DCAMERA_BAD_VALUE, "sinkCotrEventHandler_ is null.");
81         AppExecFwk::InnerEvent::Pointer triggerEvent =
82                 AppExecFwk::InnerEvent::Get(EVENT_FRAME_TRIGGER, param, 0);
83         AppExecFwk::InnerEvent::Pointer authorizationEvent =
84                 AppExecFwk::InnerEvent::Get(EVENT_AUTHORIZATION, infos, 0);
85         sinkCotrEventHandler_->SendEvent(triggerEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
86         sinkCotrEventHandler_->SendEvent(authorizationEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
87     }
88     return DCAMERA_OK;
89 }
90 
StopCapture()91 int32_t DCameraSinkController::StopCapture()
92 {
93     DHLOGI("StopCapture dhId: %{public}s", GetAnonyString(dhId_).c_str());
94     std::lock_guard<std::mutex> autoLock(captureLock_);
95     if (operator_ == nullptr) {
96         return DCAMERA_BAD_VALUE;
97     }
98     int32_t ret = operator_->StopCapture();
99     if (ret != DCAMERA_OK) {
100         DHLOGE("client stop capture failed, dhId: %{public}s, ret: %{public}d",
101                GetAnonyString(dhId_).c_str(), ret);
102         DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_DEVICE_ERROR, std::string("operator stop capture failed."));
103         return ret;
104     }
105     if (output_ == nullptr) {
106         return DCAMERA_BAD_VALUE;
107     }
108     ret = output_->StopCapture();
109     if (ret != DCAMERA_OK) {
110         DHLOGE("output stop capture failed, dhId: %{public}s, ret: %{public}d",
111                GetAnonyString(dhId_).c_str(), ret);
112         DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_DEVICE_ERROR, std::string("output stop capture failed"));
113         return ret;
114     }
115     DHLOGI("StopCapture %{public}s success", GetAnonyString(dhId_).c_str());
116     return DCAMERA_OK;
117 }
118 
ChannelNeg(std::shared_ptr<DCameraChannelInfo> & info)119 int32_t DCameraSinkController::ChannelNeg(std::shared_ptr<DCameraChannelInfo>& info)
120 {
121     DHLOGI("ChannelNeg dhId: %{public}s", GetAnonyString(dhId_).c_str());
122     int32_t ret = output_->OpenChannel(info);
123     if (ret != DCAMERA_OK) {
124         DHLOGE("channel negotiate failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
125         return ret;
126     }
127 
128     DHLOGI("ChannelNeg %{public}s success", GetAnonyString(dhId_).c_str());
129     return DCAMERA_OK;
130 }
131 
DCameraNotify(std::shared_ptr<DCameraEvent> & events)132 int32_t DCameraSinkController::DCameraNotify(std::shared_ptr<DCameraEvent>& events)
133 {
134     DHLOGI("DCameraNotify dhId: %{public}s", GetAnonyString(dhId_).c_str());
135     if (srcDevId_.empty()) {
136         DHLOGE("source deviceId is empty");
137         return DCAMERA_BAD_VALUE;
138     }
139 
140     sptr<IDistributedCameraSource> sourceSA = DCameraSinkServiceIpc::GetInstance().GetSourceRemoteCamSrv(srcDevId_);
141     if (sourceSA == nullptr) {
142         DHLOGE("sourceSA is null");
143         return DCAMERA_BAD_VALUE;
144     }
145 
146     DCameraEventCmd eventCmd;
147     std::string jsonStr = "";
148     eventCmd.type_ = DCAMERA_PROTOCOL_TYPE_MESSAGE;
149     eventCmd.dhId_ = dhId_;
150     eventCmd.command_ = DCAMERA_PROTOCOL_CMD_STATE_NOTIFY;
151     eventCmd.value_ = events;
152     int32_t ret = eventCmd.Marshal(jsonStr);
153     if (ret != DCAMERA_OK) {
154         DHLOGE("DCameraEventCmd marshal failed, dhId: %{public}s, ret: %{public}d",
155                GetAnonyString(dhId_).c_str(), ret);
156         return ret;
157     }
158 
159     std::string sinkDevId;
160     ret = GetLocalDeviceNetworkId(sinkDevId);
161     if (ret != DCAMERA_OK) {
162         DHLOGE("GetLocalDeviceNetworkId failed, devId: %{public}s, dhId: %{public}s, ret: %{public}d",
163                GetAnonyString(sinkDevId).c_str(), GetAnonyString(dhId_).c_str(), ret);
164         return ret;
165     }
166 
167     ret = sourceSA->DCameraNotify(sinkDevId, dhId_, jsonStr);
168     if (ret != DCAMERA_OK) {
169         DHLOGE("SourceSA notify failed, srcId: %{public}s, sinkId: %{public}s, dhId: %{public}s, ret: %{public}d",
170                GetAnonyString(srcDevId_).c_str(), GetAnonyString(sinkDevId).c_str(),
171                GetAnonyString(dhId_).c_str(), ret);
172         return ret;
173     }
174 
175     DHLOGI("DCameraNotify %{public}s success", GetAnonyString(dhId_).c_str());
176     return DCAMERA_OK;
177 }
178 
UpdateSettings(std::vector<std::shared_ptr<DCameraSettings>> & settings)179 int32_t DCameraSinkController::UpdateSettings(std::vector<std::shared_ptr<DCameraSettings>>& settings)
180 {
181     DHLOGI("UpdateSettings dhId: %{public}s", GetAnonyString(dhId_).c_str());
182     if (!CheckPermission()) {
183         DHLOGE("DCameraSinkController UpdateSettings fail, CheckPermission fail");
184         return DCAMERA_WRONG_STATE;
185     }
186     int32_t ret = operator_->UpdateSettings(settings);
187     if (ret != DCAMERA_OK) {
188         DHLOGE("UpdateSettings failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
189         return ret;
190     }
191 
192     DHLOGI("UpdateSettings %{public}s success", GetAnonyString(dhId_).c_str());
193     return DCAMERA_OK;
194 }
195 
GetCameraInfo(std::shared_ptr<DCameraInfo> & camInfo)196 int32_t DCameraSinkController::GetCameraInfo(std::shared_ptr<DCameraInfo>& camInfo)
197 {
198     DHLOGI("GetCameraInfo dhId: %{public}s, session state: %{public}d", GetAnonyString(dhId_).c_str(), sessionState_);
199     camInfo->state_ = sessionState_;
200     return DCAMERA_OK;
201 }
202 
OpenChannel(std::shared_ptr<DCameraOpenInfo> & openInfo)203 int32_t DCameraSinkController::OpenChannel(std::shared_ptr<DCameraOpenInfo>& openInfo)
204 {
205     DHLOGI("DCameraSinkController OpenChannel Start, dhId: %{public}s", GetAnonyString(dhId_).c_str());
206     if (!CheckPermission()) {
207         DHLOGE("DCameraSinkController OpenChannel fail, CheckPermission fail");
208         return DCAMERA_WRONG_STATE;
209     }
210     if (sessionState_ != DCAMERA_CHANNEL_STATE_DISCONNECTED) {
211         DHLOGE("wrong state, dhId: %{public}s, sessionState: %{public}d", GetAnonyString(dhId_).c_str(), sessionState_);
212         return DCAMERA_WRONG_STATE;
213     }
214     srcDevId_ = openInfo->sourceDevId_;
215     int32_t ret = sinkCallback_->OnNotifyResourceInfo(ResourceEventType::EVENT_TYPE_QUERY_RESOURCE, PAGE_SUBTYPE,
216         srcDevId_, isSensitive_, isSameAccount_);
217     CHECK_AND_RETURN_RET_LOG(ret != DCAMERA_OK, ret, "Query resource failed, ret: %{public}d", ret);
218     DHLOGI("OpenChannel isSensitive: %{public}d, isSameAccout: %{public}d", isSensitive_, isSameAccount_);
219     if (isSensitive_ && !isSameAccount_) {
220         DHLOGE("Privacy resource must be logged in with the same account.");
221         return DCAMERA_BAD_VALUE;
222     }
223 
224     if (isCheckSecLevel_) {
225         std::string sinkDevId;
226         ret = GetLocalDeviceNetworkId(sinkDevId);
227         CHECK_AND_RETURN_RET_LOG(ret != DCAMERA_OK, ret, "GetLocalDeviceNetworkId failed, ret: %{public}d", ret);
228         if (isSensitive_ && !CheckDeviceSecurityLevel(srcDevId_, sinkDevId)) {
229             DHLOGE("Check device security level failed!");
230             return DCAMERA_BAD_VALUE;
231         }
232     }
233     DCameraLowLatency::GetInstance().EnableLowLatency();
234     std::vector<DCameraIndex> indexs;
235     indexs.push_back(DCameraIndex(srcDevId_, dhId_));
236     auto controller = std::shared_ptr<DCameraSinkController>(shared_from_this());
237     std::shared_ptr<ICameraChannelListener> listener =
238         std::make_shared<DCameraSinkControllerChannelListener>(controller);
239     ret = channel_->CreateSession(indexs, SESSION_FLAG, DCAMERA_SESSION_MODE_CTRL, listener);
240     if (ret != DCAMERA_OK) {
241         DHLOGE("channel create session failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
242         return ret;
243     }
244     ret = PullUpPage();
245     CHECK_AND_RETURN_RET_LOG(ret != DCAMERA_OK, ret, "PullUpPage failed");
246     DHLOGI("DCameraSinkController OpenChannel %{public}s success", GetAnonyString(dhId_).c_str());
247     return DCAMERA_OK;
248 }
249 
PullUpPage()250 int32_t DCameraSinkController::PullUpPage()
251 {
252     if (isSensitive_) {
253         bool isSensitive = false;
254         bool isSameAccout = false;
255         int32_t ret = sinkCallback_->OnNotifyResourceInfo(ResourceEventType::EVENT_TYPE_PULL_UP_PAGE, PAGE_SUBTYPE,
256             srcDevId_, isSensitive, isSameAccout);
257         if (ret != DCAMERA_OK) {
258             DHLOGE("pull up page failed, ret %{public}d", ret);
259             return ret;
260         }
261         isPageStatus_.store(true);
262     }
263     return DCAMERA_OK;
264 }
265 
CloseChannel()266 int32_t DCameraSinkController::CloseChannel()
267 {
268     DHLOGI("DCameraSinkController CloseChannel Start, dhId: %{public}s", GetAnonyString(dhId_).c_str());
269     std::lock_guard<std::mutex> autoLock(channelLock_);
270     DCameraLowLatency::GetInstance().DisableLowLatency();
271     DCameraSinkServiceIpc::GetInstance().DeleteSourceRemoteCamSrv(srcDevId_);
272     srcDevId_.clear();
273     if (channel_ == nullptr) {
274         return DCAMERA_BAD_VALUE;
275     }
276     int32_t ret = channel_->ReleaseSession();
277     if (ret != DCAMERA_OK) {
278         DHLOGE("DCameraSinkController release channel failed, dhId: %{public}s, ret: %{public}d",
279                GetAnonyString(dhId_).c_str(), ret);
280     }
281 
282     ret = output_->CloseChannel();
283     if (ret != DCAMERA_OK) {
284         DHLOGE("DCameraSinkController CloseChannel failed, dhId: %{public}s, ret: %{public}d",
285                GetAnonyString(dhId_).c_str(), ret);
286     }
287     sessionState_ = DCAMERA_CHANNEL_STATE_DISCONNECTED;
288     if (isPageStatus_.load()) {
289         bool isSensitive = false;
290         bool isSameAccout = false;
291         ret = sinkCallback_->OnNotifyResourceInfo(ResourceEventType::EVENT_TYPE_CLOSE_PAGE, PAGE_SUBTYPE, srcDevId_,
292             isSensitive, isSameAccout);
293         if (ret != DCAMERA_OK) {
294             DHLOGE("close page failed, ret: %{public}d", ret);
295         }
296     }
297     isPageStatus_.store(false);
298     DHLOGI("DCameraSinkController CloseChannel %{public}s success", GetAnonyString(dhId_).c_str());
299     return DCAMERA_OK;
300 }
301 
Init(std::vector<DCameraIndex> & indexs)302 int32_t DCameraSinkController::Init(std::vector<DCameraIndex>& indexs)
303 {
304     DHLOGI("DCameraSinkController Init");
305     dhId_ = indexs[0].dhId_;
306     operator_ = std::make_shared<DCameraClient>(dhId_);
307     output_ = std::make_shared<DCameraSinkOutput>(dhId_, operator_);
308     int32_t ret = output_->Init();
309     if (ret != DCAMERA_OK) {
310         DHLOGE("output init failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
311         return ret;
312     }
313 
314     auto controller = std::shared_ptr<DCameraSinkController>(shared_from_this());
315     std::shared_ptr<StateCallback> stateCallback = std::make_shared<DCameraSinkControllerStateCallback>(controller);
316     operator_->SetStateCallback(stateCallback);
317     ret = operator_->Init();
318     if (ret != DCAMERA_OK) {
319         DHLOGE("operator init failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
320         return ret;
321     }
322 
323     channel_ = std::make_shared<DCameraChannelSinkImpl>();
324     std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create(true);
325     sinkCotrEventHandler_ =
326         std::make_shared<DCameraSinkController::DCameraSinkContrEventHandler>(runner, shared_from_this());
327     isInit_ = true;
328     initCallback_ = std::make_shared<DeviceInitCallback>();
329     DHLOGI("DCameraSinkController Init %{public}s success", GetAnonyString(dhId_).c_str());
330     return DCAMERA_OK;
331 }
332 
UnInit()333 int32_t DCameraSinkController::UnInit()
334 {
335     DHLOGI("DCameraSinkController UnInit dhId: %{public}s", GetAnonyString(dhId_).c_str());
336     std::lock_guard<std::mutex> autoLock(autoLock_);
337     int32_t ret = StopCapture();
338     if (ret != DCAMERA_OK) {
339         DHLOGE("DCameraSinkController UnInit %{public}s stop capture failed, ret: %{public}d",
340             GetAnonyString(dhId_).c_str(), ret);
341     }
342 
343     ret = CloseChannel();
344     if (ret != DCAMERA_OK) {
345         DHLOGE("DCameraSinkController UnInit %{public}s close channel failed, ret: %{public}d",
346             GetAnonyString(dhId_).c_str(), ret);
347     }
348 
349     if (output_ != nullptr) {
350         ret = output_->UnInit();
351         if (ret != DCAMERA_OK) {
352             DHLOGE("DCameraSinkController release output failed, dhId: %{public}s, ret: %{public}d",
353                    GetAnonyString(dhId_).c_str(), ret);
354         }
355     }
356 
357     if (operator_ != nullptr) {
358         ret = operator_->UnInit();
359         if (ret != DCAMERA_OK) {
360             DHLOGE("DCameraSinkController release operator failed, dhId: %{public}s, ret: %{public}d",
361                    GetAnonyString(dhId_).c_str(), ret);
362         }
363     }
364 
365     isInit_ = false;
366     DHLOGI("DCameraSinkController UnInit %{public}s success", GetAnonyString(dhId_).c_str());
367     return DCAMERA_OK;
368 }
369 
DCameraSinkContrEventHandler(const std::shared_ptr<AppExecFwk::EventRunner> & runner,std::shared_ptr<DCameraSinkController> sinkContrPtr)370 DCameraSinkController::DCameraSinkContrEventHandler::DCameraSinkContrEventHandler(
371     const std::shared_ptr<AppExecFwk::EventRunner> &runner, std::shared_ptr<DCameraSinkController> sinkContrPtr)
372     : AppExecFwk::EventHandler(runner), sinkContrWPtr_(sinkContrPtr)
373 {
374     DHLOGI("Ctor DCameraSinkContrEventHandler.");
375 }
376 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)377 void DCameraSinkController::DCameraSinkContrEventHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event)
378 {
379     CHECK_AND_RETURN_LOG(event, "event is nullptr.");
380     uint32_t eventId = event->GetInnerEventId();
381     auto sinkContr = sinkContrWPtr_.lock();
382     if (sinkContr == nullptr) {
383         DHLOGE("Can not get strong self ptr");
384         return;
385     }
386     switch (eventId) {
387         case EVENT_FRAME_TRIGGER:
388             sinkContr->ProcessFrameTrigger(event);
389             break;
390         case EVENT_AUTHORIZATION:
391             sinkContr->ProcessPostAuthorization(event);
392             break;
393         default:
394             DHLOGE("event is undefined, id is %d", eventId);
395             break;
396     }
397 }
398 
ProcessFrameTrigger(const AppExecFwk::InnerEvent::Pointer & event)399 void DCameraSinkController::ProcessFrameTrigger(const AppExecFwk::InnerEvent::Pointer &event)
400 {
401     DHLOGD("Receive frame trigger event then start process data in sink controller.");
402     std::shared_ptr<std::string> param = event->GetSharedObject<std::string>();
403     CHECK_AND_RETURN_LOG(param == nullptr, "ProcessFrameTrigger get param is null");
404     accessControl_->TriggerFrame(*param);
405 }
406 
ProcessPostAuthorization(const AppExecFwk::InnerEvent::Pointer & event)407 void DCameraSinkController::ProcessPostAuthorization(const AppExecFwk::InnerEvent::Pointer &event)
408 {
409     DHLOGD("Receive post authorization event then start process data in sink controller.");
410     std::shared_ptr<std::vector<std::shared_ptr<DCameraCaptureInfo>>> captureInfos =
411         event->GetSharedObject<std::vector<std::shared_ptr<DCameraCaptureInfo>>>();
412     CHECK_AND_RETURN_LOG(captureInfos == nullptr, "ProcessPostAuthorization get captureInfos is null");
413     PostAuthorization(*captureInfos);
414 }
415 
OnStateChanged(std::shared_ptr<DCameraEvent> & event)416 void DCameraSinkController::OnStateChanged(std::shared_ptr<DCameraEvent>& event)
417 {
418     DHLOGI("DCameraSinkController::OnStateChanged dhId: %{public}s, result: %{public}d",
419            GetAnonyString(dhId_).c_str(), event->eventResult_);
420     if (event->eventResult_ == DCAMERA_EVENT_DEVICE_PREEMPT) {
421         DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_DEVICE_PREEMPT, std::string("camera device preempted"));
422     } else {
423         DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_DEVICE_ERROR, std::string("camera error"));
424     }
425 }
426 
OnMetadataResult(std::vector<std::shared_ptr<DCameraSettings>> & settings)427 void DCameraSinkController::OnMetadataResult(std::vector<std::shared_ptr<DCameraSettings>>& settings)
428 {
429     DHLOGI("DCameraSinkController::OnMetadataResult dhId: %{public}s", GetAnonyString(dhId_).c_str());
430     if (settings.empty()) {
431         DHLOGE("camera settings is empty");
432         return;
433     }
434     DCameraMetadataSettingCmd cmd;
435     cmd.type_ = DCAMERA_PROTOCOL_TYPE_MESSAGE;
436     cmd.dhId_ = dhId_;
437     cmd.command_ = DCAMERA_PROTOCOL_CMD_METADATA_RESULT;
438     cmd.value_.assign(settings.begin(), settings.end());
439     std::string jsonStr;
440     int32_t ret = cmd.Marshal(jsonStr);
441     if (ret != DCAMERA_OK) {
442         DHLOGE("Marshal metadata settings failed, dhId: %{public}s ret: %{public}d",
443             GetAnonyString(dhId_).c_str(), ret);
444         return;
445     }
446     std::shared_ptr<DataBuffer> buffer = std::make_shared<DataBuffer>(jsonStr.length() + 1);
447     ret = memcpy_s(buffer->Data(), buffer->Capacity(), reinterpret_cast<uint8_t *>(const_cast<char *>(jsonStr.c_str())),
448         jsonStr.length());
449     if (ret != EOK) {
450         DHLOGE("memcpy_s failed, dhId: %{public}s ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
451         return;
452     }
453     ret = channel_->SendData(buffer);
454     if (ret != DCAMERA_OK) {
455         DHLOGE("channel send data failed, dhId: %{public}s ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
456         return;
457     }
458     DHLOGI("DCameraSinkController::OnMetadataResult dhId: %{public}s success", GetAnonyString(dhId_).c_str());
459 }
460 
OnSessionState(int32_t state)461 void DCameraSinkController::OnSessionState(int32_t state)
462 {
463     DHLOGI("DCameraSinkController::OnSessionState dhId: %{public}s, state: %{public}d",
464         GetAnonyString(dhId_).c_str(), state);
465     sessionState_ = state;
466     switch (state) {
467         case DCAMERA_CHANNEL_STATE_CONNECTING:
468             DHLOGI("channel is connecting");
469             break;
470         case DCAMERA_CHANNEL_STATE_CONNECTED:
471             DHLOGI("channel is connected");
472             break;
473         case DCAMERA_CHANNEL_STATE_DISCONNECTED:
474             DHLOGI("channel is disconnected");
475             std::thread([this]() {
476                 DHLOGI("DCameraSinkController::OnSessionState %{public}s new thread session state: %{public}d",
477                     GetAnonyString(dhId_).c_str(), sessionState_);
478                 prctl(PR_SET_NAME, CHANNEL_DISCONNECTED.c_str());
479                 std::lock_guard<std::mutex> autoLock(autoLock_);
480                 int32_t ret = CloseChannel();
481                 if (ret != DCAMERA_OK) {
482                     DHLOGE("session state: %{public}d, %{public}s close channel failed, ret: %{public}d",
483                         sessionState_, GetAnonyString(dhId_).c_str(), ret);
484                 }
485                 ret = StopCapture();
486                 if (ret != DCAMERA_OK) {
487                     DHLOGE("session state: %{public}d, %{public}s stop capture failed, ret: %{public}d",
488                         sessionState_, GetAnonyString(dhId_).c_str(), ret);
489                 }
490             }).detach();
491             break;
492         default:
493             DHLOGE("unknown session state");
494             break;
495     }
496 }
497 
OnSessionError(int32_t eventType,int32_t eventReason,std::string detail)498 void DCameraSinkController::OnSessionError(int32_t eventType, int32_t eventReason, std::string detail)
499 {
500     DHLOGI("DCameraSinkController::OnSessionError dhId: %{public}s, eventType: %{public}d, eventReason: %{public}d,"
501         " detail: %{public}s", GetAnonyString(dhId_).c_str(), eventType, eventReason, detail.c_str());
502 }
503 
OnDataReceived(std::vector<std::shared_ptr<DataBuffer>> & buffers)504 void DCameraSinkController::OnDataReceived(std::vector<std::shared_ptr<DataBuffer>>& buffers)
505 {
506     DHLOGI("OnReceivedData %{public}s control channel receive data", GetAnonyString(dhId_).c_str());
507     for (auto& buffer : buffers) {
508         if (buffer->Size() <= 0 || buffer->Size() > DATABUFF_MAX_SIZE) {
509             DHLOGI("buffer is invalid");
510             return;
511         }
512         HandleReceivedData(buffer);
513     }
514 }
515 
PostAuthorization(std::vector<std::shared_ptr<DCameraCaptureInfo>> & captureInfos)516 void DCameraSinkController::PostAuthorization(std::vector<std::shared_ptr<DCameraCaptureInfo>>& captureInfos)
517 {
518     DHLOGI("DCameraSinkController::PostAuthorization dhId: %{public}s", GetAnonyString(dhId_).c_str());
519     int32_t ret = StartCaptureInner(captureInfos);
520     if (ret == DCAMERA_OK) {
521         accessControl_->NotifySensitiveSrc(SRC_TYPE);
522     }
523 }
524 
StartCaptureInner(std::vector<std::shared_ptr<DCameraCaptureInfo>> & captureInfos)525 int32_t DCameraSinkController::StartCaptureInner(std::vector<std::shared_ptr<DCameraCaptureInfo>>& captureInfos)
526 {
527     DHLOGI("StartCaptureInner dhId: %{public}s", GetAnonyString(dhId_).c_str());
528     std::lock_guard<std::mutex> autoLock(captureLock_);
529     int32_t ret = output_->StartCapture(captureInfos);
530     if (ret != DCAMERA_OK) {
531         DHLOGE("output start capture failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
532         DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_DEVICE_ERROR, std::string("output start capture failed"));
533         return ret;
534     }
535     PropertyCarrier carrier;
536     ret = output_->GetProperty(SURFACE, carrier);
537     if (ret != DCAMERA_OK) {
538         DHLOGD("StartCaptureInner: get property fail.");
539         return DCAMERA_BAD_VALUE;
540     }
541     ret = operator_->StartCapture(captureInfos, carrier.surface_, sceneMode_);
542     if (ret != DCAMERA_OK) {
543         DHLOGE("camera client start capture failed, dhId: %{public}s, ret: %{public}d",
544             GetAnonyString(dhId_).c_str(), ret);
545         if (ret == DCAMERA_ALLOC_ERROR) {
546             DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_NO_PERMISSION,
547                                std::string("operator start capture permission denial."));
548         } else if (ret == DCAMERA_DEVICE_BUSY) {
549             DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_DEVICE_IN_USE,
550                                std::string("operator start capture in used."));
551         }
552         return ret;
553     }
554 
555     DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_CAMERA_SUCCESS, std::string("operator start capture success"));
556     DHLOGI("DCameraSinkController::StartCaptureInner %{public}s success", GetAnonyString(dhId_).c_str());
557     return DCAMERA_OK;
558 }
559 
DCameraNotifyInner(int32_t type,int32_t result,std::string reason)560 int32_t DCameraSinkController::DCameraNotifyInner(int32_t type, int32_t result, std::string reason)
561 {
562     std::shared_ptr<DCameraEvent> event = std::make_shared<DCameraEvent>();
563     event->eventType_ = type;
564     event->eventResult_ = result;
565     event->eventContent_ = reason;
566     return DCameraNotify(event);
567 }
568 
HandleReceivedData(std::shared_ptr<DataBuffer> & dataBuffer)569 int32_t DCameraSinkController::HandleReceivedData(std::shared_ptr<DataBuffer>& dataBuffer)
570 {
571     DHLOGI("DCameraSinkController::HandleReceivedData dhId: %{public}s", GetAnonyString(dhId_).c_str());
572     uint8_t *data = dataBuffer->Data();
573     std::string jsonStr(reinterpret_cast<const char *>(data), dataBuffer->Capacity());
574     cJSON *rootValue = cJSON_Parse(jsonStr.c_str());
575     if (rootValue == nullptr) {
576         return DCAMERA_BAD_VALUE;
577     }
578     cJSON *comvalue = cJSON_GetObjectItemCaseSensitive(rootValue, "Command");
579     if (comvalue == nullptr || !cJSON_IsString(comvalue) || (comvalue->valuestring == nullptr)) {
580         cJSON_Delete(rootValue);
581         DHLOGE("parse command failed");
582         return DCAMERA_BAD_VALUE;
583     }
584     std::string command = std::string(comvalue->valuestring);
585     cJSON_Delete(rootValue);
586     if ((!command.empty()) && (command.compare(DCAMERA_PROTOCOL_CMD_CAPTURE) == 0)) {
587         DCameraCaptureInfoCmd captureInfoCmd;
588         int ret = captureInfoCmd.Unmarshal(jsonStr);
589         if (ret != DCAMERA_OK) {
590             DHLOGE("Capture Info Unmarshal failed, dhId: %{public}s ret: %{public}d",
591                 GetAnonyString(dhId_).c_str(), ret);
592             return ret;
593         }
594         sceneMode_ = captureInfoCmd.sceneMode_;
595         return StartCapture(captureInfoCmd.value_, sceneMode_);
596     } else if ((!command.empty()) && (command.compare(DCAMERA_PROTOCOL_CMD_UPDATE_METADATA) == 0)) {
597         DCameraMetadataSettingCmd metadataSettingCmd;
598         int ret = metadataSettingCmd.Unmarshal(jsonStr);
599         if (ret != DCAMERA_OK) {
600             DHLOGE("Metadata Setting Unmarshal failed, dhId: %{public}s ret: %{public}d",
601                    GetAnonyString(dhId_).c_str(), ret);
602             return ret;
603         }
604         return UpdateSettings(metadataSettingCmd.value_);
605     }
606     return DCAMERA_BAD_VALUE;
607 }
608 
PauseDistributedHardware(const std::string & networkId)609 int32_t DCameraSinkController::PauseDistributedHardware(const std::string &networkId)
610 {
611     DHLOGI("Pause distributed hardware dhId: %{public}s", GetAnonyString(dhId_).c_str());
612     if (networkId.empty()) {
613         DHLOGE("networkId is empty");
614         return DCAMERA_BAD_VALUE;
615     }
616     if (operator_ == nullptr) {
617         DHLOGE("operator_ is nullptr.");
618         return DCAMERA_BAD_VALUE;
619     }
620     int32_t ret = operator_->PauseCapture();
621     if (ret != DCAMERA_OK) {
622         DHLOGE("Pause distributed hardware failed, dhId: %{public}s, ret: %{public}d",
623             GetAnonyString(dhId_).c_str(), ret);
624     }
625     return ret;
626 }
627 
ResumeDistributedHardware(const std::string & networkId)628 int32_t DCameraSinkController::ResumeDistributedHardware(const std::string &networkId)
629 {
630     DHLOGI("Resume distributed hardware dhId: %{public}s", GetAnonyString(dhId_).c_str());
631     if (networkId.empty()) {
632         DHLOGE("networkId is empty");
633         return DCAMERA_BAD_VALUE;
634     }
635     if (operator_ == nullptr) {
636         DHLOGE("operator_ is nullptr.");
637         return DCAMERA_BAD_VALUE;
638     }
639     int32_t ret = operator_->ResumeCapture();
640     if (ret != DCAMERA_OK) {
641         DHLOGE("Resume distributed hardware failed, dhId: %{public}s, ret: %{public}d",
642             GetAnonyString(dhId_).c_str(), ret);
643     }
644     return ret;
645 }
646 
StopDistributedHardware(const std::string & networkId)647 int32_t DCameraSinkController::StopDistributedHardware(const std::string &networkId)
648 {
649     DHLOGI("Stop distributed hardware dhId: %{public}s", GetAnonyString(dhId_).c_str());
650     if (networkId.empty()) {
651         DHLOGE("networkId is empty");
652         return DCAMERA_BAD_VALUE;
653     }
654 
655     isPageStatus_.store(false);
656     return DCameraNotifyInner(DCAMERA_SINK_STOP, DCAMERA_EVENT_SINK_STOP, std::string("sink stop dcamera business"));
657 }
658 
CheckDeviceSecurityLevel(const std::string & srcDeviceId,const std::string & dstDeviceId)659 bool DCameraSinkController::CheckDeviceSecurityLevel(const std::string &srcDeviceId, const std::string &dstDeviceId)
660 {
661     DHLOGD("CheckDeviceSecurityLevel srcDeviceId %{public}s, dstDeviceId %{public}s.",
662         GetAnonyString(srcDeviceId).c_str(), GetAnonyString(dstDeviceId).c_str());
663     std::string srcUdid = GetUdidByNetworkId(srcDeviceId);
664     if (srcUdid.empty()) {
665         DHLOGE("src udid is empty");
666         return false;
667     }
668     std::string dstUdid = GetUdidByNetworkId(dstDeviceId);
669     if (dstUdid.empty()) {
670         DHLOGE("dst udid is empty");
671         return false;
672     }
673     DHLOGD("CheckDeviceSecurityLevel srcUdid %{public}s, dstUdid %{public}s.",
674         GetAnonyString(srcUdid).c_str(), GetAnonyString(dstUdid).c_str());
675     int32_t srcDeviceSecurityLevel = GetDeviceSecurityLevel(srcUdid);
676     int32_t dstDeviceSecurityLevel = GetDeviceSecurityLevel(dstUdid);
677     DHLOGI("srcDeviceSecurityLevel is %{public}d, dstDeviceSecurityLevel is %{public}d.",
678         srcDeviceSecurityLevel, dstDeviceSecurityLevel);
679     if (srcDeviceSecurityLevel == DEFAULT_DEVICE_SECURITY_LEVEL ||
680         srcDeviceSecurityLevel < dstDeviceSecurityLevel) {
681         DHLOGE("The device security of source device is lower.");
682         return false;
683     }
684     return true;
685 }
686 
GetDeviceSecurityLevel(const std::string & udid)687 int32_t DCameraSinkController::GetDeviceSecurityLevel(const std::string &udid)
688 {
689     DeviceIdentify devIdentify;
690     devIdentify.length = DEVICE_ID_MAX_LEN;
691     int32_t ret = memcpy_s(devIdentify.identity, DEVICE_ID_MAX_LEN, udid.c_str(), DEVICE_ID_MAX_LEN);
692     if (ret != 0) {
693         DHLOGE("str copy failed %{public}d", ret);
694         return DEFAULT_DEVICE_SECURITY_LEVEL;
695     }
696     DeviceSecurityInfo *info = nullptr;
697     ret = RequestDeviceSecurityInfo(&devIdentify, nullptr, &info);
698     if (ret != SUCCESS) {
699         DHLOGE("Request device security info failed %{public}d", ret);
700         FreeDeviceSecurityInfo(info);
701         info = nullptr;
702         return DEFAULT_DEVICE_SECURITY_LEVEL;
703     }
704     int32_t level = 0;
705     ret = GetDeviceSecurityLevelValue(info, &level);
706     DHLOGD("Get device security level, level is %{public}d", level);
707     FreeDeviceSecurityInfo(info);
708     info = nullptr;
709     if (ret != SUCCESS) {
710         DHLOGE("Get device security level failed %{public}d", ret);
711         return DEFAULT_DEVICE_SECURITY_LEVEL;
712     }
713     return level;
714 }
715 
GetUdidByNetworkId(const std::string & networkId)716 std::string DCameraSinkController::GetUdidByNetworkId(const std::string &networkId)
717 {
718     if (networkId.empty()) {
719         DHLOGE("networkId is empty!");
720         return "";
721     }
722     int32_t ret = DeviceManager::GetInstance().InitDeviceManager(DCAMERA_PKG_NAME, initCallback_);
723     if (ret != DCAMERA_OK) {
724         DHLOGE("InitDeviceManager failed ret = %{public}d", ret);
725         return "";
726     }
727     std::string udid = "";
728     ret = DeviceManager::GetInstance().GetUdidByNetworkId(DCAMERA_PKG_NAME, networkId, udid);
729     if (ret != DCAMERA_OK) {
730         DHLOGE("GetUdidByNetworkId failed ret = %{public}d", ret);
731         return "";
732     }
733     return udid;
734 }
735 
CheckPermission()736 bool DCameraSinkController::CheckPermission()
737 {
738     DHLOGI("DCameraSinkController CheckPermission Start");
739     auto uid = IPCSkeleton::GetCallingUid();
740     return uid == DCAMERA_UID;
741 }
742 
OnRemoteDied()743 void DeviceInitCallback::OnRemoteDied()
744 {
745     DHLOGI("DeviceInitCallback OnRemoteDied");
746 }
747 } // namespace DistributedHardware
748 } // namespace OHOS