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 <arpa/inet.h>
19 #include <cerrno>
20 #include <chrono>
21 #include <cstdlib>
22 #include <cstring>
23 #include <fstream>
24 #include <iomanip>
25 #include <iostream>
26 #include <unistd.h>
27 #include <sys/reboot.h>
28 #include <sys/socket.h>
29 #include <sys/stat.h>
30 #include <sys/syscall.h>
31 #include <sys/types.h>
32 #include <vector>
33
34 #include "cJSON.h"
35 #include "init_reboot.h"
36 #include "iservice_registry.h"
37 #include "libxml/parser.h"
38 #include "libxml/tree.h"
39 #include "openssl/err.h"
40 #include "openssl/ssl.h"
41 #include "package/package.h"
42 #include "parameter.h"
43 #include "parameters.h"
44 #include "progress_thread.h"
45 #include "securec.h"
46 #include "system_ability_definition.h"
47 #include "update_service_ab_update.h"
48 #include "update_system_event.h"
49 #include "updaterkits/updaterkits.h"
50
51 namespace OHOS {
52 namespace UpdateEngine {
53 REGISTER_SYSTEM_ABILITY_BY_ID(UpdateService, UPDATE_DISTRIBUTED_SERVICE_ID, true)
54
55 constexpr int32_t PORT_NUMBER = 5022;
56 const mode_t MKDIR_MODE = 0777;
57 constexpr int32_t JSON_MAX_SIZE = 4096;
58 constexpr int32_t OS_NAME_MAX_LEN = 16;
59 constexpr int32_t DEV_NAME_MAX_LEN = 32;
60 constexpr int32_t VER_NAME_MAX_LEN = 64;
61 constexpr uint32_t MAX_PERCENT = 100;
62
63 const std::string UPDATER_PKG_NAME = "/data/ota_package/updater.zip";
64 const std::string MISC_FILE = "/dev/block/by-name/misc";
65 const std::string BASE_PATH = "/data/ota_package";
66 const std::string CMD_WIPE_DATA = "--user_wipe_data";
67 #ifndef UPDATER_UT
68 const std::string SIGNING_CERT_NAME = "/data/ota_package/signing_cert.crt";
69 #else
70 const std::string SIGNING_CERT_NAME = "/data/ota_package/signing_cert.crt";
71 #endif
72 const std::string PARAM_NAME_FOR_VERSION = "hw_sc.build.os.version";
73 const std::string DEFAULT_VERSION = "2.2.0";
74 const std::string PARAM_NAME_FOR_SEARCH = "update.serverip.search";
75 const std::string PARAM_NAME_FOR_DOWNLOAD = "update.serverip.download";
76 const std::string DEFAULT_SERVER_IP = "127.0.0.1";
77
78 OHOS::sptr<UpdateService> UpdateService::updateService_ { nullptr };
79
OnRemoteDied(const wptr<IRemoteObject> & remote)80 void UpdateService::ClientDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
81 {
82 ENGINE_LOGI("client DeathRecipient OnRemoteDied: %{public}s", upgradeInfo_.ToString().c_str());
83 sptr<UpdateService> service = UpdateService::GetInstance();
84 if (service != nullptr) {
85 service->UnregisterUpdateCallback(upgradeInfo_);
86 }
87 }
88
ClientProxy(const UpgradeInfo & info,const sptr<IUpdateCallback> & callback)89 UpdateService::ClientProxy::ClientProxy(const UpgradeInfo &info, const sptr<IUpdateCallback> &callback)
90 : proxy_(callback)
91 {
92 ENGINE_LOGI("UpdateService::ClientProxy constructor");
93 auto clientDeathRecipient = new (std::nothrow) ClientDeathRecipient(info);
94 if (clientDeathRecipient != nullptr) {
95 deathRecipient_ = sptr<ClientDeathRecipient>(clientDeathRecipient);
96 } else {
97 ENGINE_LOGE("UpdateService::ClientProxy, new fail");
98 }
99 }
100
operator =(const UpdateService::ClientProxy & source)101 UpdateService::ClientProxy &UpdateService::ClientProxy::operator=(const UpdateService::ClientProxy &source)
102 {
103 if (&source != this) {
104 proxy_ = source.proxy_;
105 deathRecipient_ = source.deathRecipient_;
106 }
107 return *this;
108 }
109
AddDeathRecipient()110 void UpdateService::ClientProxy::AddDeathRecipient()
111 {
112 ENGINE_LOGI("UpdateService::ClientProxy AddDeathRecipient in");
113 if (proxy_ != nullptr) {
114 auto remoteObject = proxy_->AsObject();
115 if ((remoteObject != nullptr) && (deathRecipient_ != nullptr)) {
116 remoteObject->AddDeathRecipient(deathRecipient_);
117 ENGINE_LOGI("UpdateService::ClientProxy AddDeathRecipient success");
118 }
119 }
120 }
121
RemoveDeathRecipient()122 void UpdateService::ClientProxy::RemoveDeathRecipient()
123 {
124 ENGINE_LOGI("UpdateService::ClientProxy RemoveDeathRecipient in");
125 if (proxy_ != nullptr) {
126 auto remoteObject = proxy_->AsObject();
127 if ((remoteObject != nullptr) && (deathRecipient_ != nullptr)) {
128 remoteObject->RemoveDeathRecipient(deathRecipient_);
129 ENGINE_LOGI("UpdateService::ClientProxy RemoveDeathRecipient success");
130 }
131 }
132 }
133
Get()134 sptr<IUpdateCallback> UpdateService::ClientProxy::Get()
135 {
136 return proxy_;
137 }
138
UpdateService(int32_t systemAbilityId,bool runOnCreate)139 UpdateService::UpdateService(int32_t systemAbilityId, bool runOnCreate)
140 : SystemAbility(systemAbilityId, runOnCreate)
141 {
142 InitVersionInfo(versionInfo_);
143 }
144
~UpdateService()145 UpdateService::~UpdateService()
146 {
147 ENGINE_LOGE("UpdateServerTest free now");
148 if (downloadThread_ != nullptr) {
149 downloadThread_->StopDownload();
150 delete downloadThread_;
151 downloadThread_ = nullptr;
152 }
153
154 for (auto &iter : clientProxyMap_) {
155 iter.second.RemoveDeathRecipient();
156 }
157 }
158
GetInstance()159 sptr<UpdateService> UpdateService::GetInstance()
160 {
161 return updateService_;
162 }
163
RegisterUpdateCallback(const UpgradeInfo & info,const sptr<IUpdateCallback> & updateCallback)164 int32_t UpdateService::RegisterUpdateCallback(const UpgradeInfo &info, const sptr<IUpdateCallback> &updateCallback)
165 {
166 ENGINE_LOGI("RegisterUpdateCallback");
167 UnregisterUpdateCallback(info);
168 {
169 std::lock_guard<std::mutex> lock(clientProxyMapLock_);
170 ClientProxy clientProxy(info, updateCallback);
171 clientProxy.AddDeathRecipient();
172 clientProxyMap_.insert({info, clientProxy});
173 }
174 if (!info.IsLocal()) {
175 upgradeInfo_ = info;
176 }
177 return INT_CALL_SUCCESS;
178 }
179
UnregisterUpdateCallback(const UpgradeInfo & info)180 int32_t UpdateService::UnregisterUpdateCallback(const UpgradeInfo &info)
181 {
182 ENGINE_LOGI("UnregisterUpdateCallback");
183 std::lock_guard<std::mutex> lock(clientProxyMapLock_);
184 auto iter = clientProxyMap_.find(info);
185 if (iter == clientProxyMap_.end()) {
186 return INT_CALL_SUCCESS;
187 }
188 iter->second.RemoveDeathRecipient();
189 clientProxyMap_.erase(info);
190 return INT_CALL_SUCCESS;
191 }
192
GetUpgradeCallback(const UpgradeInfo & info)193 sptr<IUpdateCallback> UpdateService::GetUpgradeCallback(const UpgradeInfo &info)
194 {
195 std::lock_guard<std::mutex> lock(clientProxyMapLock_);
196 auto iter = clientProxyMap_.find(info);
197 if (iter == clientProxyMap_.end()) {
198 return nullptr;
199 }
200 return iter->second.Get();
201 }
202
GetCheckResult(CheckResultEx & checkResult)203 void UpdateService::GetCheckResult(CheckResultEx &checkResult)
204 {
205 ENGINE_LOGI("GetCheckResult start");
206 checkResult.isExistNewVersion = versionInfo_.result[0].verifyInfo != "";
207 checkResult.newVersionInfo.versionDigestInfo.versionDigest = "versionDigest";
208
209 // packages
210 checkResult.newVersionInfo.versionComponents[0].componentType = static_cast<uint32_t>(ComponentType::OTA);
211 checkResult.newVersionInfo.versionComponents[0].upgradeAction = UpgradeAction::UPGRADE;
212 checkResult.newVersionInfo.versionComponents[0].displayVersion = versionInfo_.result[0].versionName;
213 checkResult.newVersionInfo.versionComponents[0].innerVersion = versionInfo_.result[0].versionCode;
214 checkResult.newVersionInfo.versionComponents[0].size = versionInfo_.result[0].size;
215 checkResult.newVersionInfo.versionComponents[0].effectiveMode = static_cast<size_t>(EffectiveMode::COLD);
216
217 // descriptInfo
218 checkResult.newVersionInfo.versionComponents[0].descriptionInfo.descriptionType = DescriptionType::CONTENT;
219 checkResult.newVersionInfo.versionComponents[0].descriptionInfo.content = versionInfo_.descriptInfo[0].content;
220 }
221
GetNewVersion(const UpgradeInfo & info,NewVersionInfo & newVersionInfo,BusinessError & businessError)222 int32_t UpdateService::GetNewVersion(const UpgradeInfo &info, NewVersionInfo &newVersionInfo,
223 BusinessError &businessError)
224 {
225 ENGINE_LOGI("GetNewVersion start");
226 businessError.errorNum = CallResult::SUCCESS;
227 CheckResultEx checkResult;
228 GetCheckResult(checkResult);
229 newVersionInfo = checkResult.newVersionInfo;
230
231 ENGINE_LOGI("GetNewVersion finish %{public}s", newVersionInfo.versionComponents[0].displayVersion.c_str());
232 ENGINE_LOGI("GetNewVersion componentType %{public}d", newVersionInfo.versionComponents[0].componentType);
233 ENGINE_LOGI("GetNewVersion innerVersion %{public}s", newVersionInfo.versionComponents[0].innerVersion.c_str());
234 return INT_CALL_SUCCESS;
235 }
236
GetNewVersionDescription(const UpgradeInfo & info,const VersionDigestInfo & versionDigestInfo,const DescriptionOptions & descriptionOptions,VersionDescriptionInfo & newVersionDescriptionInfo,BusinessError & businessError)237 int32_t UpdateService::GetNewVersionDescription(const UpgradeInfo &info, const VersionDigestInfo &versionDigestInfo,
238 const DescriptionOptions &descriptionOptions, VersionDescriptionInfo &newVersionDescriptionInfo,
239 BusinessError &businessError)
240 {
241 ENGINE_LOGE("GetNewVersionDescription versionDigestInfo %{public}s format %{public}d language %{public}s",
242 versionDigestInfo.versionDigest.c_str(),
243 CAST_INT(descriptionOptions.format),
244 descriptionOptions.language.c_str());
245 businessError.Build(CallResult::UN_SUPPORT, "GetNewVersionDescription unsupport");
246 return INT_CALL_SUCCESS;
247 }
248
GetCurrentVersionInfo(const UpgradeInfo & info,CurrentVersionInfo & currentVersionInfo,BusinessError & businessError)249 int32_t UpdateService::GetCurrentVersionInfo(const UpgradeInfo &info, CurrentVersionInfo ¤tVersionInfo,
250 BusinessError &businessError)
251 {
252 businessError.errorNum = CallResult::SUCCESS;
253 char osName[OS_NAME_MAX_LEN] = {0};
254 if (strcpy_s(osName, sizeof(osName), GetOSFullName()) != EOK) {
255 ENGINE_LOGE("GetOSFullName fail");
256 }
257 currentVersionInfo.osVersion = osName;
258
259 char deviceName[DEV_NAME_MAX_LEN] = {0};
260 if (strcpy_s(deviceName, sizeof(deviceName), GetProductModel()) != EOK) {
261 ENGINE_LOGE("GetProductModel fail");
262 }
263 currentVersionInfo.deviceName = deviceName;
264
265 char version[VER_NAME_MAX_LEN] = {0};
266 if (strcpy_s(version, sizeof(version), GetDisplayVersion()) != EOK) {
267 ENGINE_LOGE("GetDisplayVersion fail");
268 }
269
270 VersionComponent *versionComponent = ¤tVersionInfo.versionComponents[0];
271 versionComponent->displayVersion = version;
272 versionComponent->innerVersion = version;
273
274 versionComponent->descriptionInfo.descriptionType = DescriptionType::CONTENT;
275 versionComponent->descriptionInfo.content = versionInfo_.descriptInfo[0].content;
276 return INT_CALL_SUCCESS;
277 }
278
GetCurrentVersionDescription(const UpgradeInfo & info,const DescriptionOptions & descriptionOptions,VersionDescriptionInfo & currentVersionDescriptionInfo,BusinessError & businessError)279 int32_t UpdateService::GetCurrentVersionDescription(const UpgradeInfo &info,
280 const DescriptionOptions &descriptionOptions, VersionDescriptionInfo ¤tVersionDescriptionInfo,
281 BusinessError &businessError)
282 {
283 ENGINE_LOGE("GetCurrentVersionDescription format %{public}d language %{public}s",
284 CAST_INT(descriptionOptions.format),
285 descriptionOptions.language.c_str());
286 businessError.Build(CallResult::UN_SUPPORT, "GetCurrentVersionDescription unsupport");
287 return INT_CALL_SUCCESS;
288 }
289
GetTaskInfo(const UpgradeInfo & info,TaskInfo & taskInfo,BusinessError & businessError)290 int32_t UpdateService::GetTaskInfo(const UpgradeInfo &info, TaskInfo &taskInfo, BusinessError &businessError)
291 {
292 ENGINE_LOGI("UpdateService::GetTaskInfo");
293 businessError.errorNum = CallResult::SUCCESS;
294 CheckResultEx checkResult;
295 GetCheckResult(checkResult);
296 taskInfo.existTask = checkResult.isExistNewVersion;
297 if (!taskInfo.existTask) {
298 ENGINE_LOGI("GetTaskInfo no new version");
299 return INT_CALL_SUCCESS;
300 }
301
302 taskInfo.taskBody.versionDigestInfo.versionDigest = checkResult.newVersionInfo.versionDigestInfo.versionDigest;
303 taskInfo.taskBody.status = otaStatus_.status;
304 taskInfo.taskBody.subStatus = otaStatus_.subStatus;
305 taskInfo.taskBody.progress = otaStatus_.progress;
306 taskInfo.taskBody.errorMessages[0].errorCode = otaStatus_.errMsg[0].errorCode;
307 taskInfo.taskBody.errorMessages[0].errorMessage = otaStatus_.errMsg[0].errorMsg;
308 return INT_CALL_SUCCESS;
309 }
310
SetUpgradePolicy(const UpgradeInfo & info,const UpgradePolicy & policy,BusinessError & businessError)311 int32_t UpdateService::SetUpgradePolicy(const UpgradeInfo &info, const UpgradePolicy &policy,
312 BusinessError &businessError)
313 {
314 ENGINE_LOGI("autoDownload %{public}d installmode %{public}d startTime %{public}d endTime %{public}d",
315 policy.downloadStrategy, policy.autoUpgradeStrategy, policy.autoUpgradePeriods[0].start,
316 policy.autoUpgradePeriods[1].end);
317 businessError.errorNum = CallResult::SUCCESS;
318 policy_ = policy;
319 return INT_CALL_SUCCESS;
320 }
321
GetUpgradePolicy(const UpgradeInfo & info,UpgradePolicy & policy,BusinessError & businessError)322 int32_t UpdateService::GetUpgradePolicy(const UpgradeInfo &info, UpgradePolicy &policy, BusinessError &businessError)
323 {
324 ENGINE_LOGI("GetUpgradePolicy");
325 businessError.errorNum = CallResult::SUCCESS;
326 policy = policy_;
327 return INT_CALL_SUCCESS;
328 }
329
CheckNewVersion(const UpgradeInfo & info)330 int32_t UpdateService::CheckNewVersion(const UpgradeInfo &info)
331 {
332 upgradeStatus_ = UPDATE_STATE_CHECK_VERSION_ON;
333 otaStatus_.status = upgradeStatus_;
334 int32_t engineSocket = socket(AF_INET, SOCK_STREAM, 0);
335 ENGINE_CHECK(engineSocket >= 0, SearchCallback("socket error !", SERVER_BUSY);
336 return INT_CALL_SUCCESS, "socket error !");
337
338 std::string serverIp = OHOS::system::GetParameter(PARAM_NAME_FOR_SEARCH, DEFAULT_SERVER_IP);
339 ENGINE_LOGI("CheckNewVersion serverIp: %s ", serverIp.c_str());
340
341 sockaddr_in engineSin {};
342 engineSin.sin_family = AF_INET;
343 engineSin.sin_port = htons(PORT_NUMBER);
344 int32_t ret = inet_pton(AF_INET, serverIp.c_str(), &engineSin.sin_addr);
345 ENGINE_CHECK(ret > 0, close(engineSocket); SearchCallback("Invalid ip!", SERVER_BUSY);
346 return INT_CALL_SUCCESS, "socket error");
347
348 struct timeval tv = {TIMEOUT_FOR_CONNECT, 0};
349 setsockopt(engineSocket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval));
350 ret = connect(engineSocket, reinterpret_cast<sockaddr*>(&engineSin), sizeof(engineSin));
351 ENGINE_CHECK(ret == 0,
352 SearchCallback("Connect error !", SERVER_BUSY);
353 close(engineSocket);
354 return INT_CALL_SUCCESS, "connect error");
355 ReadDataFromSSL(engineSocket);
356 return INT_CALL_SUCCESS;
357 }
358
GetTimestamp()359 static uint64_t GetTimestamp()
360 {
361 auto now = std::chrono::system_clock::now();
362 auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
363 return millisecs.count();
364 }
365
DownloadVersion(const UpgradeInfo & info,const VersionDigestInfo & versionDigestInfo,const DownloadOptions & downloadOptions,BusinessError & businessError)366 int32_t UpdateService::DownloadVersion(const UpgradeInfo &info, const VersionDigestInfo &versionDigestInfo,
367 const DownloadOptions &downloadOptions, BusinessError &businessError)
368 {
369 ENGINE_LOGI("DownloadVersion versionDigestInfo %{public}s allowNetwork %{public}d order %{public}d",
370 versionDigestInfo.versionDigest.c_str(),
371 CAST_INT(downloadOptions.allowNetwork),
372 CAST_INT(downloadOptions.order));
373 downloadInterval_ = GetTimestamp();
374 if (access(BASE_PATH.c_str(), 0) == -1) {
375 mkdir(BASE_PATH.c_str(), MKDIR_MODE);
376 }
377
378 Progress progress0 = {0, UPDATE_STATE_DOWNLOAD_ON, ""};
379 ENGINE_CHECK(upgradeStatus_ >= UPDATE_STATE_CHECK_VERSION_SUCCESS,
380 progress0.status = UPDATE_STATE_DOWNLOAD_FAIL;
381 progress0.endReason = "Invalid status";
382 DownloadCallback(progress0);
383 return INT_CALL_SUCCESS, "Invalid status %d", upgradeStatus_);
384
385 ENGINE_CHECK(!versionInfo_.result[0].verifyInfo.empty(),
386 progress0.status = UPDATE_STATE_DOWNLOAD_FAIL;
387 progress0.endReason = "Invalid verify info";
388 DownloadCallback(progress0);
389 return INT_CALL_SUCCESS, "Invalid verify info");
390 std::string downloadFileName = BASE_PATH + "/" + versionInfo_.result[0].verifyInfo;
391 size_t localFileLength = DownloadThread::GetLocalFileLength(downloadFileName);
392 ENGINE_LOGI("Download %zu %s", localFileLength, downloadFileName.c_str());
393 if (localFileLength == versionInfo_.result[0].size && versionInfo_.result[0].size != 0) {
394 progress0.percent = DOWNLOAD_FINISH_PERCENT;
395 progress0.status = UPDATE_STATE_DOWNLOAD_SUCCESS;
396 DownloadCallback(progress0);
397 return INT_CALL_SUCCESS;
398 }
399
400 upgradeStatus_ = UPDATE_STATE_DOWNLOAD_ON;
401 if (downloadThread_ == nullptr) {
402 downloadThread_ = new DownloadThread([&](const std::string &fileName, const Progress &progress) -> int {
403 DownloadCallback(progress);
404 return INT_CALL_SUCCESS;
405 });
406 ENGINE_CHECK(downloadThread_ != nullptr,
407 progress0.status = UPDATE_STATE_DOWNLOAD_FAIL;
408 progress0.endReason = "Failed to start thread";
409 DownloadCallback(progress0);
410 return INT_CALL_SUCCESS, "Failed to start thread");
411 }
412 int32_t ret = downloadThread_->StartDownload(downloadFileName, GetDownloadServerUrl());
413 if (ret != 0) {
414 businessError.Build(CallResult::FAIL, "start download fail");
415 }
416 return INT_CALL_SUCCESS;
417 }
418
PauseDownload(const UpgradeInfo & info,const VersionDigestInfo & versionDigestInfo,const PauseDownloadOptions & pauseDownloadOptions,BusinessError & businessError)419 int32_t UpdateService::PauseDownload(const UpgradeInfo &info, const VersionDigestInfo &versionDigestInfo,
420 const PauseDownloadOptions &pauseDownloadOptions, BusinessError &businessError)
421 {
422 ENGINE_LOGE("PauseDownload versionDigestInfo %{public}s isAllowAutoResume %{public}d",
423 versionDigestInfo.versionDigest.c_str(),
424 pauseDownloadOptions.isAllowAutoResume);
425 businessError.Build(CallResult::UN_SUPPORT, "PauseDownload unsupport");
426 return INT_CALL_SUCCESS;
427 }
428
ResumeDownload(const UpgradeInfo & info,const VersionDigestInfo & versionDigestInfo,const ResumeDownloadOptions & resumeDownloadOptions,BusinessError & businessError)429 int32_t UpdateService::ResumeDownload(const UpgradeInfo &info, const VersionDigestInfo &versionDigestInfo,
430 const ResumeDownloadOptions &resumeDownloadOptions, BusinessError &businessError)
431 {
432 ENGINE_LOGE("ResumeDownload versionDigestInfo %{public}s allowNetwork %{public}d",
433 versionDigestInfo.versionDigest.c_str(),
434 CAST_INT(resumeDownloadOptions.allowNetwork));
435 businessError.Build(CallResult::UN_SUPPORT, "ResumeDownload unsupport");
436 return INT_CALL_SUCCESS;
437 }
438
DoUpdate(const UpgradeInfo & info,const VersionDigestInfo & versionDigestInfo,const UpgradeOptions & upgradeOptions,BusinessError & businessError)439 int32_t UpdateService::DoUpdate(const UpgradeInfo &info, const VersionDigestInfo &versionDigestInfo,
440 const UpgradeOptions &upgradeOptions, BusinessError &businessError)
441 {
442 ENGINE_LOGE("DoUpdate versionDigest=%{public}s UpgradeOptions %{public}d",
443 versionDigestInfo.versionDigest.c_str(),
444 CAST_INT(upgradeOptions.order));
445 if (UpdateServiceAbUpdate::IsAbUpdate()) {
446 if (upgradeOptions.order == Order::APPLY) {
447 ENGINE_LOGI("Try DoUpdate Now");
448 if (DoReboot(NULL) != 0) {
449 ENGINE_LOGE("AbUpdate DoReboot fail");
450 return INT_CALL_FAIL;
451 }
452 return INT_CALL_SUCCESS;
453 }
454 int32_t ret = UpdateServiceAbUpdate::DoAbUpdate(info, UPDATER_PKG_NAME);
455 SYS_EVENT_SYSTEM_UPGRADE(ret == INT_CALL_SUCCESS, UpdateSystemEvent::EVENT_FAILED_RESULT);
456 if (ret != INT_CALL_SUCCESS) {
457 ENGINE_LOGE("AbUpdate err=%{public}d", ret);
458 businessError.Build(CallResult::FAIL, "result is " + std::to_string(ret));
459 return INT_CALL_FAIL;
460 }
461 return INT_CALL_SUCCESS;
462 }
463 SYS_EVENT_SYSTEM_UPGRADE(0, UpdateSystemEvent::UPGRADE_START);
464 upgradeInterval_.timeStart = GetTimestamp();
465 Progress progress;
466 progress.percent = 1;
467 progress.status = UPDATE_STATE_INSTALL_ON;
468 SYS_EVENT_SYSTEM_UPGRADE(upgradeStatus_ < UPDATE_STATE_DOWNLOAD_SUCCESS, UpdateSystemEvent::EVENT_FAILED_RESULT);
469 ENGINE_CHECK(upgradeStatus_ >= UPDATE_STATE_DOWNLOAD_SUCCESS,
470 progress.endReason = "Invalid status";
471 progress.status = UPDATE_STATE_INSTALL_FAIL;
472 UpgradeCallback(progress);
473 return INT_CALL_SUCCESS, "Invalid status %d", upgradeStatus_);
474
475 progress.status = UPDATE_STATE_INSTALL_SUCCESS;
476 std::vector<std::string> updaterPkgName;
477 updaterPkgName.push_back(UPDATER_PKG_NAME);
478 bool ret = RebootAndInstallUpgradePackage(MISC_FILE, updaterPkgName);
479 SYS_EVENT_SYSTEM_UPGRADE(0, ret ? UpdateSystemEvent::EVENT_SUCCESS_RESULT : UpdateSystemEvent::EVENT_FAILED_RESULT);
480 if (!ret) {
481 ENGINE_LOGI("UpdateService::DoUpdate execute failed");
482 businessError.Build(CallResult::FAIL, "result is " + std::to_string(ret));
483 return INT_CALL_SUCCESS;
484 }
485 progress.percent = DOWNLOAD_FINISH_PERCENT;
486 UpgradeCallback(progress);
487 return INT_CALL_SUCCESS;
488 }
489
ClearError(const UpgradeInfo & info,const VersionDigestInfo & versionDigestInfo,const ClearOptions & clearOptions,BusinessError & businessError)490 int32_t UpdateService::ClearError(const UpgradeInfo &info, const VersionDigestInfo &versionDigestInfo,
491 const ClearOptions &clearOptions, BusinessError &businessError)
492 {
493 ENGINE_LOGE("ClearError, versionDigestInfo %{public}s ClearOptions %{public}d",
494 versionDigestInfo.versionDigest.c_str(),
495 CAST_INT(clearOptions.status));
496 businessError.Build(CallResult::UN_SUPPORT, "ClearError unsupport");
497 return INT_CALL_SUCCESS;
498 }
499
TerminateUpgrade(const UpgradeInfo & info,BusinessError & businessError)500 int32_t UpdateService::TerminateUpgrade(const UpgradeInfo &info, BusinessError &businessError)
501 {
502 ENGINE_LOGE("TerminateUpgrade");
503 businessError.Build(CallResult::UN_SUPPORT, "TerminateUpgrade unsupport");
504 return INT_CALL_SUCCESS;
505 }
506
SearchCallbackEx(BusinessError & businessError,CheckResultEx & checkResult)507 void UpdateService::SearchCallbackEx(BusinessError &businessError, CheckResultEx &checkResult)
508 {
509 ENGINE_LOGI("SearchCallbackEx isExistNewVersion %{public}d", checkResult.isExistNewVersion);
510 checkResultEx_ = checkResult;
511 auto updateCallback = GetUpgradeCallback(upgradeInfo_);
512 if (updateCallback == nullptr) {
513 ENGINE_LOGE("SearchCallbackEx updateCallback is null");
514 return;
515 }
516 updateCallback->OnCheckVersionDone(businessError, checkResultEx_);
517 }
518
519
SearchCallback(const std::string & msg,SearchStatus status)520 void UpdateService::SearchCallback(const std::string &msg, SearchStatus status)
521 {
522 ENGINE_LOGI("SearchCallback status:%{public}d msg:%{public}s ", status, msg.c_str());
523 versionInfo_.status = status;
524 versionInfo_.errMsg = msg;
525 if (status == HAS_NEW_VERSION || status == NO_NEW_VERSION) {
526 upgradeStatus_ = UPDATE_STATE_CHECK_VERSION_SUCCESS;
527
528 // Compare the downloaded version with the local version.
529 std::string loadVersion = OHOS::system::GetParameter(PARAM_NAME_FOR_VERSION, DEFAULT_VERSION);
530 int32_t ret = UpdateHelper::CompareVersion(versionInfo_.result[0].versionCode, loadVersion);
531 if (ret <= 0) {
532 versionInfo_.status = NO_NEW_VERSION;
533 }
534 } else {
535 upgradeStatus_ = UPDATE_STATE_CHECK_VERSION_FAIL;
536 }
537 otaStatus_.status = upgradeStatus_;
538 auto upgradeCallback = GetUpgradeCallback(upgradeInfo_);
539 if (upgradeCallback == nullptr) {
540 ENGINE_LOGE("SearchCallback upgradeCallback is null");
541 return;
542 }
543 SYS_EVENT_UPDATE_INTERVAL(0, UpdateHelper::BuildEventVersionInfo(versionInfo_),
544 UpdateSystemEvent::EVENT_CHECK_INTERVAL, checkInterval_);
545 BusinessError businessError {};
546 CheckResultEx checkResultEx {};
547 GetCheckResult(checkResultEx);
548
549 businessError.errorNum = CallResult::SUCCESS;
550 businessError.data[0].errorCode = CAST_INT(status);
551 businessError.data[0].errorMessage = msg;
552 ENGINE_LOGI("SearchCallback errorCode:%{public}d msg:%{public}s ",
553 CAST_INT(businessError.data[0].errorCode),
554 businessError.data[0].errorMessage.c_str());
555 upgradeCallback->OnCheckVersionDone(businessError, checkResultEx);
556 }
557
DownloadCallback(const Progress & progress)558 void UpdateService::DownloadCallback(const Progress &progress)
559 {
560 Progress downloadProgress {};
561 upgradeStatus_ = UPDATE_STATE_DOWNLOAD_ON;
562 if (progress.status == UPDATE_STATE_DOWNLOAD_FAIL ||
563 progress.status == UPDATE_STATE_DOWNLOAD_SUCCESS) {
564 upgradeStatus_ = progress.status;
565 }
566 downloadProgress = progress;
567
568 otaStatus_.progress = progress.percent;
569 otaStatus_.status = progress.status;
570 otaStatus_.errMsg[0].errorMsg = progress.endReason;
571
572 #ifdef UPDATER_UT
573 upgradeStatus_ = UPDATE_STATE_DOWNLOAD_SUCCESS;
574 #endif
575 std::string fileName = BASE_PATH + "/" + versionInfo_.result[0].verifyInfo;
576 ENGINE_LOGI("DownloadCallback status %{public}d %{public}d", progress.status, progress.percent);
577 if (upgradeStatus_ == UPDATE_STATE_DOWNLOAD_SUCCESS) {
578 ENGINE_LOGI("DownloadCallback fileName %{public}s %{public}s", fileName.c_str(), UPDATER_PKG_NAME.c_str());
579 if (rename(fileName.c_str(), UPDATER_PKG_NAME.c_str())) {
580 ENGINE_LOGE("Rename file fail %s", fileName.c_str());
581 remove(UPDATER_PKG_NAME.c_str());
582 downloadProgress.status = UPDATE_STATE_DOWNLOAD_FAIL;
583 } else if (!VerifyDownloadPkg(UPDATER_PKG_NAME, downloadProgress)) {
584 // If the verification fails, delete the corresponding package.
585 remove(UPDATER_PKG_NAME.c_str());
586 downloadProgress.status = UPDATE_STATE_VERIFY_FAIL;
587 }
588 }
589
590 if (downloadProgress.percent == MAX_PERCENT) {
591 downloadInterval_ = GetTimestamp();
592 SYS_EVENT_UPDATE_INTERVAL(0, UpdateHelper::BuildEventVersionInfo(versionInfo_),
593 UpdateSystemEvent::EVENT_DOWNLOAD_INTERVAL, downloadInterval_);
594 }
595 switch (downloadProgress.status) {
596 case UPDATE_STATE_DOWNLOAD_ON:
597 SendEvent(upgradeInfo_, EventId::EVENT_DOWNLOAD_UPDATE);
598 break;
599 case UPDATE_STATE_DOWNLOAD_PAUSE:
600 SendEvent(upgradeInfo_, EventId::EVENT_DOWNLOAD_PAUSE);
601 break;
602 case UPDATE_STATE_DOWNLOAD_FAIL:
603 case UPDATE_STATE_VERIFY_FAIL:
604 SendEvent(upgradeInfo_, EventId::EVENT_DOWNLOAD_FAIL);
605 break;
606 case UPDATE_STATE_DOWNLOAD_SUCCESS:
607 SendEvent(upgradeInfo_, EventId::EVENT_DOWNLOAD_SUCCESS);
608 break;
609 default:
610 ENGINE_LOGE("DownloadCallback downloadProgress error status:%d", downloadProgress.status);
611 break;
612 }
613 }
614
UpgradeCallback(const Progress & progress)615 void UpdateService::UpgradeCallback(const Progress &progress)
616 {
617 upgradeStatus_ = progress.status;
618 otaStatus_.status = progress.status;
619 ENGINE_LOGE("UpgradeCallback status %{public}d %{public}d", progress.status, progress.percent);
620
621 auto upgradeCallback = GetUpgradeCallback(upgradeInfo_);
622 if (upgradeCallback == nullptr) {
623 ENGINE_LOGE("UpgradeCallback upgradeCallback is null");
624 return;
625 }
626
627 if (progress.percent == MAX_PERCENT) {
628 upgradeInterval_.timeEnd = GetTimestamp();
629 SYS_EVENT_UPDATE_INTERVAL(0, UpdateHelper::BuildEventVersionInfo(versionInfo_),
630 UpdateSystemEvent::EVENT_UPGRADE_INTERVAL,
631 upgradeInterval_.timeEnd > upgradeInterval_.timeStart
632 ? (upgradeInterval_.timeEnd - upgradeInterval_.timeStart) : 0);
633 }
634 SendEvent(upgradeInfo_, EventId::EVENT_UPGRADE_UPDATE);
635 }
636
ReadDataFromSSL(int32_t engineSocket)637 void UpdateService::ReadDataFromSSL(int32_t engineSocket)
638 {
639 SearchStatus result = SERVER_BUSY;
640 std::string errMsg = "Couldn't connect to server";
641 std::vector<char> buffer(JSON_MAX_SIZE);
642
643 SSL_library_init();
644 OpenSSL_add_all_algorithms();
645 SSL_load_error_strings();
646 SSL_CTX* sslCtx = SSL_CTX_new(SSLv23_client_method());
647 ENGINE_CHECK(sslCtx != nullptr, return, "sslCtx is nullptr");
648 SSL *ssl = SSL_new(sslCtx);
649 ENGINE_CHECK(ssl != nullptr, SSL_CTX_free(sslCtx); return, "ssl is nullptr");
650 SSL_set_fd(ssl, engineSocket);
651 int32_t ret = SSL_connect(ssl);
652 if (ret != -1) {
653 int32_t len = SSL_read(ssl, buffer.data(), JSON_MAX_SIZE);
654 if (len > 0 && ParseJsonFile(buffer, versionInfo_, downloadUrl_) == 0) {
655 result = HAS_NEW_VERSION;
656 errMsg = "";
657 } else {
658 result = SYSTEM_ERROR;
659 errMsg = "Couldn't read data";
660 }
661 } else {
662 result = SYSTEM_ERROR;
663 errMsg = "Couldn't connect to server";
664 }
665 SSL_shutdown(ssl);
666 SSL_free(ssl);
667 close(engineSocket);
668 SSL_CTX_free(sslCtx);
669
670 SearchCallback(errMsg, result);
671 return;
672 }
673
ParseJsonFile(const std::vector<char> & buffer,VersionInfo & info,std::string & url)674 int32_t UpdateService::ParseJsonFile(const std::vector<char> &buffer, VersionInfo &info, std::string &url)
675 {
676 ENGINE_CHECK(buffer.size() > 0, return -1, "JsonFile length must > 0");
677 cJSON *root = cJSON_Parse(buffer.data());
678 ENGINE_CHECK(root != nullptr, return -1, "Error get root");
679
680 cJSON *item = cJSON_GetObjectItem(root, "searchStatus");
681 ENGINE_CHECK(item != nullptr, cJSON_Delete(root); return -1, "Error get searchStatus");
682 info.status = static_cast<SearchStatus>(item->valueint);
683
684 item = cJSON_GetObjectItem(root, "errMsg");
685 ENGINE_CHECK(item != nullptr, cJSON_Delete(root); return -1, "Error get errMsg");
686 info.errMsg = item->valuestring;
687
688 cJSON *results = cJSON_GetObjectItem(root, "checkResults");
689 ENGINE_CHECK(results != nullptr, cJSON_Delete(root); return -1, "Error get checkResults");
690 int32_t ret = ReadCheckVersionResult(results, info, url);
691 ENGINE_CHECK(ret == 0, cJSON_Delete(root); return -1, "Error get checkResults");
692
693 cJSON *descriptInfo = cJSON_GetObjectItem(root, "descriptInfo");
694 ENGINE_CHECK(descriptInfo != nullptr, cJSON_Delete(root); return -1, "Error get descriptInfo");
695 ret = ReadCheckVersiondescriptInfo(descriptInfo, info);
696 ENGINE_CHECK(ret == 0, cJSON_Delete(root); return -1, "Error get descriptInfo");
697
698 cJSON_Delete(root);
699 if (info.status == HAS_NEW_VERSION) {
700 ENGINE_CHECK(!info.result[0].verifyInfo.empty() &&
701 !info.result[0].versionName.empty() &&
702 info.result[0].size > 0, return -1, "Error get descriptInfo");
703 }
704 return INT_CALL_SUCCESS;
705 }
706
ReadCheckVersionResult(const cJSON * results,VersionInfo & info,std::string & url)707 int32_t UpdateService::ReadCheckVersionResult(const cJSON* results, VersionInfo &info, std::string &url)
708 {
709 size_t number = (size_t)cJSON_GetArraySize(results);
710 for (size_t i = 0; i < number && i < sizeof(info.result) / sizeof(info.result[0]); i++) {
711 cJSON *result = cJSON_GetArrayItem(results, i);
712 ENGINE_CHECK(result != nullptr, return -1, "Error get result");
713
714 cJSON *item = cJSON_GetObjectItem(result, "versionName");
715 ENGINE_CHECK(item != nullptr, return -1, "Error get versionName");
716 info.result[i].versionName = item->valuestring;
717
718 item = cJSON_GetObjectItem(result, "versionCode");
719 ENGINE_CHECK(item != nullptr, return -1, "Error get versionCode");
720 info.result[i].versionCode = item->valuestring;
721
722 item = cJSON_GetObjectItem(result, "verifyInfo");
723 ENGINE_CHECK(item != nullptr, return -1, "Error get verifyInfo");
724 info.result[i].verifyInfo = item->valuestring;
725
726 item = cJSON_GetObjectItem(result, "size");
727 ENGINE_CHECK(item != nullptr, return -1, "Error get size");
728 info.result[i].size = (size_t)item->valueint;
729
730 item = cJSON_GetObjectItem(result, "packageType");
731 ENGINE_CHECK(item != nullptr, return -1, "Error get packageType");
732 info.result[i].packageType = (PackageType)(item->valueint);
733
734 item = cJSON_GetObjectItem(result, "url");
735 ENGINE_CHECK(item != nullptr, return -1, "Error get url");
736 url = item->valuestring;
737
738 item = cJSON_GetObjectItem(result, "descriptPackageId");
739 ENGINE_CHECK(item != nullptr, return -1, "Error get descriptPackageId");
740 info.result[i].descriptPackageId = item->valuestring;
741 }
742 return INT_CALL_SUCCESS;
743 }
744
ReadCheckVersiondescriptInfo(const cJSON * descriptInfo,VersionInfo & info)745 int32_t UpdateService::ReadCheckVersiondescriptInfo(const cJSON *descriptInfo, VersionInfo &info)
746 {
747 size_t number = (size_t)cJSON_GetArraySize(descriptInfo);
748 for (size_t i = 0; i < number && i < sizeof(info.result) / sizeof(info.result[0]); i++) {
749 cJSON *descript = cJSON_GetArrayItem(descriptInfo, i);
750 ENGINE_CHECK(descript != nullptr, return -1, "Error get descriptInfo");
751
752 cJSON *item = cJSON_GetObjectItem(descript, "descriptionType");
753 if (item != nullptr) {
754 info.descriptInfo[i].descriptionType = static_cast<DescriptionType>(item->valueint);
755 }
756 item = cJSON_GetObjectItem(descript, "content");
757 if (item != nullptr) {
758 info.descriptInfo[i].content = item->valuestring;
759 ENGINE_LOGI(" descriptInfo content %s", info.descriptInfo[i].content.c_str());
760 }
761 }
762 return INT_CALL_SUCCESS;
763 }
764
VerifyUpgradePackage(const std::string & packagePath,const std::string & keyPath,BusinessError & businessError)765 int32_t UpdateService::VerifyUpgradePackage(const std::string &packagePath, const std::string &keyPath,
766 BusinessError &businessError)
767 {
768 businessError.errorNum = CallResult::SUCCESS;
769 int32_t ret = ::VerifyPackageWithCallback(packagePath.c_str(), keyPath.c_str(),
770 [](int32_t result, uint32_t percent) {});
771 ENGINE_LOGI("VerifyUpgradePackage %s, %s, %{public}d", packagePath.c_str(), keyPath.c_str(), ret);
772 ret = (ret == 0) ? INT_CALL_SUCCESS : INT_CALL_FAIL;
773 return ret;
774 }
775
VerifyDownloadPkg(const std::string & pkgName,Progress & progress)776 bool UpdateService::VerifyDownloadPkg(const std::string &pkgName, Progress &progress)
777 {
778 // Compare the downloaded version with the local version. Only update is supported.
779 std::string loadVersion = OHOS::system::GetParameter(PARAM_NAME_FOR_VERSION, DEFAULT_VERSION);
780 int32_t ret = UpdateHelper::CompareVersion(versionInfo_.result[0].versionCode, loadVersion);
781 if (ret <= 0) {
782 progress.endReason = "Update package version earlier than the local version";
783 ENGINE_LOGE("Version compare Failed local '%{public}s' server '%{public}s'",
784 loadVersion.c_str(), versionInfo_.result[0].versionCode.c_str());
785 return false;
786 }
787 ENGINE_LOGI("versionInfo_.result[0].verifyInfo %s ", versionInfo_.result[0].verifyInfo.c_str());
788 std::vector<uint8_t> digest = UpdateHelper::HexToDegist(versionInfo_.result[0].verifyInfo);
789 ret = ::VerifyPackage(pkgName.c_str(),
790 SIGNING_CERT_NAME.c_str(), versionInfo_.result[0].versionCode.c_str(), digest.data(), digest.size());
791 if (ret != 0) {
792 progress.endReason = "Upgrade package verify Failed";
793 SYS_EVENT_VERIFY_FAILED(0, UpdateHelper::BuildEventDevId(upgradeInfo_),
794 UpdateSystemEvent::EVENT_PKG_VERIFY_FAILED);
795 ENGINE_LOGE("Package %{public}s verification Failed, ret = %d", pkgName.c_str(), ret);
796 return false;
797 }
798 ENGINE_LOGE("Package verify success");
799 return true;
800 }
801
GetDownloadServerUrl() const802 std::string UpdateService::GetDownloadServerUrl() const
803 {
804 return downloadUrl_;
805 }
806
Cancel(const UpgradeInfo & info,int32_t service,BusinessError & businessError)807 int32_t UpdateService::Cancel(const UpgradeInfo &info, int32_t service, BusinessError &businessError)
808 {
809 ENGINE_LOGI("Cancel %{public}d", service);
810 businessError.errorNum = CallResult::SUCCESS;
811 if (downloadThread_ != nullptr && service == DOWNLOAD) {
812 downloadThread_->StopDownload();
813 }
814 return INT_CALL_SUCCESS;
815 }
816
FactoryReset(BusinessError & businessError)817 int32_t UpdateService::FactoryReset(BusinessError &businessError)
818 {
819 #ifndef UPDATER_UT
820 businessError.errorNum = CallResult::SUCCESS;
821 int32_t ret = RebootAndCleanUserData(MISC_FILE, CMD_WIPE_DATA) ? INT_CALL_SUCCESS : INT_CALL_FAIL;
822 ENGINE_LOGI("FactoryReset result : %{public}d", ret);
823 SYS_EVENT_SYSTEM_RESET(
824 0, ret == INT_CALL_SUCCESS ? UpdateSystemEvent::EVENT_SUCCESS_RESULT : UpdateSystemEvent::EVENT_FAILED_RESULT);
825 return ret;
826 #else
827 return INT_CALL_SUCCESS;
828 #endif
829 }
830
ApplyNewVersion(const UpgradeInfo & info,const std::string & miscFile,const std::string & packageName,BusinessError & businessError)831 int32_t UpdateService::ApplyNewVersion(const UpgradeInfo &info, const std::string &miscFile,
832 const std::string &packageName, BusinessError &businessError)
833 {
834 #ifndef UPDATER_UT
835 SYS_EVENT_SYSTEM_UPGRADE(0, UpdateSystemEvent::UPGRADE_START);
836 businessError.errorNum = CallResult::SUCCESS;
837 SendEvent(info, EventId::EVENT_UPGRADE_UPDATE);
838 std::vector<std::string> packagePath;
839 packagePath.push_back(packageName);
840 int32_t ret = RebootAndInstallUpgradePackage(miscFile, packagePath) ? INT_CALL_SUCCESS : INT_CALL_FAIL;
841 ENGINE_LOGI("ApplyNewVersion result : %{public}d", ret);
842 SendEvent(info, ret == INT_CALL_SUCCESS ? EventId::EVENT_UPGRADE_SUCCESS : EventId::EVENT_UPGRADE_FAIL);
843 SYS_EVENT_SYSTEM_UPGRADE(
844 0, ret == INT_CALL_SUCCESS ? UpdateSystemEvent::EVENT_SUCCESS_RESULT : UpdateSystemEvent::EVENT_FAILED_RESULT);
845 return ret;
846 #else
847 return INT_CALL_SUCCESS;
848 #endif
849 }
850
InitVersionInfo(VersionInfo & versionInfo) const851 void UpdateService::InitVersionInfo(VersionInfo &versionInfo) const
852 {
853 versionInfo.status = HAS_NEW_VERSION;
854 std::string versionName = OHOS::system::GetParameter(PARAM_NAME_FOR_VERSION, DEFAULT_VERSION);
855 if (versionName.empty()) {
856 versionInfo.status = SYSTEM_ERROR;
857 versionInfo.errMsg = "Can not get local version";
858 }
859
860 size_t i;
861 for (i = 0; i < sizeof(versionInfo.result) / sizeof(versionInfo.result[0]); i++) {
862 versionInfo.result[i].size = 0;
863 versionInfo.result[i].packageType = PACKAGE_TYPE_NORMAL;
864 versionInfo.result[i].versionName = versionName;
865 versionInfo.result[i].versionCode = "";
866 versionInfo.result[i].verifyInfo = "";
867 versionInfo.result[i].descriptPackageId = "";
868 }
869 for (i = 0; i < sizeof(versionInfo.descriptInfo) / sizeof(versionInfo.descriptInfo[0]); i++) {
870 versionInfo.descriptInfo[i].content = "";
871 versionInfo.descriptInfo[i].descriptionType = DescriptionType::CONTENT;
872 }
873 }
874
SetCheckInterval(uint64_t interval)875 void UpdateService::SetCheckInterval(uint64_t interval)
876 {
877 checkInterval_ = interval;
878 }
879
SetDownloadInterval(uint64_t interval)880 void UpdateService::SetDownloadInterval(uint64_t interval)
881 {
882 downloadInterval_ = interval;
883 }
884
GetCheckInterval()885 uint64_t UpdateService::GetCheckInterval()
886 {
887 return checkInterval_;
888 }
889
GetDownloadInterval()890 uint64_t UpdateService::GetDownloadInterval()
891 {
892 return downloadInterval_;
893 }
894
GetUpgradeContext(std::string & devIdInfo)895 void UpdateService::GetUpgradeContext(std::string &devIdInfo)
896 {
897 devIdInfo = UpdateHelper::BuildEventDevId(upgradeInfo_);
898 }
899
BuildUpgradeInfoDump(const int fd,UpgradeInfo & info)900 void BuildUpgradeInfoDump(const int fd, UpgradeInfo &info)
901 {
902 dprintf(fd, "---------------------upgrade info--------------------\n");
903 dprintf(fd, "UpgradeApp: %s\n", info.upgradeApp.c_str());
904 dprintf(fd, "vendor: %s\n", info.businessType.vendor.c_str());
905 dprintf(fd, "subType: %d\n", static_cast<int>(info.businessType.subType));
906 }
907
BuildVersionInfoDump(const int fd,VersionInfo & ver)908 void BuildVersionInfoDump(const int fd, VersionInfo &ver)
909 {
910 dprintf(fd, "---------------------version info--------------------\n");
911 dprintf(fd, "SearchStatus: %d\n", ver.status);
912 dprintf(fd, "ErrorMsg: %s\n", ver.errMsg.c_str());
913 dprintf(fd, "PackageSize: %zu\n", ver.result[0].size);
914 dprintf(fd, "PackageType: %d\n", ver.result[0].packageType);
915 dprintf(fd, "VersionName: %s\n", ver.result[0].versionName.c_str());
916 dprintf(fd, "VersionCode: %s\n", ver.result[0].versionCode.c_str());
917 dprintf(fd, "DescriptPackageId: %s\n", ver.result[0].descriptPackageId.c_str());
918 dprintf(fd, "Content: %s\n", ver.descriptInfo[0].content.c_str());
919 }
920
BuildTaskInfoDump(const int fd)921 void BuildTaskInfoDump(const int fd)
922 {
923 sptr<UpdateService> service = UpdateService::GetInstance();
924 if (service == nullptr) {
925 ENGINE_LOGI("BuildTaskInfoDump no instance");
926 return;
927 }
928
929 TaskInfo taskInfo;
930 BusinessError businessError;
931 UpgradeInfo upgradeInfo;
932 service->GetTaskInfo(upgradeInfo, taskInfo, businessError);
933 if (!taskInfo.existTask) {
934 dprintf(fd, "TaskInfo is empty\n");
935 return;
936 }
937
938 dprintf(fd, "---------------------OTA status info--------------------\n");
939 dprintf(fd, "Progress: %d\n", taskInfo.taskBody.progress);
940 dprintf(fd, "UpgradeStatus: %d\n", taskInfo.taskBody.status);
941 dprintf(fd, "SubStatus: %d\n", taskInfo.taskBody.subStatus);
942 dprintf(fd, "ErrorCode: %d\n", taskInfo.taskBody.errorMessages[0].errorCode);
943 dprintf(fd, "ErrorMsg: %s\n", taskInfo.taskBody.errorMessages[0].errorMessage.c_str());
944 }
945
DumpUpgradeCallback(const int fd)946 void UpdateService::DumpUpgradeCallback(const int fd)
947 {
948 dprintf(fd, "---------------------callback info--------------------\n");
949 for (const auto &iter : clientProxyMap_) {
950 const UpgradeInfo& info = iter.first;
951 dprintf(fd, "%s\n", info.ToString().c_str());
952 }
953 }
954
Dump(int fd,const std::vector<std::u16string> & args)955 int UpdateService::Dump(int fd, const std::vector<std::u16string> &args)
956 {
957 if (fd < 0) {
958 ENGINE_LOGI("HiDumper handle invalid");
959 return -1;
960 }
961
962 if (args.size() == 0) {
963 BuildUpgradeInfoDump(fd, upgradeInfo_);
964 BuildVersionInfoDump(fd, versionInfo_);
965 BuildTaskInfoDump(fd);
966 DumpUpgradeCallback(fd);
967 } else {
968 dprintf(fd, "input error, no parameters required\n");
969 }
970 return INT_CALL_SUCCESS;
971 }
972
OnStart()973 void UpdateService::OnStart()
974 {
975 ENGINE_LOGI("UpdaterService OnStart");
976 bool res = Publish(this);
977 if (!res) {
978 ENGINE_LOGI("UpdaterService OnStart failed");
979 return;
980 }
981 updateService_ = this;
982 if (updateService_ == nullptr) {
983 ENGINE_LOGE("updateService_ null");
984 }
985 return;
986 }
987
OnStop()988 void UpdateService::OnStop()
989 {
990 ENGINE_LOGI("UpdaterService OnStop");
991 }
992
SendEvent(const UpgradeInfo & upgradeInfo,EventId eventId)993 void UpdateService::SendEvent(const UpgradeInfo &upgradeInfo, EventId eventId)
994 {
995 auto upgradeCallback = GetUpgradeCallback(upgradeInfo);
996 ENGINE_CHECK(upgradeCallback != nullptr, return, "SendEvent Error, upgradeCallback is nullptr");
997
998 ENGINE_LOGI("SendEvent %{public}d", CAST_INT(eventId));
999 TaskInfo taskInfo;
1000 BusinessError businessError;
1001 GetTaskInfo(upgradeInfo, taskInfo, businessError);
1002
1003 EventInfo eventInfo(eventId, taskInfo.taskBody);
1004 upgradeCallback->OnEvent(eventInfo);
1005 }
1006 } // namespace UpdateEngine
1007 } // namespace OHOS
1008