• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 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 "request_manager_impl.h"
17 
18 #include <atomic>
19 #include <cstdint>
20 #include <memory>
21 #include <vector>
22 
23 #include "data_ability_predicates.h"
24 #include "download_server_ipc_interface_code.h"
25 #include "errors.h"
26 #include "log.h"
27 #include "rdb_errno.h"
28 #include "rdb_helper.h"
29 #include "rdb_open_callback.h"
30 #include "rdb_predicates.h"
31 #include "rdb_store.h"
32 #include "request_common.h"
33 #include "request_manager.h"
34 #include "request_running_task_count.h"
35 #include "request_service_interface.h"
36 #include "response_message_receiver.h"
37 #include "result_set.h"
38 #include "runcount_notify_stub.h"
39 #include "sys_event.h"
40 #include "system_ability_definition.h"
41 
42 namespace OHOS::Request {
43 
GetInstance()44 const std::unique_ptr<RequestManagerImpl> &RequestManagerImpl::GetInstance()
45 {
46     static std::unique_ptr<RequestManagerImpl> instance(new RequestManagerImpl());
47     return instance;
48 }
49 
SetMode(const std::string & tid,const Mode mode)50 ExceptionErrorCode RequestManagerImpl::SetMode(const std::string &tid, const Mode mode)
51 {
52     return static_cast<ExceptionErrorCode>(CallProxyMethod(&RequestServiceInterface::SetMode, tid, mode));
53 }
54 
DisableTaskNotification(const std::vector<std::string> & tids,std::vector<ExceptionErrorCode> & rets)55 ExceptionErrorCode RequestManagerImpl::DisableTaskNotification(
56     const std::vector<std::string> &tids, std::vector<ExceptionErrorCode> &rets)
57 {
58     return static_cast<ExceptionErrorCode>(
59         CallProxyMethod(&RequestServiceInterface::DisableTaskNotification, tids, rets));
60 }
61 
CreateTasks(const std::vector<Config> & configs,std::vector<TaskRet> & rets)62 ExceptionErrorCode RequestManagerImpl::CreateTasks(const std::vector<Config> &configs, std::vector<TaskRet> &rets)
63 {
64     if (configs.size() == 0) {
65         return ExceptionErrorCode::E_OK;
66     }
67     this->EnsureChannelOpen();
68     int ret = CallProxyMethod(&RequestServiceInterface::CreateTasks, configs, rets);
69     if (ret == E_OK) {
70         bool channelOpened = false;
71         for (auto taskRet : rets) {
72             if (taskRet.code != E_CHANNEL_NOT_OPEN) {
73                 continue;
74             }
75             if (!channelOpened) {
76                 this->ReopenChannel();
77                 channelOpened = true;
78             }
79             taskRet.code =
80                 static_cast<ExceptionErrorCode>(CallProxyMethod(&RequestServiceInterface::Subscribe, taskRet.tid));
81         }
82     }
83     return static_cast<ExceptionErrorCode>(ret);
84 }
85 
StartTasks(const std::vector<std::string> & tids,std::vector<ExceptionErrorCode> & rets)86 ExceptionErrorCode RequestManagerImpl::StartTasks(
87     const std::vector<std::string> &tids, std::vector<ExceptionErrorCode> &rets)
88 {
89     return static_cast<ExceptionErrorCode>(CallProxyMethod(&RequestServiceInterface::StartTasks, tids, rets));
90 }
91 
StopTasks(const std::vector<std::string> & tids,std::vector<ExceptionErrorCode> & rets)92 ExceptionErrorCode RequestManagerImpl::StopTasks(
93     const std::vector<std::string> &tids, std::vector<ExceptionErrorCode> &rets)
94 {
95     return static_cast<ExceptionErrorCode>(CallProxyMethod(&RequestServiceInterface::StopTasks, tids, rets));
96 }
97 
ResumeTasks(const std::vector<std::string> & tids,std::vector<ExceptionErrorCode> & rets)98 ExceptionErrorCode RequestManagerImpl::ResumeTasks(
99     const std::vector<std::string> &tids, std::vector<ExceptionErrorCode> &rets)
100 {
101     return static_cast<ExceptionErrorCode>(CallProxyMethod(&RequestServiceInterface::ResumeTasks, tids, rets));
102 }
103 
RemoveTasks(const std::vector<std::string> & tids,const Version version,std::vector<ExceptionErrorCode> & rets)104 ExceptionErrorCode RequestManagerImpl::RemoveTasks(
105     const std::vector<std::string> &tids, const Version version, std::vector<ExceptionErrorCode> &rets)
106 {
107     return static_cast<ExceptionErrorCode>(CallProxyMethod(&RequestServiceInterface::RemoveTasks, tids, version, rets));
108 }
109 
PauseTasks(const std::vector<std::string> & tids,const Version version,std::vector<ExceptionErrorCode> & rets)110 ExceptionErrorCode RequestManagerImpl::PauseTasks(
111     const std::vector<std::string> &tids, const Version version, std::vector<ExceptionErrorCode> &rets)
112 {
113     return static_cast<ExceptionErrorCode>(CallProxyMethod(&RequestServiceInterface::PauseTasks, tids, version, rets));
114 }
115 
QueryTasks(const std::vector<std::string> & tids,std::vector<TaskInfoRet> & rets)116 ExceptionErrorCode RequestManagerImpl::QueryTasks(const std::vector<std::string> &tids, std::vector<TaskInfoRet> &rets)
117 {
118     return static_cast<ExceptionErrorCode>(CallProxyMethod(&RequestServiceInterface::QueryTasks, tids, rets));
119 }
120 
ShowTasks(const std::vector<std::string> & tids,std::vector<TaskInfoRet> & rets)121 ExceptionErrorCode RequestManagerImpl::ShowTasks(const std::vector<std::string> &tids, std::vector<TaskInfoRet> &rets)
122 {
123     return static_cast<ExceptionErrorCode>(CallProxyMethod(&RequestServiceInterface::ShowTasks, tids, rets));
124 }
125 
TouchTasks(const std::vector<TaskIdAndToken> & tidTokens,std::vector<TaskInfoRet> & rets)126 ExceptionErrorCode RequestManagerImpl::TouchTasks(
127     const std::vector<TaskIdAndToken> &tidTokens, std::vector<TaskInfoRet> &rets)
128 {
129     return static_cast<ExceptionErrorCode>(CallProxyMethod(&RequestServiceInterface::TouchTasks, tidTokens, rets));
130 }
131 
SetMaxSpeeds(const std::vector<SpeedConfig> & speedConfig,std::vector<ExceptionErrorCode> & rets)132 ExceptionErrorCode RequestManagerImpl::SetMaxSpeeds(
133     const std::vector<SpeedConfig> &speedConfig, std::vector<ExceptionErrorCode> &rets)
134 {
135     return static_cast<ExceptionErrorCode>(CallProxyMethod(&RequestServiceInterface::SetMaxSpeeds, speedConfig, rets));
136 }
137 
Create(const Config & config,int32_t seq,std::string & tid)138 int32_t RequestManagerImpl::Create(const Config &config, int32_t seq, std::string &tid)
139 {
140     this->EnsureChannelOpen();
141 
142     int ret = CallProxyMethod(&RequestServiceInterface::Create, config, tid);
143     if (ret == E_CHANNEL_NOT_OPEN) {
144         this->ReopenChannel();
145         ret = CallProxyMethod(&RequestServiceInterface::Subscribe, tid);
146     }
147     if (ret == E_OK && config.version != Version::API10) {
148         ret = CallProxyMethod(&RequestServiceInterface::Start, tid);
149     }
150     if (ret != E_OK) {
151         REQUEST_HILOGE("Request create, seq: %{public}d, failed: %{public}d", seq, ret);
152     }
153     for (auto &file : config.files) {
154         if (file.isUserFile) {
155             if (file.fd > 0) {
156                 fdsan_close_with_tag(file.fd, REQUEST_FDSAN_TAG);
157             }
158         }
159     }
160     return ret;
161 }
162 
GetTask(const std::string & tid,const std::string & token,Config & config)163 int32_t RequestManagerImpl::GetTask(const std::string &tid, const std::string &token, Config &config)
164 {
165     REQUEST_HILOGD("GetTask in");
166     this->EnsureChannelOpen();
167     int32_t ret = CallProxyMethod(&RequestServiceInterface::GetTask, tid, token, config);
168     if (ret == E_CHANNEL_NOT_OPEN) {
169         this->ReopenChannel();
170         ret = CallProxyMethod(&RequestServiceInterface::Subscribe, tid);
171     }
172     if (ret != E_OK) {
173         REQUEST_HILOGE("Request getTask, tid: %{public}s, failed: %{public}d", tid.c_str(), ret);
174     }
175 
176     return ret;
177 }
178 
Start(const std::string & tid)179 int32_t RequestManagerImpl::Start(const std::string &tid)
180 {
181     return CallProxyMethod(&RequestServiceInterface::Start, tid);
182 }
183 
Stop(const std::string & tid)184 int32_t RequestManagerImpl::Stop(const std::string &tid)
185 {
186     return CallProxyMethod(&RequestServiceInterface::Stop, tid);
187 }
188 
Query(const std::string & tid,TaskInfo & info)189 int32_t RequestManagerImpl::Query(const std::string &tid, TaskInfo &info)
190 {
191     return CallProxyMethod(&RequestServiceInterface::Query, tid, info);
192 }
193 
Touch(const std::string & tid,const std::string & token,TaskInfo & info)194 int32_t RequestManagerImpl::Touch(const std::string &tid, const std::string &token, TaskInfo &info)
195 {
196     return CallProxyMethod(&RequestServiceInterface::Touch, tid, token, info);
197 }
198 
Search(const Filter & filter,std::vector<std::string> & tids)199 int32_t RequestManagerImpl::Search(const Filter &filter, std::vector<std::string> &tids)
200 {
201     return CallProxyMethod(&RequestServiceInterface::Search, filter, tids);
202 }
203 
Show(const std::string & tid,TaskInfo & info)204 int32_t RequestManagerImpl::Show(const std::string &tid, TaskInfo &info)
205 {
206     return CallProxyMethod(&RequestServiceInterface::Show, tid, info);
207 }
208 
Pause(const std::string & tid,const Version version)209 int32_t RequestManagerImpl::Pause(const std::string &tid, const Version version)
210 {
211     return CallProxyMethod(&RequestServiceInterface::Pause, tid, version);
212 }
213 
QueryMimeType(const std::string & tid,std::string & mimeType)214 int32_t RequestManagerImpl::QueryMimeType(const std::string &tid, std::string &mimeType)
215 {
216     return CallProxyMethod(&RequestServiceInterface::QueryMimeType, tid, mimeType);
217 }
218 
Remove(const std::string & tid,const Version version)219 int32_t RequestManagerImpl::Remove(const std::string &tid, const Version version)
220 {
221     auto proxy = this->GetRequestServiceProxy(false);
222     if (proxy == nullptr) {
223         REQUEST_HILOGE("Get service proxy failed");
224         return E_SERVICE_ERROR;
225     }
226     return proxy->Remove(tid, version);
227 }
228 
Resume(const std::string & tid)229 int32_t RequestManagerImpl::Resume(const std::string &tid)
230 {
231     return CallProxyMethod(&RequestServiceInterface::Resume, tid);
232 }
233 
CreateGroup(std::string & gid,const bool gauge,Notification & notification)234 int32_t RequestManagerImpl::CreateGroup(std::string &gid, const bool gauge, Notification &notification)
235 {
236     return CallProxyMethod(&RequestServiceInterface::CreateGroup, gid, gauge, notification);
237 }
AttachGroup(const std::string & gid,const std::vector<std::string> & tids)238 int32_t RequestManagerImpl::AttachGroup(const std::string &gid, const std::vector<std::string> &tids)
239 {
240     return CallProxyMethod(&RequestServiceInterface::AttachGroup, gid, tids);
241 }
DeleteGroup(const std::string & gid)242 int32_t RequestManagerImpl::DeleteGroup(const std::string &gid)
243 {
244     return CallProxyMethod(&RequestServiceInterface::DeleteGroup, gid);
245 }
246 
SetMaxSpeed(const std::string & tid,const int64_t maxSpeed)247 int32_t RequestManagerImpl::SetMaxSpeed(const std::string &tid, const int64_t maxSpeed)
248 {
249     return CallProxyMethod(&RequestServiceInterface::SetMaxSpeed, tid, maxSpeed);
250 }
251 
AddListener(const std::string & taskId,const SubscribeType & type,const std::shared_ptr<IResponseListener> & listener)252 int32_t RequestManagerImpl::AddListener(
253     const std::string &taskId, const SubscribeType &type, const std::shared_ptr<IResponseListener> &listener)
254 {
255     REQUEST_HILOGD("AddListener in, tid:%{public}s, type: %{public}d", taskId.c_str(), type);
256     std::shared_ptr<Request> task = this->GetTask(taskId);
257     if (task.get()) {
258         task->AddListener(type, listener);
259         return E_OK;
260     } else {
261         return E_OTHER;
262     }
263 }
264 
RemoveListener(const std::string & taskId,const SubscribeType & type,const std::shared_ptr<IResponseListener> & listener)265 int32_t RequestManagerImpl::RemoveListener(
266     const std::string &taskId, const SubscribeType &type, const std::shared_ptr<IResponseListener> &listener)
267 {
268     REQUEST_HILOGD("RemoveListener in, tid:%{public}s, type: %{public}d", taskId.c_str(), type);
269     std::shared_ptr<Request> task = this->GetTask(taskId);
270     if (task.get()) {
271         task->RemoveListener(type, listener);
272         return E_OK;
273     } else {
274         return E_OTHER;
275     }
276 }
277 
AddListener(const std::string & taskId,const SubscribeType & type,const std::shared_ptr<INotifyDataListener> & listener)278 int32_t RequestManagerImpl::AddListener(
279     const std::string &taskId, const SubscribeType &type, const std::shared_ptr<INotifyDataListener> &listener)
280 {
281     REQUEST_HILOGD("AddListener in, tid:%{public}s, type: %{public}d", taskId.c_str(), type);
282     std::shared_ptr<Request> task = this->GetTask(taskId);
283     if (task.get()) {
284         task->AddListener(type, listener);
285         return E_OK;
286     } else {
287         REQUEST_HILOGE("GetTask Failed");
288         return E_OTHER;
289     }
290 }
291 
RemoveListener(const std::string & taskId,const SubscribeType & type,const std::shared_ptr<INotifyDataListener> & listener)292 int32_t RequestManagerImpl::RemoveListener(
293     const std::string &taskId, const SubscribeType &type, const std::shared_ptr<INotifyDataListener> &listener)
294 {
295     REQUEST_HILOGD("RemoveListener in, tid:%{public}s, type: %{public}d", taskId.c_str(), type);
296     std::shared_ptr<Request> task = this->GetTask(taskId);
297     if (task.get()) {
298         task->RemoveListener(type, listener);
299         return E_OK;
300     } else {
301         return E_OTHER;
302     }
303 }
304 
RemoveAllListeners(const std::string & taskId)305 void RequestManagerImpl::RemoveAllListeners(const std::string &taskId)
306 {
307     REQUEST_HILOGD("RemoveAllListeners in, tid:%{public}s", taskId.c_str());
308     std::lock_guard<std::mutex> lock(tasksMutex_);
309     tasks_.erase(taskId);
310 }
311 
Subscribe(const std::string & taskId)312 int32_t RequestManagerImpl::Subscribe(const std::string &taskId)
313 {
314     this->EnsureChannelOpen();
315     int ret = CallProxyMethod(&RequestServiceInterface::Subscribe, taskId);
316     if (ret == E_CHANNEL_NOT_OPEN) {
317         this->ReopenChannel();
318         ret = CallProxyMethod(&RequestServiceInterface::Subscribe, taskId);
319     }
320     return ret;
321 }
322 
Unsubscribe(const std::string & taskId)323 int32_t RequestManagerImpl::Unsubscribe(const std::string &taskId)
324 {
325     return CallProxyMethod(&RequestServiceInterface::Unsubscribe, taskId);
326 }
327 
SubRunCount(const sptr<NotifyInterface> & listener)328 int32_t RequestManagerImpl::SubRunCount(const sptr<NotifyInterface> &listener)
329 {
330     REQUEST_HILOGD("Impl SubRunCount in");
331     auto proxy = GetRequestServiceProxy(false);
332     if (proxy == nullptr) {
333         REQUEST_HILOGE("Impl SubRunCount in, get request service proxy failed.");
334         FwkRunningTaskCountManager::GetInstance()->SetSaStatus(false);
335         // Proxy does not affect sub runcount at framework.
336         return E_OK;
337     }
338     return proxy->SubRunCount(listener);
339 }
340 
UnsubRunCount()341 int32_t RequestManagerImpl::UnsubRunCount()
342 {
343     REQUEST_HILOGD("Impl UnsubRunCount in");
344     auto proxy = GetRequestServiceProxy(false);
345     if (proxy == nullptr) {
346         REQUEST_HILOGE("GetRequestServiceProxy fail.");
347         return E_SERVICE_ERROR;
348     }
349     return proxy->UnsubRunCount();
350 }
351 
EnsureChannelOpen()352 int32_t RequestManagerImpl::EnsureChannelOpen()
353 {
354     std::lock_guard<std::recursive_mutex> lock(msgReceiverMutex_);
355     if (msgReceiver_) {
356         return E_OK;
357     }
358 
359     int32_t sockFd = -1;
360     int ret = CallProxyMethod(&RequestServiceInterface::OpenChannel, sockFd);
361     if (ret != E_OK) {
362         REQUEST_HILOGE("EnsureChannelOpen failed: %{public}d, %{public}d", ret, sockFd);
363         return ret;
364     }
365     if (sockFd == -1) {
366         REQUEST_HILOGE("EnsureChannelOpen but fd -1: %{public}d", sockFd);
367         return ret;
368     }
369     fdsan_exchange_owner_tag(sockFd, 0, REQUEST_FDSAN_TAG);
370     REQUEST_HILOGD("EnsureChannelOpen ok: %{public}d", sockFd);
371     msgReceiver_ = std::make_shared<ResponseMessageReceiver>(this, sockFd);
372     msgReceiver_->BeginReceive();
373     return E_OK;
374 }
375 
GetTask(const std::string & taskId)376 std::shared_ptr<Request> RequestManagerImpl::GetTask(const std::string &taskId)
377 {
378     std::lock_guard<std::mutex> lock(tasksMutex_);
379     auto it = tasks_.find(taskId);
380     if (it != tasks_.end()) {
381         return it->second;
382     }
383 
384     auto retPair = this->tasks_.emplace(taskId, std::make_shared<Request>(taskId));
385     if (retPair.second) {
386         return retPair.first->second;
387     } else {
388         this->tasks_.erase(taskId);
389         REQUEST_HILOGE("Response Task create fail");
390         return std::shared_ptr<Request>(nullptr);
391     }
392 }
393 
OnChannelBroken()394 void RequestManagerImpl::OnChannelBroken()
395 {
396     std::lock_guard<std::recursive_mutex> lock(msgReceiverMutex_);
397     this->msgReceiver_.reset();
398 }
399 
OnResponseReceive(const std::shared_ptr<Response> & response)400 void RequestManagerImpl::OnResponseReceive(const std::shared_ptr<Response> &response)
401 {
402     std::shared_ptr<Request> task = this->GetTask(response->taskId);
403     if (task.get() == nullptr) {
404         REQUEST_HILOGE("OnResponseReceive task not found");
405         return;
406     }
407     task->OnResponseReceive(response);
408 }
409 
OnNotifyDataReceive(const std::shared_ptr<NotifyData> & notifyData)410 void RequestManagerImpl::OnNotifyDataReceive(const std::shared_ptr<NotifyData> &notifyData)
411 {
412     std::shared_ptr<Request> task = this->GetTask(std::to_string(notifyData->taskId));
413     if (task.get() == nullptr) {
414         REQUEST_HILOGE("OnNotifyDataReceive task not found");
415         return;
416     }
417     task->OnNotifyDataReceive(notifyData);
418 }
419 
OnFaultsReceive(const std::shared_ptr<int32_t> & tid,const std::shared_ptr<SubscribeType> & type,const std::shared_ptr<Reason> & reason)420 void RequestManagerImpl::OnFaultsReceive(const std::shared_ptr<int32_t> &tid,
421     const std::shared_ptr<SubscribeType> &type, const std::shared_ptr<Reason> &reason)
422 {
423     std::shared_ptr<Request> task = this->GetTask(std::to_string(*tid));
424     if (task.get() == nullptr) {
425         REQUEST_HILOGE("OnFaultsReceive task not found");
426         return;
427     }
428     task->OnFaultsReceive(tid, type, reason);
429 }
430 
OnWaitReceive(std::int32_t taskId,WaitingReason reason)431 void RequestManagerImpl::OnWaitReceive(std::int32_t taskId, WaitingReason reason)
432 {
433     std::shared_ptr<Request> task = this->GetTask(std::to_string(taskId));
434     if (task.get() == nullptr) {
435         REQUEST_HILOGE("OnWaitReceive task not found");
436         return;
437     }
438     task->OnWaitReceive(taskId, reason);
439 }
440 
GetRequestServiceProxy(bool needLoadSA)441 sptr<RequestServiceInterface> RequestManagerImpl::GetRequestServiceProxy(bool needLoadSA)
442 {
443     std::lock_guard<std::mutex> lock(serviceProxyMutex_);
444     // When SubRuncount/UnSubRuncount/RestoreSubRunCount/Remove need to get proxy but not need to load
445     if (!needLoadSA) {
446         sptr<ISystemAbilityManager> systemAbilityManager =
447             SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
448         if (systemAbilityManager == nullptr) {
449             REQUEST_HILOGE("Getting SystemAbilityManager failed.");
450             SysEventLog::SendSysEventLog(FAULT_EVENT, SAMGR_FAULT_00, "Get SAM failed");
451             return nullptr;
452         }
453         // Update the proxy to avoid holding an expired object
454         auto systemAbility = systemAbilityManager->GetSystemAbility(DOWNLOAD_SERVICE_ID, "");
455         if (systemAbility != nullptr) {
456             requestServiceProxy_ = iface_cast<RequestServiceInterface>(systemAbility);
457         } else {
458             REQUEST_HILOGI("Get SystemAbility failed.");
459         }
460         return requestServiceProxy_;
461     }
462     if (requestServiceProxy_ != nullptr) {
463         return requestServiceProxy_;
464     }
465 
466     REQUEST_HILOGI("Load System Ability");
467     sptr<ISystemAbilityManager> systemAbilityManager =
468         SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
469     if (systemAbilityManager == nullptr) {
470         REQUEST_HILOGE("Getting SystemAbilityManager failed.");
471         SysEventLog::SendSysEventLog(FAULT_EVENT, SAMGR_FAULT_00, "Get SAM failed");
472         return nullptr;
473     }
474     auto systemAbility = systemAbilityManager->LoadSystemAbility(DOWNLOAD_SERVICE_ID, LOAD_SA_TIMEOUT_MS);
475     if (systemAbility == nullptr) {
476         REQUEST_HILOGE("Load SystemAbility failed.");
477         SysEventLog::SendSysEventLog(FAULT_EVENT, SAMGR_FAULT_01, "Load SA failed");
478         return nullptr;
479     }
480     requestServiceProxy_ = iface_cast<RequestServiceInterface>(systemAbility);
481 
482     return requestServiceProxy_;
483 }
484 
SubscribeSA()485 bool RequestManagerImpl::SubscribeSA()
486 {
487     std::lock_guard<std::mutex> lock(saChangeListenerMutex_);
488     if (saChangeListener_ != nullptr) {
489         return true;
490     }
491     sptr<ISystemAbilityManager> systemAbilityManager =
492         SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
493     if (systemAbilityManager == nullptr) {
494         REQUEST_HILOGE("Getting SystemAbilityManager failed.");
495         SysEventLog::SendSysEventLog(FAULT_EVENT, SAMGR_FAULT_00, "Get SAM failed");
496         return false;
497     }
498     saChangeListener_ = new (std::nothrow) SystemAbilityStatusChangeListener();
499     if (saChangeListener_ == nullptr) {
500         REQUEST_HILOGE("Get saChangeListener_ failed.");
501         return false;
502     }
503     if (systemAbilityManager->SubscribeSystemAbility(DOWNLOAD_SERVICE_ID, saChangeListener_) != E_OK) {
504         REQUEST_HILOGE("SubscribeSystemAbility failed.");
505         SysEventLog::SendSysEventLog(FAULT_EVENT, SAMGR_FAULT_03, "Subscribe SA failed");
506         return false;
507     }
508     REQUEST_HILOGI("SubscribeSA Success");
509     return true;
510 }
511 
UnsubscribeSA()512 bool RequestManagerImpl::UnsubscribeSA()
513 {
514     std::lock_guard<std::mutex> lock(saChangeListenerMutex_);
515     if (saChangeListener_ == nullptr) {
516         return true;
517     }
518     sptr<ISystemAbilityManager> systemAbilityManager =
519         SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
520     if (systemAbilityManager == nullptr) {
521         REQUEST_HILOGE("Getting SystemAbilityManager failed.");
522         SysEventLog::SendSysEventLog(FAULT_EVENT, SAMGR_FAULT_00, "Get SAM failed");
523         return false;
524     }
525     if (systemAbilityManager->UnSubscribeSystemAbility(DOWNLOAD_SERVICE_ID, saChangeListener_) != E_OK) {
526         SysEventLog::SendSysEventLog(FAULT_EVENT, SAMGR_FAULT_04, "UnSubscribe SA failed");
527         REQUEST_HILOGE("UnsubscribeSystemAbility failed.");
528         return false;
529     }
530     saChangeListener_ = nullptr;
531 
532     // Not sure about the SA state when it was supposed to set requestServiceProxy_ to nullptr, but there
533     // was already retry logic in place when the message was sent, and also,
534     // SA accesses a low-memory framework and doesn't hang frequently.
535 
536     REQUEST_HILOGI("UnsubscribeSA Success");
537     return true;
538 }
539 
RestoreListener(void (* callback)())540 void RequestManagerImpl::RestoreListener(void (*callback)())
541 {
542     callback_ = callback;
543 }
544 
RestoreSubRunCount()545 void RequestManagerImpl::RestoreSubRunCount()
546 {
547     REQUEST_HILOGD("Restore sub run count in");
548     auto proxy = GetRequestServiceProxy(false);
549     if (proxy == nullptr) {
550         REQUEST_HILOGE("Restore sub run count, but get request service proxy fail.");
551         return;
552     }
553     auto listener = RunCountNotifyStub::GetInstance();
554     int ret = CallProxyMethod(&RequestServiceInterface::SubRunCount, listener);
555     if (ret != E_OK) {
556         REQUEST_HILOGE("Restore sub run count failed, ret: %{public}d.", ret);
557     }
558 }
559 
SystemAbilityStatusChangeListener()560 RequestManagerImpl::SystemAbilityStatusChangeListener::SystemAbilityStatusChangeListener()
561 {
562 }
563 
564 // Sometimes too slow to return.
OnAddSystemAbility(int32_t saId,const std::string & deviceId)565 void RequestManagerImpl::SystemAbilityStatusChangeListener::OnAddSystemAbility(
566     int32_t saId, const std::string &deviceId)
567 {
568     if (saId != DOWNLOAD_SERVICE_ID) {
569         REQUEST_HILOGE("SA ID is not DOWNLOAD_SERVICE_ID.");
570     }
571     REQUEST_HILOGD("SystemAbility Add.");
572     if (RequestManagerImpl::GetInstance()->callback_ != nullptr) {
573         RequestManagerImpl::GetInstance()->callback_();
574     }
575     if (FwkRunningTaskCountManager::GetInstance()->HasObserver()) {
576         RequestManagerImpl::GetInstance()->RestoreSubRunCount();
577     }
578 }
579 
OnRemoveSystemAbility(int32_t saId,const std::string & deviceId)580 void RequestManagerImpl::SystemAbilityStatusChangeListener::OnRemoveSystemAbility(
581     int32_t saId, const std::string &deviceId)
582 {
583     REQUEST_HILOGI("SystemAbility Unloaded");
584     if (saId != DOWNLOAD_SERVICE_ID) {
585         REQUEST_HILOGE("SA ID is not DOWNLOAD_SERVICE_ID.");
586     }
587     {
588         std::lock_guard<std::mutex> locks(RequestManagerImpl::GetInstance()->serviceProxyMutex_);
589         RequestManagerImpl::GetInstance()->requestServiceProxy_ = nullptr;
590     }
591     FwkRunningTaskCountManager::GetInstance()->SetCount(0);
592     FwkRunningTaskCountManager::GetInstance()->SetSaStatus(false);
593     FwkRunningTaskCountManager::GetInstance()->NotifyAllObservers();
594     std::lock_guard<std::recursive_mutex> lock(RequestManagerImpl::GetInstance()->msgReceiverMutex_);
595     if (!RequestManagerImpl::GetInstance()->msgReceiver_) {
596         return;
597     }
598     RequestManagerImpl::GetInstance()->msgReceiver_->Shutdown();
599 }
600 
LoadRequestServer()601 void RequestManagerImpl::LoadRequestServer()
602 {
603     this->GetRequestServiceProxy(true);
604 }
605 
IsSaReady()606 bool RequestManagerImpl::IsSaReady()
607 {
608     sptr<ISystemAbilityManager> systemAbilityManager =
609         SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
610     if (systemAbilityManager == nullptr) {
611         REQUEST_HILOGE("Getting SystemAbilityManager failed.");
612         SysEventLog::SendSysEventLog(FAULT_EVENT, SAMGR_FAULT_00, "Get SAM failed");
613         return false;
614     }
615     return systemAbilityManager->CheckSystemAbility(DOWNLOAD_SERVICE_ID) != nullptr;
616 }
617 
ReopenChannel()618 void RequestManagerImpl::ReopenChannel()
619 {
620     std::lock_guard<std::recursive_mutex> lock(msgReceiverMutex_);
621     if (!msgReceiver_) {
622         return;
623     }
624     msgReceiver_->Shutdown();
625     this->EnsureChannelOpen();
626 }
627 
GetNextSeq()628 int32_t RequestManagerImpl::GetNextSeq()
629 {
630     static std::atomic<int32_t> seq{ 0 };
631     return seq.fetch_add(1);
632 }
633 
634 } // namespace OHOS::Request
635