1/*
2 * Copyright (c) 2021 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 "update_service.h"
17
18#include <dlfcn.h>
19#include <unistd.h>
20#include <updater_sa_ipc_interface_code.h>
21
22#include "iservice_registry.h"
23#include "system_ability_definition.h"
24
25#include "access_manager.h"
26#include "dupdate_net_manager.h"
27#include "config_parse.h"
28#include "firmware_common.h"
29#include "firmware_manager.h"
30#include "startup_manager.h"
31#include "update_log.h"
32#include "update_service_cache.h"
33#include "update_service_local_updater.h"
34#include "update_service_restorer.h"
35#include "update_service_util.h"
36
37#include "update_service_module.h"
38#include "module_manager.h"
39
40namespace OHOS {
41namespace UpdateEngine {
42REGISTER_SYSTEM_ABILITY_BY_ID(UpdateService, UPDATE_DISTRIBUTED_SERVICE_ID, true)
43
44OHOS::sptr<UpdateService> UpdateService::updateService_ { nullptr };
45
46void UpdateService::ClientDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
47{
48    ENGINE_LOGI("client DeathRecipient OnRemoteDied: %{public}s", upgradeInfo_.ToString().c_str());
49    sptr<UpdateService> service = UpdateService::GetInstance();
50    if (service != nullptr) {
51        service->UnregisterUpdateCallback(upgradeInfo_);
52    }
53}
54
55UpdateService::ClientProxy::ClientProxy(const UpgradeInfo &info, const sptr<IUpdateCallback> &callback)
56    : proxy_(callback)
57{
58    ENGINE_LOGI("UpdateService::ClientProxy constructor");
59    auto clientDeathRecipient = new (std::nothrow) ClientDeathRecipient(info);
60    if (clientDeathRecipient != nullptr) {
61        deathRecipient_ = sptr<ClientDeathRecipient>(clientDeathRecipient);
62    } else {
63        ENGINE_LOGE("UpdateService::ClientProxy, new fail");
64    }
65}
66
67void UpdateService::ClientProxy::AddDeathRecipient()
68{
69    ENGINE_LOGI("UpdateService::ClientProxy AddDeathRecipient in");
70    if (proxy_ != nullptr) {
71        auto remoteObject = proxy_->AsObject();
72        if ((remoteObject != nullptr) && (deathRecipient_ != nullptr)) {
73            remoteObject->AddDeathRecipient(deathRecipient_);
74            ENGINE_LOGI("UpdateService::ClientProxy AddDeathRecipient success");
75        }
76    }
77}
78
79void UpdateService::ClientProxy::RemoveDeathRecipient()
80{
81    ENGINE_LOGI("UpdateService::ClientProxy RemoveDeathRecipient in");
82    if (proxy_ != nullptr) {
83        auto remoteObject = proxy_->AsObject();
84        if ((remoteObject != nullptr) && (deathRecipient_ != nullptr)) {
85            remoteObject->RemoveDeathRecipient(deathRecipient_);
86            ENGINE_LOGI("UpdateService::ClientProxy RemoveDeathRecipient success");
87        }
88    }
89}
90
91sptr<IUpdateCallback> UpdateService::ClientProxy::Get()
92{
93    return proxy_;
94}
95
96UpdateService::UpdateService(int32_t systemAbilityId, bool runOnCreate)
97    : SystemAbility(systemAbilityId, runOnCreate)
98{
99    updateImplMgr_ = std::make_shared<UpdateServiceImplManager>();
100}
101
102UpdateService::~UpdateService()
103{
104    ENGINE_LOGI("UpdateServerTest free now");
105    for (auto &iter : clientProxyMap_) {
106        iter.second.RemoveDeathRecipient();
107    }
108}
109
110sptr<UpdateService> UpdateService::GetInstance()
111{
112    return updateService_;
113}
114
115int32_t UpdateService::RegisterUpdateCallback(const UpgradeInfo &info, const sptr<IUpdateCallback> &updateCallback)
116{
117    ENGINE_LOGI("RegisterUpdateCallback");
118    UnregisterUpdateCallback(info);
119    {
120        std::lock_guard<std::mutex> lock(clientProxyMapLock_);
121        ClientProxy clientProxy(info, updateCallback);
122        clientProxy.AddDeathRecipient();
123        clientProxyMap_.insert({info, clientProxy});
124    }
125    if (!info.IsLocal()) {
126        UpdateServiceCache::SetUpgradeInfo(info);
127    }
128    DelayedSingleton<AccessManager>::GetInstance()->SetRemoteIdle(clientProxyMap_.empty());
129    return INT_CALL_SUCCESS;
130}
131
132int32_t UpdateService::UnregisterUpdateCallback(const UpgradeInfo &info)
133{
134    ENGINE_LOGI("UnregisterUpdateCallback");
135    std::lock_guard<std::mutex> lock(clientProxyMapLock_);
136    auto iter = clientProxyMap_.find(info);
137    if (iter == clientProxyMap_.end()) {
138        return INT_CALL_SUCCESS;
139    }
140    iter->second.RemoveDeathRecipient();
141    clientProxyMap_.erase(info);
142    DelayedSingleton<AccessManager>::GetInstance()->SetRemoteIdle(clientProxyMap_.empty());
143    return INT_CALL_SUCCESS;
144}
145
146sptr<IUpdateCallback> UpdateService::GetUpgradeCallback(const UpgradeInfo &info)
147{
148    std::lock_guard<std::mutex> lock(clientProxyMapLock_);
149    auto iter = clientProxyMap_.find(info);
150    if (iter == clientProxyMap_.end()) {
151        return nullptr;
152    }
153    return iter->second.Get();
154}
155
156int32_t UpdateService::GetNewVersionInfo(const UpgradeInfo &info, NewVersionInfo &newVersionInfo,
157    BusinessError &businessError)
158{
159    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
160    if (onlineUpdater == nullptr) {
161        ENGINE_LOGI("GetNewVersionInfo onlineUpdater null");
162        return INT_CALL_FAIL;
163    }
164    return onlineUpdater->GetNewVersionInfo(info, newVersionInfo, businessError);
165}
166
167int32_t UpdateService::GetNewVersionDescription(const UpgradeInfo &info, const VersionDigestInfo &versionDigestInfo,
168    const DescriptionOptions &descriptionOptions, VersionDescriptionInfo &newVersionDescriptionInfo,
169    BusinessError &businessError)
170{
171    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
172    if (onlineUpdater == nullptr) {
173        ENGINE_LOGI("GetNewVersionDescription onlineUpdater null");
174        return INT_CALL_FAIL;
175    }
176    return onlineUpdater->GetNewVersionDescription(info, versionDigestInfo, descriptionOptions,
177        newVersionDescriptionInfo, businessError);
178}
179
180int32_t UpdateService::GetCurrentVersionInfo(const UpgradeInfo &info, CurrentVersionInfo &currentVersionInfo,
181    BusinessError &businessError)
182{
183    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
184    if (onlineUpdater == nullptr) {
185        ENGINE_LOGI("GetCurrentVersionInfo onlineUpdater null");
186        return INT_CALL_FAIL;
187    }
188    return onlineUpdater->GetCurrentVersionInfo(info, currentVersionInfo, businessError);
189}
190
191int32_t UpdateService::GetCurrentVersionDescription(const UpgradeInfo &info,
192    const DescriptionOptions &descriptionOptions, VersionDescriptionInfo &currentVersionDescriptionInfo,
193    BusinessError &businessError)
194{
195    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
196    if (onlineUpdater == nullptr) {
197        ENGINE_LOGI("GetCurrentVersionDescription onlineUpdater null");
198        return INT_CALL_FAIL;
199    }
200    return onlineUpdater->GetCurrentVersionDescription(info, descriptionOptions, currentVersionDescriptionInfo,
201        businessError);
202}
203
204int32_t UpdateService::GetTaskInfo(const UpgradeInfo &info, TaskInfo &taskInfo, BusinessError &businessError)
205{
206    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
207    if (onlineUpdater == nullptr) {
208        ENGINE_LOGI("GetTaskInfo onlineUpdater null");
209        return INT_CALL_FAIL;
210    }
211    return onlineUpdater->GetTaskInfo(info, taskInfo, businessError);
212}
213
214int32_t UpdateService::SetUpgradePolicy(const UpgradeInfo &info, const UpgradePolicy &policy,
215    BusinessError &businessError)
216{
217    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
218    if (onlineUpdater == nullptr) {
219        ENGINE_LOGI("SetUpgradePolicy onlineUpdater null");
220        return INT_CALL_FAIL;
221    }
222    return onlineUpdater->SetUpgradePolicy(info, policy, businessError);
223}
224
225int32_t UpdateService::GetUpgradePolicy(const UpgradeInfo &info, UpgradePolicy &policy, BusinessError &businessError)
226{
227    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
228    if (onlineUpdater == nullptr) {
229        ENGINE_LOGI("GetUpgradePolicy onlineUpdater null");
230        return INT_CALL_FAIL;
231    }
232    return onlineUpdater->GetUpgradePolicy(info, policy, businessError);
233}
234
235int32_t UpdateService::CheckNewVersion(const UpgradeInfo &info, BusinessError &businessError, CheckResult &checkResult)
236{
237    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
238    if (onlineUpdater == nullptr) {
239        ENGINE_LOGI("CheckNewVersion onlineUpdater null");
240        return INT_CALL_FAIL;
241    }
242    return onlineUpdater->CheckNewVersion(info, businessError, checkResult);
243}
244
245int32_t UpdateService::Download(const UpgradeInfo &info, const VersionDigestInfo &versionDigestInfo,
246    const DownloadOptions &downloadOptions, BusinessError &businessError)
247{
248    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
249    if (onlineUpdater == nullptr) {
250        ENGINE_LOGI("Download onlineUpdater null");
251        return INT_CALL_FAIL;
252    }
253    return onlineUpdater->Download(info, versionDigestInfo, downloadOptions, businessError);
254}
255
256int32_t UpdateService::PauseDownload(const UpgradeInfo &info, const VersionDigestInfo &versionDigestInfo,
257    const PauseDownloadOptions &pauseDownloadOptions, BusinessError &businessError)
258{
259    ENGINE_LOGI("PauseDownload");
260    businessError.errorNum = CallResult::SUCCESS;
261    businessError.Build(CallResult::UN_SUPPORT, "PauseDownload unsupport");
262    return INT_CALL_SUCCESS;
263}
264
265int32_t UpdateService::ResumeDownload(const UpgradeInfo &info, const VersionDigestInfo &versionDigestInfo,
266    const ResumeDownloadOptions &resumeDownloadOptions, BusinessError &businessError)
267{
268    ENGINE_LOGI("ResumeDownload allowNetwork:%{public}d", CAST_INT(resumeDownloadOptions.allowNetwork));
269    businessError.Build(CallResult::UN_SUPPORT, "ResumeDownload unsupport");
270    return INT_CALL_SUCCESS;
271}
272
273int32_t UpdateService::Upgrade(const UpgradeInfo &info, const VersionDigestInfo &versionDigestInfo,
274    const UpgradeOptions &upgradeOptions, BusinessError &businessError)
275{
276    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
277    if (onlineUpdater == nullptr) {
278        ENGINE_LOGI("Upgrade onlineUpdater null");
279        return INT_CALL_FAIL;
280    }
281    return onlineUpdater->Upgrade(info, versionDigestInfo, upgradeOptions, businessError);
282}
283
284int32_t UpdateService::ClearError(const UpgradeInfo &info, const VersionDigestInfo &versionDigestInfo,
285    const ClearOptions &clearOptions, BusinessError &businessError)
286{
287    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
288    if (onlineUpdater == nullptr) {
289        ENGINE_LOGI("ClearError onlineUpdater null");
290        return INT_CALL_FAIL;
291    }
292    return onlineUpdater->ClearError(info, versionDigestInfo, clearOptions, businessError);
293}
294
295int32_t UpdateService::TerminateUpgrade(const UpgradeInfo &info, BusinessError &businessError)
296{
297    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
298    if (onlineUpdater == nullptr) {
299        ENGINE_LOGI("TerminateUpgrade onlineUpdater null");
300        return INT_CALL_FAIL;
301    }
302    return onlineUpdater->TerminateUpgrade(info, businessError);
303}
304
305int32_t UpdateService::Cancel(const UpgradeInfo &info, int32_t service, BusinessError &businessError)
306{
307    sptr<IServiceOnlineUpdater> onlineUpdater = updateImplMgr_->GetOnlineUpdater(info);
308    if (onlineUpdater == nullptr) {
309        ENGINE_LOGI("Cancel onlineUpdater null");
310        return INT_CALL_FAIL;
311    }
312    return onlineUpdater->Cancel(info, service, businessError);
313}
314
315int32_t UpdateService::FactoryReset(BusinessError &businessError)
316{
317    sptr<UpdateServiceRestorer> restorer = new UpdateServiceRestorer();
318    if (restorer == nullptr) {
319        ENGINE_LOGI("FactoryReset restorer null");
320        return INT_CALL_FAIL;
321    }
322    return restorer->FactoryReset(businessError);
323}
324
325int32_t UpdateService::ApplyNewVersion(const UpgradeInfo &info, const std::string &miscFile,
326    const std::vector<std::string> &packageNames, BusinessError &businessError)
327{
328    sptr<UpdateServiceLocalUpdater> localUpdater = new UpdateServiceLocalUpdater();
329    if (localUpdater == nullptr) {
330        ENGINE_LOGI("FactoryReset localUpdater null");
331        return INT_CALL_FAIL;
332    }
333    return localUpdater->ApplyNewVersion(info, miscFile, packageNames, businessError);
334}
335
336int32_t UpdateService::VerifyUpgradePackage(const std::string &packagePath, const std::string &keyPath,
337    BusinessError &businessError)
338{
339    sptr<UpdateServiceLocalUpdater> localUpdater = new UpdateServiceLocalUpdater();
340    if (localUpdater == nullptr) {
341        ENGINE_LOGI("FactoryReset localUpdater null");
342        return INT_CALL_FAIL;
343    }
344    return localUpdater->VerifyUpgradePackage(packagePath, keyPath, businessError);
345}
346
347void BuildUpgradeInfoDump(const int fd, UpgradeInfo &info)
348{
349    dprintf(fd, "---------------------upgrade info info--------------------\n");
350    dprintf(fd, "UpgradeApp: %s\n", info.upgradeApp.c_str());
351    dprintf(fd, "vendor: %s\n", info.businessType.vendor.c_str());
352    dprintf(fd, "subType: %d\n", static_cast<int>(info.businessType.subType));
353}
354
355void BuildVersionInfoDump(const int fd, const CheckResult &checkResult)
356{
357    dprintf(fd, "---------------------version info--------------------\n");
358    dprintf(fd, "isExistNewVersion: %d\n", checkResult.isExistNewVersion);
359    if (checkResult.newVersionInfo.versionComponents.empty()) {
360        return;
361    }
362    dprintf(fd, "PackageSize: %zu\n", static_cast<size_t>(checkResult.newVersionInfo.versionComponents[0].size));
363    dprintf(fd, "ComponentType: %d\n", checkResult.newVersionInfo.versionComponents[0].componentType);
364    dprintf(fd, "UpgradeAction: %s\n", checkResult.newVersionInfo.versionComponents[0].upgradeAction.c_str());
365    dprintf(fd, "DisplayVersion: %s\n", checkResult.newVersionInfo.versionComponents[0].displayVersion.c_str());
366    dprintf(fd, "InnerVersion: %s\n", checkResult.newVersionInfo.versionComponents[0].innerVersion.c_str());
367    dprintf(fd, "Content: %s\n", checkResult.newVersionInfo.versionComponents[0].descriptionInfo.content.c_str());
368}
369
370void BuildTaskInfoDump(const int fd)
371{
372    sptr<UpdateService> service = UpdateService::GetInstance();
373    if (service == nullptr) {
374        ENGINE_LOGI("BuildTaskInfoDump no instance");
375        return;
376    }
377
378    TaskInfo taskInfo;
379    BusinessError businessError;
380    UpgradeInfo upgradeInfo;
381    service->GetTaskInfo(upgradeInfo, taskInfo, businessError);
382    if (!taskInfo.existTask) {
383        dprintf(fd, "TaskInfo is empty\n");
384        return;
385    }
386
387    dprintf(fd, "---------------------OTA status info--------------------\n");
388    dprintf(fd, "Progress: %d\n", taskInfo.taskBody.progress);
389    dprintf(fd, "UpgradeStatus: %d\n", taskInfo.taskBody.status);
390    dprintf(fd, "SubStatus: %d\n", taskInfo.taskBody.subStatus);
391    for (auto &iter : taskInfo.taskBody.errorMessages) {
392        dprintf(fd, "ErrorCode: %d\n", iter.errorCode);
393        dprintf(fd, "ErrorMsg: %s\n", iter.errorMessage.c_str());
394    }
395}
396
397void UpdateService::DumpUpgradeCallback(const int fd)
398{
399    dprintf(fd, "---------------------callback info--------------------\n");
400    for (const auto &iter : clientProxyMap_) {
401        const UpgradeInfo& info = iter.first;
402        dprintf(fd, "%s\n", info.ToString().c_str());
403    }
404}
405
406int UpdateService::Dump(int fd, const std::vector<std::u16string> &args)
407{
408    if (!ModuleManager::GetInstance().IsModuleLoaded()) {
409        if (fd < 0) {
410            ENGINE_LOGI("HiDumper handle invalid");
411            return -1;
412        }
413
414        if (args.size() == 0) {
415            UpgradeInfo upgradeInfo = UpdateServiceCache::GetUpgradeInfo(BusinessSubType::FIRMWARE);
416            BuildUpgradeInfoDump(fd, upgradeInfo);
417            BuildTaskInfoDump(fd);
418            DumpUpgradeCallback(fd);
419        } else {
420            dprintf(fd, "input error, no parameters required\n");
421        }
422        return 0;
423    } else {
424        return ModuleManager::GetInstance().HandleDumpFunc("Dump", fd, args);
425    }
426}
427
428void UpdateService::OnStart(const SystemAbilityOnDemandReason &startReason)
429{
430    ENGINE_LOGI("UpdaterService oh OnStart, startReason name %{public}s, id %{public}d, value %{public}s",
431        startReason.GetName().c_str(), CAST_INT(startReason.GetId()), startReason.GetValue().c_str());
432    updateService_ = this;
433    if (updateService_ == nullptr) {
434        ENGINE_LOGE("updateService_ null");
435    }
436
437    DelayedSingleton<ConfigParse>::GetInstance()->LoadConfigInfo(); // 启动读取配置信息
438    std::string libPath = DelayedSingleton<ConfigParse>::GetInstance()->GetModuleLibPath();
439    ENGINE_LOGI("GetModuleLibPath %{public}s ", libPath.c_str());
440    ModuleManager::GetInstance().LoadModule(libPath);
441
442    ENGINE_LOGI("RegisterOhFunc HandleOhRemoteRequest");
443    RegisterOhFunc();
444
445    if (!ModuleManager::GetInstance().IsModuleLoaded()) {
446        ENGINE_LOGI("IsModuleLoaded false, init updateservice_sa");
447        DelayedSingleton<NetManager>::GetInstance()->Init();
448
449        // 动态启停流程启动
450        DelayedSingleton<StartupManager>::GetInstance()->Start();
451    }
452
453    if (Publish(this)) {
454        ENGINE_LOGI("UpdaterService OnStart publish success");
455    } else {
456        ENGINE_LOGI("UpdaterService OnStart publish fail");
457    }
458
459    if (ModuleManager::GetInstance().IsModuleLoaded()) {
460        ENGINE_LOGI("IsModuleLoaded true");
461        ModuleManager::GetInstance().HandleOnStartOnStopFunc("OnStart", startReason);
462    }
463}
464
465int32_t UpdateService::OnIdle(const SystemAbilityOnDemandReason &idleReason)
466{
467    ENGINE_LOGI("UpdaterService OnIdle");
468    return ModuleManager::GetInstance().HandleOnIdleFunc("OnIdle", idleReason);
469}
470
471void UpdateService::OnStop(const SystemAbilityOnDemandReason &stopReason)
472{
473    ENGINE_LOGI("UpdaterService OnStop");
474    ModuleManager::GetInstance().HandleOnStartOnStopFunc("OnStop", stopReason);
475}
476
477int32_t HandleOhRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
478{
479    return UpdateService::GetInstance()-> HandleRemoteRequest(code, data, reply, option);
480}
481
482void UpdateService::RegisterOhFunc()
483{
484    std::vector<uint32_t> codes = {
485        CAST_UINT(UpdaterSaInterfaceCode::CHECK_VERSION),
486        CAST_UINT(UpdaterSaInterfaceCode::DOWNLOAD),
487        CAST_UINT(UpdaterSaInterfaceCode::PAUSE_DOWNLOAD),
488        CAST_UINT(UpdaterSaInterfaceCode::RESUME_DOWNLOAD),
489        CAST_UINT(UpdaterSaInterfaceCode::UPGRADE),
490        CAST_UINT(UpdaterSaInterfaceCode::CLEAR_ERROR),
491        CAST_UINT(UpdaterSaInterfaceCode::TERMINATE_UPGRADE),
492        CAST_UINT(UpdaterSaInterfaceCode::SET_POLICY),
493        CAST_UINT(UpdaterSaInterfaceCode::GET_POLICY),
494        CAST_UINT(UpdaterSaInterfaceCode::GET_NEW_VERSION),
495        CAST_UINT(UpdaterSaInterfaceCode::GET_NEW_VERSION_DESCRIPTION),
496        CAST_UINT(UpdaterSaInterfaceCode::GET_CURRENT_VERSION),
497        CAST_UINT(UpdaterSaInterfaceCode::GET_CURRENT_VERSION_DESCRIPTION),
498        CAST_UINT(UpdaterSaInterfaceCode::GET_TASK_INFO),
499        CAST_UINT(UpdaterSaInterfaceCode::REGISTER_CALLBACK),
500        CAST_UINT(UpdaterSaInterfaceCode::UNREGISTER_CALLBACK),
501        CAST_UINT(UpdaterSaInterfaceCode::CANCEL),
502        CAST_UINT(UpdaterSaInterfaceCode::FACTORY_RESET),
503        CAST_UINT(UpdaterSaInterfaceCode::APPLY_NEW_VERSION),
504        CAST_UINT(UpdaterSaInterfaceCode::VERIFY_UPGRADE_PACKAGE)
505    };
506    RegisterFunc(codes, HandleOhRemoteRequest);
507}
508} // namespace UpdateEngine
509} // namespace OHOS
510