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 "distributed_device_profile_service.h"
17 
18 #include "file_ex.h"
19 #include "string_ex.h"
20 
21 #include "authority_manager.h"
22 #include "content_sensor_manager.h"
23 #include "device_profile_dumper.h"
24 #include "device_profile_errors.h"
25 #include "device_profile_log.h"
26 #include "device_profile_storage_manager.h"
27 #include "distributed_device_profile_service_new.h"
28 #include "dp_device_manager.h"
29 #include "dp_radar_helper.h"
30 #include "event_handler_factory.h"
31 #include "hitrace_meter.h"
32 #include "if_system_ability_manager.h"
33 #include "ipc_object_proxy.h"
34 #include "ipc_skeleton.h"
35 #include "iprofile_event_notifier.h"
36 #include "iservice_registry.h"
37 #include "sa_profiles.h"
38 #include "service_characteristic_profile.h"
39 #include "sync_coordinator.h"
40 #include "subscribe_manager.h"
41 #include "trust_group_manager.h"
42 
43 namespace OHOS {
44 namespace DeviceProfile {
45 namespace {
46 const std::string TAG = "DistributedDeviceProfileService";
47 const std::string DP_DEVICE_SUB_TRACE = "DP_DEVICE_SUB";
48 const std::string TASK_ID = "unload";
49 const std::string BOOT_COMPLETED_EVENT = "usual.event.BOOT_COMPLETED";
50 const std::string STRING_DEVICE_ONLINE = "deviceonline";
51 const std::string EVENT_ID = "eventId";
52 const std::string NAME = "name";
53 const std::string INIT_TASK_ID = "CheckAndInitDP";
54 constexpr int32_t DELAY_TIME = 180000;
55 constexpr int32_t UNLOAD_IMMEDIATELY = 0;
56 constexpr int32_t DP_IPC_THREAD_NUM = 32;
57 }
58 
59 IMPLEMENT_SINGLE_INSTANCE(DistributedDeviceProfileService);
60 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(&DistributedDeviceProfileService::GetInstance());
61 
DistributedDeviceProfileService()62 DistributedDeviceProfileService::DistributedDeviceProfileService()
63     : SystemAbility(DISTRIBUTED_DEVICE_PROFILE_SA_ID, true)
64 {
65 }
66 
Init()67 bool DistributedDeviceProfileService::Init()
68 {
69     HILOGI("init DistributedDeviceProfileServiceNew");
70     DistributedDeviceProfile::DistributedDeviceProfileServiceNew::GetInstance().Init();
71     {
72         std::lock_guard<std::mutex> lock(unloadMutex_);
73         if (unloadHandler_ == nullptr) {
74             unloadHandler_ = DistributedDeviceProfile::EventHandlerFactory::GetInstance().GetEventHandler();
75         }
76         if (unloadHandler_ == nullptr) {
77             return false;
78         }
79     }
80     HILOGI("init succeeded");
81     return true;
82 }
83 
PutDeviceProfile(const ServiceCharacteristicProfile & profile)84 int32_t DistributedDeviceProfileService::PutDeviceProfile(const ServiceCharacteristicProfile& profile)
85 {
86     bool ret = AuthorityManager::GetInstance().CheckServiceAuthority(AuthValue::AUTH_W,
87         profile.GetServiceId());
88     struct RadarInfo info = {
89         .funcName = "PutDeviceProfile",
90         .stageRes = ret ?
91             static_cast<int32_t>(StageRes::STAGE_SUCC) : static_cast<int32_t>(StageRes::STAGE_FAIL),
92         .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
93         .errCode = ERR_DP_PERMISSION_DENIED,
94     };
95     if (!DpRadarHelper::GetInstance().ReportSaCheckAuth(info)) {
96         HILOGE("ReportSaCheckAuth failed");
97     }
98     if (!ret) {
99         return ERR_DP_PERMISSION_DENIED;
100     }
101     return DeviceProfileStorageManager::GetInstance().PutDeviceProfile(profile);
102 }
103 
DeviceOnline()104 void DistributedDeviceProfileService::DeviceOnline()
105 {
106     HILOGI("device online begin");
107     isOnline_ = true;
108     {
109         std::lock_guard<std::mutex> lock(unloadMutex_);
110         if (unloadHandler_ == nullptr) {
111             return;
112         }
113         unloadHandler_->RemoveTask(TASK_ID);
114     }
115 }
116 
GetDeviceProfile(const std::string & udid,const std::string & serviceId,ServiceCharacteristicProfile & profile)117 int32_t DistributedDeviceProfileService::GetDeviceProfile(const std::string& udid, const std::string& serviceId,
118     ServiceCharacteristicProfile& profile)
119 {
120     bool ret = AuthorityManager::GetInstance().CheckServiceAuthority(AuthValue::AUTH_R,
121         serviceId);
122     struct RadarInfo info = {
123         .funcName = "GetDeviceProfile",
124         .stageRes = ret ?
125             static_cast<int32_t>(StageRes::STAGE_SUCC) : static_cast<int32_t>(StageRes::STAGE_FAIL),
126         .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
127         .errCode = ERR_DP_PERMISSION_DENIED,
128     };
129     if (!DpRadarHelper::GetInstance().ReportSaCheckAuth(info)) {
130         HILOGE("ReportSaCheckAuth failed");
131     }
132     if (!ret) {
133         return ERR_DP_PERMISSION_DENIED;
134     }
135     return DeviceProfileStorageManager::GetInstance().GetDeviceProfile(udid, serviceId, profile);
136 }
137 
DeleteDeviceProfile(const std::string & serviceId)138 int32_t DistributedDeviceProfileService::DeleteDeviceProfile(const std::string& serviceId)
139 {
140     bool ret = AuthorityManager::GetInstance().CheckServiceAuthority(AuthValue::AUTH_W,
141         serviceId);
142     struct RadarInfo info = {
143         .funcName = "DeleteDeviceProfile",
144         .stageRes = ret ?
145             static_cast<int32_t>(StageRes::STAGE_SUCC) : static_cast<int32_t>(StageRes::STAGE_FAIL),
146         .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
147         .errCode = ERR_DP_PERMISSION_DENIED,
148     };
149     if (!DpRadarHelper::GetInstance().ReportSaCheckAuth(info)) {
150         HILOGE("ReportSaCheckAuth failed");
151     }
152     if (!ret) {
153         return ERR_DP_PERMISSION_DENIED;
154     }
155     return DeviceProfileStorageManager::GetInstance().DeleteDeviceProfile(serviceId);
156 }
157 
SubscribeProfileEvents(const std::list<SubscribeInfo> & subscribeInfos,const sptr<IRemoteObject> & profileEventNotifier,std::list<ProfileEvent> & failedEvents)158 int32_t DistributedDeviceProfileService::SubscribeProfileEvents(const std::list<SubscribeInfo>& subscribeInfos,
159     const sptr<IRemoteObject>& profileEventNotifier,
160     std::list<ProfileEvent>& failedEvents)
161 {
162     HITRACE_METER_NAME(HITRACE_TAG_DEVICE_PROFILE, DP_DEVICE_SUB_TRACE);
163     struct RadarInfo info = {
164         .funcName = "SubscribeProfileEvents",
165         .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
166         .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
167     };
168     if (!DpRadarHelper::GetInstance().ReportSaCheckAuth(info)) {
169         HILOGE("ReportSaCheckAuth failed");
170     }
171     return SubscribeManager::GetInstance().SubscribeProfileEvents(subscribeInfos,
172         profileEventNotifier, failedEvents);
173 }
174 
UnsubscribeProfileEvents(const std::list<ProfileEvent> & profileEvents,const sptr<IRemoteObject> & profileEventNotifier,std::list<ProfileEvent> & failedEvents)175 int32_t DistributedDeviceProfileService::UnsubscribeProfileEvents(const std::list<ProfileEvent>& profileEvents,
176     const sptr<IRemoteObject>& profileEventNotifier,
177     std::list<ProfileEvent>& failedEvents)
178 {
179     struct RadarInfo info = {
180         .funcName = "UnsubscribeProfileEvents",
181         .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
182         .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
183     };
184     if (!DpRadarHelper::GetInstance().ReportSaCheckAuth(info)) {
185         HILOGE("ReportSaCheckAuth failed");
186     }
187     return SubscribeManager::GetInstance().UnsubscribeProfileEvents(profileEvents,
188         profileEventNotifier, failedEvents);
189 }
190 
SyncDeviceProfile(const SyncOptions & syncOptions,const sptr<IRemoteObject> & profileEventNotifier)191 int32_t DistributedDeviceProfileService::SyncDeviceProfile(const SyncOptions& syncOptions,
192     const sptr<IRemoteObject>& profileEventNotifier)
193 {
194     bool ret = AuthorityManager::GetInstance().CheckInterfaceAuthority("sync");
195     struct RadarInfo info = {
196         .funcName = "SyncDeviceProfile",
197         .stageRes = ret ?
198             static_cast<int32_t>(StageRes::STAGE_SUCC) : static_cast<int32_t>(StageRes::STAGE_FAIL),
199         .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
200         .errCode = ERR_DP_PERMISSION_DENIED,
201     };
202     if (!DpRadarHelper::GetInstance().ReportSaCheckAuth(info)) {
203         HILOGE("ReportSaCheckAuth failed");
204     }
205     if (!ret) {
206         return ERR_DP_PERMISSION_DENIED;
207     }
208     return DeviceProfileStorageManager::GetInstance().SyncDeviceProfile(syncOptions, profileEventNotifier);
209 }
210 
Dump(int32_t fd,const std::vector<std::u16string> & args)211 int32_t DistributedDeviceProfileService::Dump(int32_t fd, const std::vector<std::u16string>& args)
212 {
213     std::vector<std::string> argsInStr8;
214     for (const auto& arg : args) {
215         argsInStr8.emplace_back(Str16ToStr8(arg));
216     }
217 
218     std::string result;
219     DeviceProfileDumper::Dump(argsInStr8, result);
220 
221     if (!SaveStringToFd(fd, result)) {
222         HILOGE("save to fd failed");
223         return ERR_DP_FILE_FAILED_ERR;
224     }
225     return ERR_OK;
226 }
227 
DelayUnloadTask()228 void DistributedDeviceProfileService::DelayUnloadTask()
229 {
230     auto task = [this]() {
231         HILOGD("do unload task");
232         auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
233         if (samgrProxy == nullptr) {
234             HILOGE("get samgr failed");
235             return;
236         }
237         int32_t ret = samgrProxy->UnloadSystemAbility(DISTRIBUTED_DEVICE_PROFILE_SA_ID);
238         if (ret != ERR_OK) {
239             HILOGE("remove system ability failed");
240             return;
241         }
242     };
243 
244     {
245         std::lock_guard<std::mutex> lock(unloadMutex_);
246         if (unloadHandler_ == nullptr) {
247             return;
248         }
249         unloadHandler_->RemoveTask(TASK_ID);
250         if (!isOnline_) {
251             HILOGI("delay unload task post task");
252             unloadHandler_->PostTask(task, TASK_ID, DELAY_TIME);
253         }
254     }
255 }
256 
OnStart(const SystemAbilityOnDemandReason & startReason)257 void DistributedDeviceProfileService::OnStart(const SystemAbilityOnDemandReason& startReason)
258 {
259     HILOGI("called");
260     if (!Init()) {
261         HILOGE("init failed");
262     }
263     AddSystemAbilityListener(SOFTBUS_SERVER_SA_ID);
264     AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
265     AddSystemAbilityListener(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
266     if (!Publish(this)) {
267         HILOGE("publish SA failed");
268         return;
269     }
270     IPCSkeleton::SetMaxWorkThreadNum(DP_IPC_THREAD_NUM);
271     HILOGI("start reason %{public}s", startReason.GetName().c_str());
272     DelayUnloadTask();
273 }
274 
OnIdle(const SystemAbilityOnDemandReason & idleReason)275 int32_t DistributedDeviceProfileService::OnIdle(const SystemAbilityOnDemandReason& idleReason)
276 {
277     HILOGI("idle reason %{public}d", idleReason.GetId());
278     return UNLOAD_IMMEDIATELY;
279 }
280 
OnStop()281 void DistributedDeviceProfileService::OnStop()
282 {
283     HILOGI("called");
284     if (!DistributedDeviceProfile::DistributedDeviceProfileServiceNew::GetInstance().UnInit()) {
285         HILOGE("UnInit failed");
286         return;
287     }
288 }
289 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)290 void DistributedDeviceProfileService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
291 {
292     HILOGI("called systemAbilityId:%{public}d", systemAbilityId);
293     if (DistributedDeviceProfile::DistributedDeviceProfileServiceNew::GetInstance().IsInited()) {
294         return;
295     }
296     {
297         std::lock_guard<std::mutex> lock(depSaIdsMtx_);
298         if (depSaIds_.empty()) {
299             return;
300         }
301         depSaIds_.erase(systemAbilityId);
302         if (!depSaIds_.empty()) {
303             return;
304         }
305     }
306     DoBusinessInit();
307 }
308 
DoBusinessInit()309 bool DistributedDeviceProfileService::DoBusinessInit()
310 {
311     HILOGD("called");
312     if (!DpDeviceManager::GetInstance().Init()) {
313         HILOGE("DeviceManager init failed");
314         return false;
315     }
316     if (!AuthorityManager::GetInstance().Init()) {
317         HILOGE("AuthorityManager init failed");
318         return false;
319     }
320     if (DistributedDeviceProfile::DistributedDeviceProfileServiceNew::GetInstance().PostInit() != ERR_OK) {
321         HILOGE("PostInit failed");
322         return false;
323     }
324     HILOGI("DoBusinessInit succeeded");
325     return true;
326 }
327 } // namespace DeviceProfile
328 } // namespace OHOS
329