• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2025 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 "ipc_server_stub.h"
17 
18 #include <cstdio>
19 #include <unordered_set>
20 
21 #include "ipc_cmd_register.h"
22 #include "ipc_skeleton.h"
23 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
24 #include "kv_adapter_manager.h"
25 #endif
26 #ifdef SUPPORT_MEMMGR
27 #include "mem_mgr_client.h"
28 #include "mem_mgr_proxy.h"
29 #endif // SUPPORT_MEMMGR
30 #include "system_ability_definition.h"
31 #include "datetime_ex.h"
32 #include "device_manager_service.h"
33 #include "device_manager_service_notify.h"
34 #include "device_name_manager.h"
35 #include "dm_error_type.h"
36 #include "dm_device_info.h"
37 #include "ffrt.h"
38 #include <unistd.h>
39 #include <string>
40 #include <fcntl.h>
41 #include <sys/types.h>
42 #include "dm_log.h"
43 #include "multiple_user_connector.h"
44 #include "permission_manager.h"
45 
46 namespace OHOS {
47 namespace DistributedHardware {
48 namespace {
49 const std::unordered_set<int32_t> CLIENT_CODE { SERVER_DEVICE_STATE_NOTIFY, SERVER_DEVICE_FOUND, BIND_TARGET_RESULT,
50 SERVER_DEVICE_DISCOVERY, SERVER_PUBLISH_FINISH, SERVER_AUTH_RESULT, SERVER_DEVICE_FA_NOTIFY, SERVER_CREDENTIAL_RESULT,
51 SERVER_CREATE_PIN_HOLDER, SERVER_DESTROY_PIN_HOLDER, SERVER_CREATE_PIN_HOLDER_RESULT, SERVER_DESTROY_PIN_HOLDER_RESULT,
52 SERVER_ON_PIN_HOLDER_EVENT, UNBIND_TARGET_RESULT, REMOTE_DEVICE_TRUST_CHANGE, SERVER_DEVICE_SCREEN_STATE_NOTIFY,
53 SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, SINK_BIND_TARGET_RESULT, GET_DEVICE_PROFILE_INFO_LIST_RESULT,
54 GET_DEVICE_ICON_INFO_RESULT, SET_LOCAL_DEVICE_NAME_RESULT, SET_REMOTE_DEVICE_NAME_RESULT };
55 }
56 
57 DM_IMPLEMENT_SINGLE_INSTANCE(IpcServerStub);
58 
59 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(&IpcServerStub::GetInstance());
60 constexpr int32_t DM_IPC_THREAD_NUM = 32;
61 constexpr int32_t MAX_CALLBACK_NUM = 5000;
62 constexpr int32_t RECLAIM_DELAY_TIME = 5 * 60 * 1000 * 1000; // 5 minutes
63 constexpr int32_t ECHO_COUNT = 2;
64 
IpcServerStub()65 IpcServerStub::IpcServerStub() : SystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, true)
66 {
67     registerToService_ = false;
68     state_ = ServiceRunningState::STATE_NOT_START;
69 }
70 
OnStart()71 void IpcServerStub::OnStart()
72 {
73     startBeginTime_ = GetTickCount();
74     LOGI("IpcServerStub::OnStart start");
75     if (state_ == ServiceRunningState::STATE_RUNNING) {
76         LOGI("IpcServerStub has already started.");
77         return;
78     }
79 
80     IPCSkeleton::SetMaxWorkThreadNum(DM_IPC_THREAD_NUM);
81 
82     LOGI("called:AddAbilityListener begin!");
83     AddSystemAbilityListener(DISTRIBUTED_HARDWARE_SA_ID);
84 #ifdef SUPPORT_MEMMGR
85     AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
86 #endif // SUPPORT_MEMMGR
87     AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN);
88     AddSystemAbilityListener(SCREENLOCK_SERVICE_ID);
89     AddSystemAbilityListener(SOFTBUS_SERVER_SA_ID);
90     LOGI("called:AddAbilityListener end!");
91 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
92     AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
93 #endif
94     AddSystemAbilityListener(DEVICE_AUTH_SERVICE_ID);
95     AddSystemAbilityListener(ACCESS_TOKEN_MANAGER_SERVICE_ID);
96     AddSystemAbilityListener(RISK_ANALYSIS_MANAGER_SA_ID);
97     DeviceManagerService::GetInstance().SubscribePackageCommonEvent();
98 }
99 
ReclaimMemmgrFileMemForDM()100 void IpcServerStub::ReclaimMemmgrFileMemForDM()
101 {
102     int32_t memmgrPid = getpid();
103     int32_t echoCnt = ECHO_COUNT;
104     for (int32_t i = 0; i < echoCnt; ++i) {
105         if (memmgrPid <= 0) {
106             LOGE("Get invalid pid : %{public}d.", memmgrPid);
107             return;
108         }
109         std::string path = JoinPath("/proc/", std::to_string(memmgrPid), "reclaim");
110         std::string contentStr = "1";
111         LOGI("Start echo 1 to pid : %{public}d, path: %{public}s", memmgrPid, path.c_str());
112         FILE *file = fopen(path.c_str(), "w");
113         if (file == NULL) {
114             LOGE("ReclaimMemmgrFileMemForDM open file failed.");
115             return;
116         }
117         size_t strLength = contentStr.length();
118         size_t ret = fwrite(contentStr.c_str(), 1, strLength, file);
119         if (ret != strLength) {
120             LOGE("fwrite failed");
121         }
122         if (fclose(file) != DM_OK) {
123             LOGE("fclose failed");
124         }
125     }
126     LOGI("ReclaimMemmgrFileMemForDM success.");
127 }
128 
AddDelimiter(const std::string & path)129 std::string IpcServerStub::AddDelimiter(const std::string &path)
130 {
131     if (path.empty()) {
132         return path;
133     }
134     if (path.rfind("/") != path.size() - 1) {
135         return path + "/";
136     }
137     return path;
138 }
139 
JoinPath(const std::string & prefixPath,const std::string & subPath)140 std::string IpcServerStub::JoinPath(const std::string &prefixPath, const std::string &subPath)
141 {
142     return AddDelimiter(prefixPath) + subPath;
143 }
144 
JoinPath(const std::string & prefixPath,const std::string & midPath,const std::string & subPath)145 std::string IpcServerStub::JoinPath(const std::string &prefixPath, const std::string &midPath,
146     const std::string &subPath)
147 {
148     return JoinPath(JoinPath(prefixPath, midPath), subPath);
149 }
150 
HandleSoftBusServerAdd()151 void IpcServerStub::HandleSoftBusServerAdd()
152 {
153     DeviceManagerService::GetInstance().InitSoftbusListener();
154     if (!Init()) {
155         LOGE("failed to init IpcServerStub");
156         state_ = ServiceRunningState::STATE_NOT_START;
157         return;
158     }
159     state_ = ServiceRunningState::STATE_RUNNING;
160     DeviceNameManager::GetInstance().InitDeviceNameWhenSoftBusReady();
161     ReclaimMemmgrFileMemForDM();
162     std::function<void()> task = [this]() {
163         LOGI("HandleSoftBusServerAdd After 5mins.");
164         ReclaimMemmgrFileMemForDM();
165     };
166     ffrt::submit(task, ffrt::task_attr().delay(RECLAIM_DELAY_TIME));
167     return;
168 }
169 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)170 void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
171 {
172     LOGI("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
173     if (systemAbilityId == SOFTBUS_SERVER_SA_ID) {
174         HandleSoftBusServerAdd();
175         return;
176     }
177 
178 #ifdef SUPPORT_MEMMGR
179     if (systemAbilityId == MEMORY_MANAGER_SA_ID) {
180         int pid = getpid();
181         Memory::MemMgrClient::GetInstance().NotifyProcessStatus(pid, 1, 1, DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
182         return;
183     }
184 #endif // SUPPORT_MEMMGR
185 
186     if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) {
187         MultipleUserConnector::SetAccountInfo(MultipleUserConnector::GetCurrentAccountUserID(),
188             MultipleUserConnector::GetCurrentDMAccountInfo());
189         DeviceManagerService::GetInstance().InitAccountInfo();
190         return;
191     }
192 
193     if (systemAbilityId == SCREENLOCK_SERVICE_ID) {
194         DeviceManagerService::GetInstance().InitScreenLockEvent();
195         return;
196     }
197 
198 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
199     if (systemAbilityId == DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) {
200         KVAdapterManager::GetInstance().ReInit();
201         return;
202     }
203 #endif
204     if (systemAbilityId == DEVICE_AUTH_SERVICE_ID) {
205         DeviceManagerService::GetInstance().InitHichainListener();
206         return;
207     }
208     if (systemAbilityId == ACCESS_TOKEN_MANAGER_SERVICE_ID) {
209         DeviceManagerService::GetInstance().InitHichainListener();
210         return;
211     }
212     if (systemAbilityId == RISK_ANALYSIS_MANAGER_SA_ID) {
213         DeviceManagerService::GetInstance().StartDetectDeviceRisk();
214         return;
215     }
216 }
217 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)218 void IpcServerStub::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
219 {
220     LOGI("OnRemoveSystemAbility systemAbilityId:%{public}d removed!", systemAbilityId);
221     if (systemAbilityId == SOFTBUS_SERVER_SA_ID) {
222         DeviceManagerService::GetInstance().UninitSoftbusListener();
223     } else if (systemAbilityId == DISTRIBUTED_HARDWARE_SA_ID) {
224         DeviceManagerService::GetInstance().LoadHardwareFwkService();
225     }
226 }
227 
Init()228 bool IpcServerStub::Init()
229 {
230     LOGI("IpcServerStub::Init ready to init.");
231     DeviceManagerService::GetInstance().InitDMServiceListener();
232     if (!registerToService_) {
233         bool ret = Publish(this);
234         LOGI("Publish, cost %{public}" PRId64 " ms", GetTickCount() -  startBeginTime_);
235         if (!ret) {
236             LOGE("IpcServerStub::Init Publish failed!");
237             return false;
238         }
239         registerToService_ = true;
240         KVAdapterManager::GetInstance().Init();
241     }
242     return true;
243 }
244 
OnStop()245 void IpcServerStub::OnStop()
246 {
247     LOGI("IpcServerStub::OnStop ready to stop service.");
248     DeviceManagerService::GetInstance().UninitDMServiceListener();
249     state_ = ServiceRunningState::STATE_NOT_START;
250     registerToService_ = false;
251 #ifdef SUPPORT_MEMMGR
252     int pid = getpid();
253     Memory::MemMgrClient::GetInstance().NotifyProcessStatus(pid, 1, 0, DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
254 #endif // SUPPORT_MEMMGR
255     LOGI("IpcServerStub::OnStop end.");
256 }
257 
OnRemoteRequest(uint32_t code,MessageParcel & data,MessageParcel & reply,MessageOption & option)258 int32_t IpcServerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
259 {
260     if (CLIENT_CODE.find(code) != CLIENT_CODE.end()) {
261         return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
262     }
263     auto remoteDescriptor = data.ReadInterfaceToken();
264     if (GetDescriptor() != remoteDescriptor) {
265         LOGI("ReadInterfaceToken fail!");
266         return ERR_DM_IPC_READ_FAILED;
267     }
268     int32_t ret = IpcCmdRegister::GetInstance().OnIpcCmd(static_cast<int32_t>(code), data, reply);
269     if (ret == ERR_DM_UNSUPPORTED_IPC_COMMAND) {
270         LOGW("unsupported code: %{public}d", code);
271         return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
272     }
273     return ret;
274 }
275 
SendCmd(int32_t cmdCode,std::shared_ptr<IpcReq> req,std::shared_ptr<IpcRsp> rsp)276 int32_t IpcServerStub::SendCmd(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp)
277 {
278     MessageParcel data;
279     MessageParcel reply;
280     MessageOption option;
281     if (cmdCode < 0 || cmdCode >= IPC_MSG_BUTT) {
282         LOGE("IpcServerStub::SendCmd error: Invalid para, cmdCode: %{public}d", (int32_t)cmdCode);
283         return IPCObjectStub::OnRemoteRequest(cmdCode, data, reply, option);
284     }
285 
286     if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DM_OK) {
287         LOGE("set request cmd failed");
288         return ERR_DM_IPC_SEND_REQUEST_FAILED;
289     }
290     int32_t ret = IpcCmdRegister::GetInstance().OnIpcCmd(cmdCode, data, reply);
291     if (ret == ERR_DM_UNSUPPORTED_IPC_COMMAND) {
292         LOGW("unsupported code: %{public}d", cmdCode);
293         return IPCObjectStub::OnRemoteRequest(cmdCode, data, reply, option);
294     }
295     return IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp);
296 }
297 
QueryServiceState() const298 ServiceRunningState IpcServerStub::QueryServiceState() const
299 {
300     return state_;
301 }
302 
RegisterDeviceManagerListener(const ProcessInfo & processInfo,sptr<IpcRemoteBroker> listener)303 int32_t IpcServerStub::RegisterDeviceManagerListener(const ProcessInfo &processInfo, sptr<IpcRemoteBroker> listener)
304 {
305     if (processInfo.pkgName.empty() || listener == nullptr) {
306         LOGE("RegisterDeviceManagerListener error: input parameter invalid.");
307         return ERR_DM_POINT_NULL;
308     }
309     LOGI("pkgName: %{public}s", processInfo.pkgName.c_str());
310 #ifdef SUPPORT_MEMMGR
311     int pid = getpid();
312     Memory::MemMgrClient::GetInstance().SetCritical(pid, true, DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
313 #endif // SUPPORT_MEMMGR
314     std::lock_guard<std::mutex> autoLock(listenerLock_);
315     auto iter = dmListener_.find(processInfo);
316     if (iter != dmListener_.end()) {
317         LOGI("Listener already exists");
318         auto recipientIter = appRecipient_.find(processInfo);
319         if (recipientIter == appRecipient_.end()) {
320             LOGI("AppRecipient not exists");
321             dmListener_.erase(processInfo);
322         } else {
323             auto listener = iter->second;
324             auto appRecipient = recipientIter->second;
325             listener->AsObject()->RemoveDeathRecipient(appRecipient);
326             appRecipient_.erase(processInfo);
327             dmListener_.erase(processInfo);
328         }
329     }
330     sptr<AppDeathRecipient> appRecipient = sptr<AppDeathRecipient>(new AppDeathRecipient());
331     LOGI("Add death recipient.");
332     if (!listener->AsObject()->AddDeathRecipient(appRecipient)) {
333         LOGE("AddDeathRecipient Failed");
334     }
335     if (dmListener_.size() > MAX_CALLBACK_NUM || appRecipient_.size() > MAX_CALLBACK_NUM) {
336         LOGE("dmListener_ or appRecipient_ size exceed the limit!");
337         return ERR_DM_FAILED;
338     }
339     dmListener_[processInfo] = listener;
340     appRecipient_[processInfo] = appRecipient;
341     AddSystemSA(processInfo.pkgName);
342     LOGI("complete.");
343     return DM_OK;
344 }
345 
UnRegisterDeviceManagerListener(const ProcessInfo & processInfo)346 int32_t IpcServerStub::UnRegisterDeviceManagerListener(const ProcessInfo &processInfo)
347 {
348     if (processInfo.pkgName.empty()) {
349         LOGE("Invalid parameter, pkgName is empty.");
350         return ERR_DM_INPUT_PARA_INVALID;
351     }
352     LOGI("In, pkgName: %{public}s", processInfo.pkgName.c_str());
353     std::lock_guard<std::mutex> autoLock(listenerLock_);
354     auto listenerIter = dmListener_.find(processInfo);
355     if (listenerIter == dmListener_.end()) {
356         LOGI("Listener not exists");
357         return DM_OK;
358     }
359     auto recipientIter = appRecipient_.find(processInfo);
360     if (recipientIter == appRecipient_.end()) {
361         LOGI("AppRecipient not exists");
362         dmListener_.erase(processInfo);
363         return DM_OK;
364     }
365     auto listener = listenerIter->second;
366     auto appRecipient = recipientIter->second;
367     listener->AsObject()->RemoveDeathRecipient(appRecipient);
368     appRecipient_.erase(processInfo);
369     dmListener_.erase(processInfo);
370 #ifdef SUPPORT_MEMMGR
371     if (dmListener_.size() == 0) {
372         int pid = getpid();
373         Memory::MemMgrClient::GetInstance().SetCritical(pid, false, DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
374     }
375 #endif // SUPPORT_MEMMGR
376     RemoveSystemSA(processInfo.pkgName);
377     DeviceManagerService::GetInstance().RemoveNotifyRecord(processInfo);
378     return DM_OK;
379 }
380 
GetAllProcessInfo()381 std::vector<ProcessInfo> IpcServerStub::GetAllProcessInfo()
382 {
383     std::vector<ProcessInfo> processInfoVec;
384     std::lock_guard<std::mutex> autoLock(listenerLock_);
385     for (const auto &iter : dmListener_) {
386         processInfoVec.push_back(iter.first);
387     }
388     return processInfoVec;
389 }
390 
GetDmListener(ProcessInfo processInfo) const391 const sptr<IpcRemoteBroker> IpcServerStub::GetDmListener(ProcessInfo processInfo) const
392 {
393     if (processInfo.pkgName.empty()) {
394         LOGE("Invalid parameter, pkgName is empty.");
395         return nullptr;
396     }
397     std::lock_guard<std::mutex> autoLock(listenerLock_);
398     auto iter = dmListener_.find(processInfo);
399     if (iter == dmListener_.end()) {
400         return nullptr;
401     }
402     return iter->second;
403 }
404 
GetDmListenerPkgName(const wptr<IRemoteObject> & remote) const405 const ProcessInfo IpcServerStub::GetDmListenerPkgName(const wptr<IRemoteObject> &remote) const
406 {
407     ProcessInfo processInfo;
408     std::lock_guard<std::mutex> autoLock(listenerLock_);
409     for (const auto &iter : dmListener_) {
410         if ((iter.second)->AsObject() == remote.promote()) {
411             processInfo = iter.first;
412             break;
413         }
414     }
415     return processInfo;
416 }
417 
Dump(int32_t fd,const std::vector<std::u16string> & args)418 int32_t IpcServerStub::Dump(int32_t fd, const std::vector<std::u16string>& args)
419 {
420     LOGI("start.");
421     std::vector<std::string> argsStr {};
422     for (auto item : args) {
423         argsStr.emplace_back(Str16ToStr8(item));
424     }
425 
426     std::string result("");
427     int ret = DeviceManagerService::GetInstance().DmHiDumper(argsStr, result);
428     if (ret != DM_OK) {
429         LOGE("Dump error, ret = %{public}d", ret);
430     }
431 
432     ret = dprintf(fd, "%s\n", result.c_str());
433     if (ret < 0) {
434         LOGE("HiDumper dprintf error");
435         ret = ERR_DM_FAILED;
436     }
437     return ret;
438 }
439 
OnRemoteDied(const wptr<IRemoteObject> & remote)440 void AppDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
441 {
442     ProcessInfo processInfo = IpcServerStub::GetInstance().GetDmListenerPkgName(remote);
443     LOGI("AppDeathRecipient: OnRemoteDied for %{public}s", processInfo.pkgName.c_str());
444     IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo);
445     DeviceManagerService::GetInstance().ClearDiscoveryCache(processInfo);
446     DeviceManagerServiceNotify::GetInstance().ClearDiedProcessCallback(processInfo);
447     DeviceManagerService::GetInstance().ClearPublishIdCache(processInfo.pkgName);
448 }
449 
AddSystemSA(const std::string & pkgName)450 void IpcServerStub::AddSystemSA(const std::string &pkgName)
451 {
452     if (PermissionManager::GetInstance().CheckSystemSA(pkgName)) {
453         systemSA_.insert(pkgName);
454     }
455 }
456 
RemoveSystemSA(const std::string & pkgName)457 void IpcServerStub::RemoveSystemSA(const std::string &pkgName)
458 {
459     if (PermissionManager::GetInstance().CheckSystemSA(pkgName) || systemSA_.find(pkgName) != systemSA_.end()) {
460         systemSA_.erase(pkgName);
461     }
462 }
463 
GetSystemSA()464 std::set<std::string> IpcServerStub::GetSystemSA()
465 {
466     std::lock_guard<std::mutex> autoLock(listenerLock_);
467     std::set<std::string> systemSA;
468     for (const auto &item : systemSA_) {
469         systemSA.insert(item);
470     }
471     return systemSA;
472 }
473 } // namespace DistributedHardware
474 } // namespace OHOS
475