1 #include "sotauptaneclient.h"
8 #include "campaign/campaign.h"
9 #include "crypto/crypto.h"
10 #include "crypto/keymanager.h"
11 #include "initializer.h"
12 #include "logging/logging.h"
13 #include "uptane/exceptions.h"
15 #include "utilities/fault_injection.h"
16 #include "utilities/utils.h"
18 static void report_progress_cb(event::Channel *channel,
const Uptane::Target &target,
const std::string &description,
19 unsigned int progress) {
20 if (channel ==
nullptr) {
23 auto event = std::make_shared<event::DownloadProgressReport>(target, description, progress);
27 void SotaUptaneClient::addSecondary(
const std::shared_ptr<Uptane::SecondaryInterface> &sec) {
31 if (!storage->loadSecondaryInfo(serial, &info) || info.type ==
"" || info.pub_key.Type() == KeyType::kUnknown) {
33 info.hw_id = sec->getHwId();
34 info.type = sec->Type();
36 if (p.Type() != KeyType::kUnknown) {
39 storage->saveSecondaryInfo(info.serial, info.type, info.pub_key);
42 if (storage->loadEcuRegistered()) {
44 storage->loadEcuSerials(&serials);
46 if (std::find_if(serials.cbegin(), serials.cend(), secondary_comp) == serials.cend()) {
47 throw std::logic_error(
"Add new secondaries for provisioned device is not implemented yet");
51 const auto map_it = secondaries.find(serial);
52 if (map_it != secondaries.end()) {
53 throw std::runtime_error(std::string(
"Multiple secondaries found with the same serial: ") + serial.ToString());
56 secondaries.emplace(serial, sec);
59 bool SotaUptaneClient::isInstalledOnPrimary(
const Uptane::Target &target) {
60 if (target.ecus().find(primaryEcuSerial()) != target.ecus().end()) {
61 return target.MatchTarget(package_manager_->getCurrent());
66 std::vector<Uptane::Target> SotaUptaneClient::findForEcu(
const std::vector<Uptane::Target> &targets,
68 std::vector<Uptane::Target>
result;
69 for (
auto it = targets.begin(); it != targets.end(); ++it) {
70 if (it->ecus().find(ecu_id) != it->ecus().end()) {
78 LOG_INFO <<
"Installing package using " << package_manager_->name() <<
" package manager";
80 return package_manager_->install(target);
81 }
catch (std::exception &ex) {
86 void SotaUptaneClient::finalizeAfterReboot() {
89 if (!hasPendingUpdates()) {
90 LOG_DEBUG <<
"No pending updates, continuing with initialization";
94 LOG_INFO <<
"Checking for a pending update to apply for Primary ECU";
97 boost::optional<Uptane::Target> pending_target;
98 storage->loadInstalledVersions(primary_ecu_serial.ToString(),
nullptr, &pending_target);
100 if (!pending_target) {
101 LOG_ERROR <<
"No pending update for Primary ECU found, continuing with initialization";
105 LOG_INFO <<
"Pending update for Primary ECU was found, trying to apply it...";
109 if (install_res.result_code == data::ResultCode::Numeric::kNeedCompletion) {
110 LOG_INFO <<
"Pending update for Primary ECU was not applied because reboot was not detected, "
111 "continuing with initialization";
115 storage->saveEcuInstallationResult(primary_ecu_serial, install_res);
117 const std::string correlation_id = pending_target->correlation_id();
118 if (install_res.success) {
119 storage->saveInstalledVersion(primary_ecu_serial.ToString(), *pending_target, InstalledVersionUpdateMode::kCurrent);
121 report_queue->enqueue(std_::make_unique<EcuInstallationCompletedReport>(primary_ecu_serial, correlation_id,
true));
124 storage->saveInstalledVersion(primary_ecu_serial.ToString(), *pending_target, InstalledVersionUpdateMode::kNone);
125 report_queue->enqueue(std_::make_unique<EcuInstallationCompletedReport>(primary_ecu_serial, correlation_id,
false));
128 director_repo.dropTargets(*storage);
131 std::string raw_report;
132 computeDeviceInstallationResult(&ir, &raw_report);
133 storage->storeDeviceInstallationResult(ir, raw_report, correlation_id);
149 storage->saveInstalledVersion(ecu_serial.ToString(), target, InstalledVersionUpdateMode::kNone);
151 result = PackageInstall(target);
152 if (
result.result_code.num_code == data::ResultCode::Numeric::kOk) {
154 storage->saveInstalledVersion(ecu_serial.ToString(), target, InstalledVersionUpdateMode::kCurrent);
155 }
else if (
result.result_code.num_code == data::ResultCode::Numeric::kNeedCompletion) {
157 storage->saveInstalledVersion(ecu_serial.ToString(), target, InstalledVersionUpdateMode::kPending);
159 storage->saveEcuInstallationResult(ecu_serial,
result);
163 void SotaUptaneClient::reportHwInfo() {
164 Json::Value hw_info = Utils::getHardwareInfo();
165 if (!hw_info.empty()) {
166 if (hw_info != last_hw_info_reported) {
167 if (http->put(config.tls.server +
"/system_info", hw_info).isOk()) {
168 last_hw_info_reported = hw_info;
172 LOG_WARNING <<
"Unable to fetch hardware information from host system.";
176 void SotaUptaneClient::reportInstalledPackages() {
177 http->put(config.tls.server +
"/core/installed", package_manager_->getInstalledPackages());
180 void SotaUptaneClient::reportNetworkInfo() {
182 LOG_DEBUG <<
"Reporting network information";
183 Json::Value network_info = Utils::getNetworkInfo();
184 if (network_info != last_network_info_reported) {
185 HttpResponse response = http->put(config.tls.server +
"/system_info/network", network_info);
186 if (response.isOk()) {
187 last_network_info_reported = network_info;
192 LOG_DEBUG <<
"Not reporting network information because telemetry is disabled";
196 void SotaUptaneClient::reportAktualizrConfiguration() {
197 if (!config.telemetry.report_config) {
198 LOG_DEBUG <<
"Not reporting network information because telemetry is disabled";
202 LOG_DEBUG <<
"Reporting libaktualizr configuration";
203 std::stringstream conf_ss;
204 config.writeToStream(conf_ss);
205 http->post(config.tls.server +
"/system_info/config",
"application/toml", conf_ss.str());
208 Json::Value SotaUptaneClient::AssembleManifest() {
209 Json::Value manifest;
211 manifest[
"primary_ecu_serial"] = primary_ecu_serial.ToString();
214 Json::Value version_manifest;
216 Json::Value primary_manifest = uptane_manifest->assembleManifest(package_manager_->getCurrent());
217 std::vector<std::pair<Uptane::EcuSerial, int64_t>> ecu_cnt;
218 std::string report_counter;
219 if (!storage->loadEcuReportCounter(&ecu_cnt) || (ecu_cnt.size() == 0)) {
220 LOG_ERROR <<
"No ECU version report counter, please check the database!";
223 report_counter = std::to_string(ecu_cnt[0].second + 1);
224 storage->saveEcuReportCounter(ecu_cnt[0].first, ecu_cnt[0].second + 1);
226 version_manifest[primary_ecu_serial.ToString()] = uptane_manifest->sign(primary_manifest, report_counter);
228 for (
auto it = secondaries.begin(); it != secondaries.end(); it++) {
232 bool from_cache =
false;
233 if (secmanifest == Json::Value()) {
236 if (storage->loadCachedEcuManifest(ecu_serial, &cached)) {
237 LOG_WARNING <<
"Could not reach secondary " << ecu_serial <<
", sending a cached version of its manifest";
238 secmanifest = Utils::parseJSON(cached);
241 LOG_ERROR <<
"Could not fetch a valid secondary manifest from cache";
245 if (secmanifest.verifySignature(it->second->getPublicKey())) {
246 version_manifest[ecu_serial.ToString()] = secmanifest;
248 storage->storeCachedEcuManifest(ecu_serial, Utils::jsonToCanonicalStr(secmanifest));
252 LOG_ERROR <<
"Secondary manifest is corrupted or not signed, or signature is invalid manifest: " << secmanifest;
255 manifest[
"ecu_version_manifests"] = version_manifest;
258 Json::Value installation_report;
261 std::string raw_report;
262 std::string correlation_id;
263 bool has_results = storage->loadDeviceInstallationResult(&dev_result, &raw_report, &correlation_id);
265 installation_report[
"result"] = dev_result.toJson();
266 installation_report[
"raw_report"] = raw_report;
267 installation_report[
"correlation_id"] = correlation_id;
268 installation_report[
"items"] = Json::arrayValue;
270 std::vector<std::pair<Uptane::EcuSerial, data::InstallationResult>> ecu_results;
271 storage->loadEcuInstallationResults(&ecu_results);
272 for (
const auto &r : ecu_results) {
277 item[
"ecu"] = serial.ToString();
278 item[
"result"] = res.toJson();
280 installation_report[
"items"].append(item);
283 manifest[
"installation_report"][
"content_type"] =
"application/vnd.com.here.otac.installationReport.v1";
284 manifest[
"installation_report"][
"report"] = installation_report;
286 LOG_DEBUG <<
"No installation result to report in manifest";
292 bool SotaUptaneClient::hasPendingUpdates()
const {
return storage->hasPendingInstall(); }
294 void SotaUptaneClient::initialize() {
295 LOG_DEBUG <<
"Checking if device is provisioned...";
296 auto keys = std::make_shared<KeyManager>(storage, config.keymanagerConfig());
297 Initializer initializer(config.provision, storage, http, *keys, secondaries);
299 if (!initializer.isSuccessful()) {
300 throw std::runtime_error(
"Fatal error during provisioning or ECU device registration.");
304 if (!storage->loadEcuSerials(&serials) || serials.size() == 0) {
305 throw std::runtime_error(
"Unable to load ECU serials after device registration.");
308 uptane_manifest = std::make_shared<Uptane::ManifestIssuer>(keys, serials[0].first);
309 primary_ecu_serial_ = serials[0].first;
310 primary_ecu_hw_id_ = serials[0].second;
311 LOG_INFO <<
"Primary ECU serial: " << primary_ecu_serial_ <<
" with hardware ID: " << primary_ecu_hw_id_;
315 std::string device_id;
316 if (!storage->loadDeviceId(&device_id)) {
317 throw std::runtime_error(
"Unable to load device ID after device registration.");
319 LOG_INFO <<
"Device ID: " << device_id;
320 LOG_INFO <<
"Device Gateway URL: " << config.tls.server;
324 std::string not_before;
325 std::string not_after;
326 keys->getCertInfo(&subject, &issuer, ¬_before, ¬_after);
327 LOG_INFO <<
"Certificate subject: " << subject;
328 LOG_INFO <<
"Certificate issuer: " << issuer;
329 LOG_INFO <<
"Certificate valid from: " << not_before <<
" until: " << not_after;
331 LOG_DEBUG <<
"... provisioned OK";
332 finalizeAfterReboot();
335 bool SotaUptaneClient::updateDirectorMeta() {
336 if (!director_repo.updateMeta(*storage, *uptane_fetcher)) {
337 last_exception = director_repo.getLastException();
343 bool SotaUptaneClient::updateImagesMeta() {
344 if (!images_repo.updateMeta(*storage, *uptane_fetcher)) {
345 last_exception = images_repo.getLastException();
351 bool SotaUptaneClient::checkDirectorMetaOffline() {
352 if (!director_repo.checkMetaOffline(*storage)) {
353 last_exception = director_repo.getLastException();
359 bool SotaUptaneClient::checkImagesMetaOffline() {
360 if (!images_repo.checkMetaOffline(*storage)) {
361 last_exception = images_repo.getLastException();
368 std::string *raw_installation_report)
const {
371 std::string raw_ir =
"Installation succesful";
374 std::vector<std::pair<Uptane::EcuSerial, data::InstallationResult>> ecu_results;
376 if (!storage->loadEcuInstallationResults(&ecu_results)) {
379 "Unable to get installation results from ecus");
380 raw_ir =
"Failed to load ECUs' installation result";
385 std::string result_code_err_str;
387 for (
const auto &r : ecu_results) {
388 auto ecu_serial = r.first;
389 auto installation_res = r.second;
391 auto hw_id = ecuHwId(ecu_serial);
396 "Unable to get installation results from ecus");
398 raw_ir =
"Couldn't find any ECU with the given serial: " + ecu_serial.ToString();
403 if (installation_res.needCompletion()) {
405 device_installation_result =
407 "ECU needs completion/finalization to be installed: " + ecu_serial.ToString());
408 raw_ir =
"ECU needs completion/finalization to be installed: " + ecu_serial.ToString();
415 if (!installation_res.isSuccess()) {
416 std::string ecu_code_str = (*hw_id).ToString() +
":" + installation_res.result_code.toString();
417 result_code_err_str += (result_code_err_str !=
"" ?
"|" :
"") + ecu_code_str;
421 if (!result_code_err_str.empty()) {
423 device_installation_result =
425 "Installation failed on at least one of ECUs");
426 raw_ir =
"Installation failed on at least one of ECUs";
434 *
result = device_installation_result;
437 if (raw_installation_report !=
nullptr) {
438 *raw_installation_report = raw_ir;
442 bool SotaUptaneClient::getNewTargets(std::vector<Uptane::Target> *new_targets,
unsigned int *ecus_count) {
443 std::vector<Uptane::Target> targets = director_repo.getTargets().targets;
445 if (ecus_count !=
nullptr) {
450 for (
const auto &ecu : target.ecus()) {
454 auto hw_id_known = ecuHwId(ecu_serial);
456 LOG_ERROR <<
"Unknown ECU ID in director targets metadata: " << ecu_serial.ToString();
461 if (*hw_id_known != hw_id) {
462 LOG_ERROR <<
"Wrong hardware identifier for ECU " << ecu_serial.ToString();
467 boost::optional<Uptane::Target> current_version;
468 if (!storage->loadInstalledVersions(ecu_serial.ToString(), ¤t_version,
nullptr)) {
469 LOG_WARNING <<
"Could not load currently installed version for ECU ID: " << ecu_serial.ToString();
473 if (!current_version) {
474 LOG_WARNING <<
"Current version for ECU ID: " << ecu_serial.ToString() <<
" is unknown";
476 }
else if (current_version->filename() != target.filename()) {
480 if (primary_ecu_serial == ecu_serial) {
482 (config.pacman.type == PACKAGE_MANAGER_OSTREE || config.pacman.type == PACKAGE_MANAGER_OSTREEDOCKERAPP)) {
483 LOG_ERROR <<
"Cannot install a non-OSTree package on an OSTree system";
489 if (is_new && ecus_count !=
nullptr) {
495 new_targets->push_back(target);
501 std::unique_ptr<Uptane::Target> SotaUptaneClient::findTargetHelper(
const Uptane::Targets &cur_targets,
503 const int level,
const bool terminating,
504 const bool offline) {
506 const auto it = std::find_if(cur_targets.targets.cbegin(), cur_targets.targets.cend(), target_comp);
507 if (it != cur_targets.targets.cend()) {
508 return std_::make_unique<Uptane::Target>(*it);
511 if (terminating || level >= Uptane::kDelegationsMaxDepth) {
512 return std::unique_ptr<Uptane::Target>(
nullptr);
515 for (
const auto &delegate_name : cur_targets.delegated_role_names_) {
516 Uptane::Role delegate_role = Uptane::Role::Delegation(delegate_name);
517 auto patterns = cur_targets.paths_for_role_.find(delegate_role);
518 if (patterns == cur_targets.paths_for_role_.end()) {
523 for (
const auto &pattern : patterns->second) {
524 if (fnmatch(pattern.c_str(), queried_target.filename().c_str(), 0) == 0) {
536 Uptane::getTrustedDelegation(delegate_role, cur_targets, images_repo, *storage, *uptane_fetcher, offline);
537 if (delegation.isExpired(TimeStamp::Now())) {
541 auto is_terminating = cur_targets.terminating_role_.find(delegate_role);
542 if (is_terminating == cur_targets.terminating_role_.end()) {
546 auto found_target = findTargetHelper(delegation, queried_target, level + 1, is_terminating->second, offline);
547 if (found_target !=
nullptr) {
552 return std::unique_ptr<Uptane::Target>(
nullptr);
555 std::unique_ptr<Uptane::Target> SotaUptaneClient::findTargetInDelegationTree(
const Uptane::Target &target,
556 const bool offline) {
557 auto toplevel_targets = images_repo.getTargets();
558 if (toplevel_targets ==
nullptr) {
559 return std::unique_ptr<Uptane::Target>(
nullptr);
562 return findTargetHelper(*toplevel_targets, target, 0,
false, offline);
565 result::Download SotaUptaneClient::downloadImages(
const std::vector<Uptane::Target> &targets,
569 std::lock_guard<std::mutex> guard(download_mutex);
571 std::vector<Uptane::Target> downloaded_targets;
574 if (update_status != result::UpdateStatus::kUpdatesAvailable) {
575 if (update_status == result::UpdateStatus::kNoUpdatesAvailable) {
579 result::Download(downloaded_targets, result::DownloadStatus::kError,
"Error rechecking stored metadata.");
580 storeInstallationFailure(
583 sendEvent<event::AllDownloadsComplete>(
result);
587 for (
const auto &target : targets) {
588 auto res = downloadImage(target, token);
590 downloaded_targets.push_back(res.second);
594 if (targets.size() == downloaded_targets.size()) {
597 if (downloaded_targets.size() == 0) {
598 LOG_ERROR <<
"None of " << targets.size() <<
" targets were successfully downloaded.";
599 result =
result::Download(downloaded_targets, result::DownloadStatus::kError,
"Each target download has failed");
601 LOG_ERROR <<
"Only " << downloaded_targets.size() <<
" of " << targets.size() <<
" were successfully downloaded.";
604 storeInstallationFailure(
608 sendEvent<event::AllDownloadsComplete>(
result);
612 void SotaUptaneClient::reportPause() {
613 const std::string &correlation_id = director_repo.getCorrelationId();
614 report_queue->enqueue(std_::make_unique<DevicePausedReport>(correlation_id));
617 void SotaUptaneClient::reportResume() {
618 const std::string &correlation_id = director_repo.getCorrelationId();
619 report_queue->enqueue(std_::make_unique<DeviceResumedReport>(correlation_id));
622 std::pair<bool, Uptane::Target> SotaUptaneClient::downloadImage(
const Uptane::Target &target,
626 const std::string &correlation_id = director_repo.getCorrelationId();
628 for (
const auto &ecu : target.ecus()) {
629 report_queue->enqueue(std_::make_unique<EcuDownloadStartedReport>(ecu.first, correlation_id));
632 KeyManager keys(storage, config.keymanagerConfig());
634 auto prog_cb = [
this](
const Uptane::Target &t,
const std::string description,
unsigned int progress) {
635 report_progress_cb(events_channel.get(), t, description, progress);
638 bool success =
false;
641 if (target.IsForEcu(primary_ecu_serial) || !target.
IsOstree()) {
643 const int max_tries = 3;
645 std::chrono::milliseconds wait(500);
647 for (; tries < max_tries; tries++) {
648 success = package_manager_->fetchTarget(target, *uptane_fetcher, keys, prog_cb, token);
651 }
else if (tries < max_tries - 1) {
652 std::this_thread::sleep_for(wait);
657 LOG_ERROR <<
"Download unsuccessful after " << tries <<
" attempts.";
666 for (
const auto &ecu : target.ecus()) {
667 report_queue->enqueue(std_::make_unique<EcuDownloadCompletedReport>(ecu.first, correlation_id, success));
670 sendEvent<event::DownloadTargetComplete>(target, success);
671 return {success, target};
674 bool SotaUptaneClient::uptaneIteration(std::vector<Uptane::Target> *targets,
unsigned int *ecus_count) {
675 if (!updateDirectorMeta()) {
676 LOG_ERROR <<
"Failed to update director metadata: " << last_exception.what();
679 std::vector<Uptane::Target> tmp_targets;
681 if (!getNewTargets(&tmp_targets, &ecus)) {
682 LOG_ERROR <<
"Inconsistency between director metadata and existent ECUs";
686 if (tmp_targets.empty()) {
687 if (targets !=
nullptr) {
688 *targets = std::move(tmp_targets);
690 if (ecus_count !=
nullptr) {
696 LOG_INFO <<
"got new updates";
698 if (!updateImagesMeta()) {
699 LOG_ERROR <<
"Failed to update images metadata: " << last_exception.what();
703 if (targets !=
nullptr) {
704 *targets = std::move(tmp_targets);
706 if (ecus_count !=
nullptr) {
712 bool SotaUptaneClient::uptaneOfflineIteration(std::vector<Uptane::Target> *targets,
unsigned int *ecus_count) {
713 if (!checkDirectorMetaOffline()) {
714 LOG_ERROR <<
"Failed to check director metadata: " << last_exception.what();
717 std::vector<Uptane::Target> tmp_targets;
719 if (!getNewTargets(&tmp_targets, &ecus)) {
720 LOG_ERROR <<
"Inconsistency between director metadata and existent ECUs";
724 if (tmp_targets.empty()) {
725 *targets = std::move(tmp_targets);
726 if (ecus_count !=
nullptr) {
732 if (!checkImagesMetaOffline()) {
733 LOG_ERROR <<
"Failed to check images metadata: " << last_exception.what();
737 *targets = std::move(tmp_targets);
738 if (ecus_count !=
nullptr) {
744 void SotaUptaneClient::sendDeviceData() {
746 reportInstalledPackages();
748 reportAktualizrConfiguration();
750 sendEvent<event::SendDeviceDataComplete>();
758 if (hasPendingUpdates()) {
760 LOG_INFO <<
"The current update is pending. Check if pending ECUs has been already updated";
761 checkAndUpdatePendingSecondaries();
764 if (hasPendingUpdates()) {
767 LOG_INFO <<
"An update is pending. Skipping check for update until installation is complete.";
769 "There are pending updates, no new updates are checked");
773 if (!putManifestSimple()) {
774 LOG_ERROR <<
"Error sending manifest!";
777 sendEvent<event::UpdateCheckComplete>(
result);
785 std::vector<Uptane::Target> updates;
786 unsigned int ecus_count = 0;
787 if (!uptaneIteration(&updates, &ecus_count)) {
792 std::string director_targets;
793 storage->loadNonRoot(&director_targets, Uptane::RepositoryType::Director(), Uptane::Role::Targets());
795 if (updates.empty()) {
796 LOG_DEBUG <<
"No new updates found in Uptane metadata.";
798 result::UpdateCheck({}, 0, result::UpdateStatus::kNoUpdatesAvailable, Utils::parseJSON(director_targets),
"");
806 for (
auto &target : updates) {
807 auto images_target = findTargetInDelegationTree(target,
false);
808 if (images_target ==
nullptr) {
811 LOG_ERROR <<
"No matching target in images targets metadata for " << target;
814 storeInstallationFailure(
820 if (target.uri().empty() && !images_target->uri().empty()) {
821 target.setUri(images_target->uri());
826 Utils::parseJSON(director_targets),
"");
827 if (updates.size() == 1) {
828 LOG_INFO <<
"1 new update found in Uptane metadata.";
830 LOG_INFO << updates.size() <<
" new updates found in Uptane metadata.";
835 result::UpdateStatus SotaUptaneClient::checkUpdatesOffline(
const std::vector<Uptane::Target> &targets) {
836 if (hasPendingUpdates()) {
838 LOG_INFO <<
"An update is pending. Skipping stored metadata check until installation is complete.";
839 return result::UpdateStatus::kError;
842 if (targets.empty()) {
843 LOG_WARNING <<
"Requested targets vector is empty. Nothing to do.";
844 return result::UpdateStatus::kError;
847 std::vector<Uptane::Target> director_targets;
848 unsigned int ecus_count = 0;
849 if (!uptaneOfflineIteration(&director_targets, &ecus_count)) {
850 LOG_ERROR <<
"Invalid Uptane metadata in storage.";
851 return result::UpdateStatus::kError;
854 if (director_targets.empty()) {
855 LOG_ERROR <<
"No new updates found in Uptane metadata, but expected " << targets.size() <<
".";
856 return result::UpdateStatus::kNoUpdatesAvailable;
862 for (
const auto &target : targets) {
864 const auto it = std::find_if(director_targets.cbegin(), director_targets.cend(), target_comp);
865 if (it == director_targets.cend()) {
866 LOG_ERROR <<
"No matching target in director targets metadata for " << target;
867 return result::UpdateStatus::kError;
870 const auto images_target = findTargetInDelegationTree(target,
true);
871 if (images_target ==
nullptr) {
872 LOG_ERROR <<
"No matching target in images targets metadata for " << target;
873 return result::UpdateStatus::kError;
877 return result::UpdateStatus::kUpdatesAvailable;
880 result::Install SotaUptaneClient::uptaneInstall(
const std::vector<Uptane::Target> &updates) {
881 const std::string &correlation_id = director_repo.getCorrelationId();
884 storage->clearInstallationResults();
889 std::string raw_report;
890 bool drop_targets =
false;
892 std::tie(r, raw_report, drop_targets) = [
this, &updates,
893 &correlation_id]() -> std::tuple<result::Install, std::string, bool> {
899 if (update_status != result::UpdateStatus::kUpdatesAvailable) {
900 if (update_status == result::UpdateStatus::kNoUpdatesAvailable) {
905 return std::make_tuple(
result,
"Stored Uptane metadata is invalid",
false);
910 for (
const auto &update : updates) {
911 if (update.IsForEcu(primary_ecu_serial) || !update.IsOstree()) {
917 if (package_manager_->verifyTarget(update) != TargetStatus::kGood) {
919 return std::make_tuple(
result,
"Downloaded target is invalid",
false);
928 if (!waitSecondariesReachable(updates)) {
930 return std::make_tuple(
result,
"Secondaries were not available",
false);
934 std::vector<Uptane::Target> primary_updates = findForEcu(updates, primary_ecu_serial);
937 sendMetadataToEcus(updates);
940 if (primary_updates.size() != 0u) {
943 primary_update.setCorrelationId(correlation_id);
945 report_queue->enqueue(std_::make_unique<EcuInstallationStartedReport>(primary_ecu_serial, correlation_id));
946 sendEvent<event::InstallStarted>(primary_ecu_serial);
949 if (!isInstalledOnPrimary(primary_update)) {
952 package_manager_->updateNotify();
953 install_res = PackageInstallSetResult(primary_update);
954 if (install_res.result_code.num_code == data::ResultCode::Numeric::kNeedCompletion) {
956 report_queue->enqueue(std_::make_unique<EcuInstallationAppliedReport>(primary_ecu_serial, correlation_id));
957 sendEvent<event::InstallTargetComplete>(primary_ecu_serial,
true);
958 }
else if (install_res.result_code.num_code == data::ResultCode::Numeric::kOk) {
959 storage->saveEcuInstallationResult(primary_ecu_serial, install_res);
960 report_queue->enqueue(
961 std_::make_unique<EcuInstallationCompletedReport>(primary_ecu_serial, correlation_id,
true));
962 sendEvent<event::InstallTargetComplete>(primary_ecu_serial,
true);
965 storage->saveEcuInstallationResult(primary_ecu_serial, install_res);
966 report_queue->enqueue(
967 std_::make_unique<EcuInstallationCompletedReport>(primary_ecu_serial, correlation_id,
false));
968 sendEvent<event::InstallTargetComplete>(primary_ecu_serial,
false);
973 storage->saveEcuInstallationResult(primary_ecu_serial, install_res);
975 report_queue->enqueue(
976 std_::make_unique<EcuInstallationCompletedReport>(primary_ecu_serial, correlation_id,
false));
977 sendEvent<event::InstallTargetComplete>(primary_ecu_serial,
false);
979 result.ecu_reports.emplace(
result.ecu_reports.begin(), primary_update, primary_ecu_serial, install_res);
981 LOG_INFO <<
"No update to install on primary";
984 auto sec_reports = sendImagesToEcus(updates);
985 result.ecu_reports.insert(
result.ecu_reports.end(), sec_reports.begin(), sec_reports.end());
987 computeDeviceInstallationResult(&
result.dev_report, &rr);
989 return std::make_tuple(
result, rr, !(
result.dev_report.isSuccess() ||
result.dev_report.needCompletion()));
993 storage->storeDeviceInstallationResult(r.dev_report, raw_report, correlation_id);
995 sendEvent<event::AllInstallsComplete>(r);
998 director_repo.dropTargets(*storage);
1005 auto campaigns = campaign::Campaign::fetchAvailableCampaigns(*http, config.tls.server);
1006 for (
const auto &c : campaigns) {
1007 LOG_INFO <<
"Campaign: " << c.name;
1008 LOG_INFO <<
"Campaign id: " << c.id;
1009 LOG_INFO <<
"Campaign size: " << c.size;
1010 LOG_INFO <<
"CampaignAccept required: " << (c.autoAccept ?
"no" :
"yes");
1011 LOG_INFO <<
"Message: " << c.description;
1014 sendEvent<event::CampaignCheckComplete>(
result);
1018 void SotaUptaneClient::campaignAccept(
const std::string &campaign_id) {
1019 sendEvent<event::CampaignAcceptComplete>();
1020 report_queue->enqueue(std_::make_unique<CampaignAcceptedReport>(campaign_id));
1023 void SotaUptaneClient::campaignDecline(
const std::string &campaign_id) {
1024 sendEvent<event::CampaignDeclineComplete>();
1025 report_queue->enqueue(std_::make_unique<CampaignDeclinedReport>(campaign_id));
1028 void SotaUptaneClient::campaignPostpone(
const std::string &campaign_id) {
1029 sendEvent<event::CampaignPostponeComplete>();
1030 report_queue->enqueue(std_::make_unique<CampaignPostponedReport>(campaign_id));
1033 bool SotaUptaneClient::isInstallCompletionRequired()
const {
1034 bool force_install_completion = (hasPendingUpdates() && config.uptane.force_install_completion);
1035 return force_install_completion;
1038 void SotaUptaneClient::completeInstall()
const {
1039 if (isInstallCompletionRequired()) {
1040 package_manager_->completeInstall();
1044 bool SotaUptaneClient::putManifestSimple(
const Json::Value &custom) {
1046 if (hasPendingUpdates()) {
1049 LOG_DEBUG <<
"An update is pending. Skipping manifest upload until installation is complete.";
1053 static bool connected =
true;
1054 auto manifest = AssembleManifest();
1055 if (custom != Json::nullValue) {
1056 manifest[
"custom"] = custom;
1058 auto signed_manifest = uptane_manifest->sign(manifest);
1059 HttpResponse response = http->put(config.uptane.director_server +
"/manifest", signed_manifest);
1060 if (response.isOk()) {
1062 LOG_INFO <<
"Connectivity is restored.";
1065 storage->clearInstallationResults();
1071 LOG_WARNING <<
"Put manifest request failed: " << response.getStatusStr();
1075 bool SotaUptaneClient::putManifest(
const Json::Value &custom) {
1076 bool success = putManifestSimple(custom);
1077 sendEvent<event::PutManifestComplete>(success);
1082 void SotaUptaneClient::verifySecondaries() {
1083 storage->clearMisconfiguredEcus();
1085 if (!storage->loadEcuSerials(&serials) || serials.empty()) {
1086 LOG_ERROR <<
"No ECU serials found in storage!";
1090 std::vector<MisconfiguredEcu> misconfigured_ecus;
1091 std::vector<bool> found(serials.size(),
false);
1093 EcuSerials::const_iterator store_it;
1094 store_it = std::find_if(serials.cbegin(), serials.cend(), primary_comp);
1095 if (store_it == serials.cend()) {
1096 LOG_ERROR <<
"Primary ECU serial " << primaryEcuSerial() <<
" not found in storage!";
1099 found[static_cast<size_t>(std::distance(serials.cbegin(), store_it))] =
true;
1102 for (
auto it = secondaries.cbegin(); it != secondaries.cend(); ++it) {
1104 store_it = std::find_if(serials.cbegin(), serials.cend(), secondary_comp);
1105 if (store_it == serials.cend()) {
1106 LOG_ERROR <<
"Secondary ECU serial " << it->second->getSerial() <<
" (hardware ID " << it->second->getHwId()
1107 <<
") not found in storage!";
1108 misconfigured_ecus.emplace_back(it->second->getSerial(), it->second->getHwId(), EcuState::kNotRegistered);
1109 }
else if (found[static_cast<size_t>(std::distance(serials.cbegin(), store_it))]) {
1110 LOG_ERROR <<
"Secondary ECU serial " << it->second->getSerial() <<
" (hardware ID " << it->second->getHwId()
1111 <<
") has a duplicate entry in storage!";
1113 found[static_cast<size_t>(std::distance(serials.cbegin(), store_it))] =
true;
1117 std::vector<bool>::iterator found_it;
1118 for (found_it = found.begin(); found_it != found.end(); ++found_it) {
1120 auto not_registered = serials[static_cast<size_t>(std::distance(found.begin(), found_it))];
1121 LOG_WARNING <<
"ECU serial " << not_registered.first <<
" in storage was not reported to aktualizr!";
1122 misconfigured_ecus.emplace_back(not_registered.first, not_registered.second, EcuState::kOld);
1126 storage->storeMisconfiguredEcus(misconfigured_ecus);
1129 bool SotaUptaneClient::waitSecondariesReachable(
const std::vector<Uptane::Target> &updates) {
1130 std::map<Uptane::EcuSerial, Uptane::SecondaryInterface *> targeted_secondaries;
1132 for (
const auto &t : updates) {
1133 for (
const auto &ecu : t.ecus()) {
1134 if (ecu.first == primary_ecu_serial) {
1137 auto f = secondaries.find(ecu.first);
1138 if (f == secondaries.end()) {
1139 LOG_ERROR <<
"Target " << t <<
" has unknown ECU ID";
1143 targeted_secondaries[ecu.first] = f->second.get();
1147 if (targeted_secondaries.empty()) {
1151 LOG_INFO <<
"Waiting for secondaries to connect to start installation...";
1153 auto deadline = std::chrono::system_clock::now() + std::chrono::seconds(config.uptane.secondary_preinstall_wait_sec);
1154 while (std::chrono::system_clock::now() <= deadline) {
1155 if (targeted_secondaries.empty()) {
1159 for (
auto sec_it = targeted_secondaries.begin(); sec_it != targeted_secondaries.end();) {
1160 if (sec_it->second->ping()) {
1161 sec_it = targeted_secondaries.erase(sec_it);
1166 std::this_thread::sleep_for(std::chrono::seconds(1));
1169 LOG_ERROR <<
"Secondaries did not connect: ";
1171 for (
const auto &sec : targeted_secondaries) {
1172 LOG_ERROR << sec.second->getSerial();
1181 const std::string &correlation_id = director_repo.getCorrelationId();
1182 storage->storeDeviceInstallationResult(
result,
"", correlation_id);
1184 director_repo.dropTargets(*storage);
1188 std::string latest_root;
1190 if (!storage->loadLatestRoot(&latest_root, repo)) {
1191 LOG_ERROR <<
"No root metadata to send";
1195 int last_root_version = Uptane::extractVersionUntrusted(latest_root);
1197 int sec_root_version = secondary.getRootVersion((repo == Uptane::RepositoryType::Director()));
1198 if (sec_root_version >= 0) {
1199 for (
int v = sec_root_version + 1; v <= last_root_version; v++) {
1202 LOG_WARNING <<
"Couldn't find root meta in the storage, trying remote repo";
1203 if (!uptane_fetcher->fetchRole(&root, Uptane::kMaxRootSize, repo, Uptane::Role::Root(),
Uptane::Version(v))) {
1205 LOG_ERROR <<
"Root metadata could not be fetched, skipping to the next secondary";
1209 if (!secondary.putRoot(root, repo == Uptane::RepositoryType::Director())) {
1210 LOG_ERROR <<
"Sending metadata to " << secondary.getSerial() <<
" failed";
1219 void SotaUptaneClient::sendMetadataToEcus(
const std::vector<Uptane::Target> &targets) {
1221 if (!storage->loadLatestRoot(&meta.director_root, Uptane::RepositoryType::Director())) {
1222 LOG_ERROR <<
"No director root metadata to send";
1225 if (!storage->loadNonRoot(&meta.director_targets, Uptane::RepositoryType::Director(), Uptane::Role::Targets())) {
1226 LOG_ERROR <<
"No director targets metadata to send";
1229 if (!storage->loadLatestRoot(&meta.image_root, Uptane::RepositoryType::Image())) {
1230 LOG_ERROR <<
"No images root metadata to send";
1233 if (!storage->loadNonRoot(&meta.image_timestamp, Uptane::RepositoryType::Image(), Uptane::Role::Timestamp())) {
1234 LOG_ERROR <<
"No images timestamp metadata to send";
1237 if (!storage->loadNonRoot(&meta.image_snapshot, Uptane::RepositoryType::Image(), Uptane::Role::Snapshot())) {
1238 LOG_ERROR <<
"No images snapshot metadata to send";
1241 if (!storage->loadNonRoot(&meta.image_targets, Uptane::RepositoryType::Image(), Uptane::Role::Targets())) {
1242 LOG_ERROR <<
"No images targets metadata to send";
1246 for (
auto targets_it = targets.cbegin(); targets_it != targets.cend(); ++targets_it) {
1247 for (
auto ecus_it = targets_it->ecus().cbegin(); ecus_it != targets_it->ecus().cend(); ++ecus_it) {
1250 auto sec = secondaries.find(ecu_serial);
1251 if (sec != secondaries.end()) {
1253 rotateSecondaryRoot(Uptane::RepositoryType::Director(), *(sec->second));
1254 rotateSecondaryRoot(Uptane::RepositoryType::Image(), *(sec->second));
1255 if (!sec->second->putMetadata(meta)) {
1256 LOG_ERROR <<
"Sending metadata to " << sec->first <<
" failed";
1265 auto f = [
this, &secondary, target]() {
1266 const std::string &correlation_id = director_repo.getCorrelationId();
1268 sendEvent<event::InstallStarted>(secondary.getSerial());
1269 report_queue->enqueue(std_::make_unique<EcuInstallationStartedReport>(secondary.getSerial(), correlation_id));
1271 std::string data_to_send;
1272 bool send_firmware_result =
false;
1276 data_to_send = secondaryTreehubCredentials();
1278 std::stringstream sstr;
1279 sstr << *storage->openTargetFile(target);
1280 data_to_send = sstr.str();
1283 if (!data_to_send.empty()) {
1284 send_firmware_result = secondary.sendFirmware(data_to_send);
1290 if (send_firmware_result) {
1291 result = secondary.install(target.filename());
1294 if (
result == data::ResultCode::Numeric::kNeedCompletion) {
1295 report_queue->enqueue(std_::make_unique<EcuInstallationAppliedReport>(secondary.getSerial(), correlation_id));
1297 report_queue->enqueue(std_::make_unique<EcuInstallationCompletedReport>(
1298 secondary.getSerial(), correlation_id,
result == data::ResultCode::Numeric::kOk));
1301 sendEvent<event::InstallTargetComplete>(secondary.getSerial(),
result == data::ResultCode::Numeric::kOk);
1305 return std::async(std::launch::async, f);
1308 std::vector<result::Install::EcuReport> SotaUptaneClient::sendImagesToEcus(
const std::vector<Uptane::Target> &targets) {
1309 std::vector<result::Install::EcuReport> reports;
1310 std::vector<std::pair<result::Install::EcuReport, std::future<data::ResultCode::Numeric>>> firmwareFutures;
1314 for (
auto targets_it = targets.cbegin(); targets_it != targets.cend(); ++targets_it) {
1315 for (
auto ecus_it = targets_it->ecus().cbegin(); ecus_it != targets_it->ecus().cend(); ++ecus_it) {
1318 if (primary_ecu_serial == ecu_serial) {
1322 auto f = secondaries.find(ecu_serial);
1323 if (f == secondaries.end()) {
1324 LOG_ERROR <<
"Target " << *targets_it <<
" has unknown ECU ID";
1331 sendFirmwareAsync(sec, *targets_it));
1335 for (
auto &f : firmwareFutures) {
1338 fut_result = f.second.get();
1341 if (fiu_fail((std::string(
"secondary_install_") + f.first.serial.ToString()).c_str()) != 0) {
1354 if (fut_result == data::ResultCode::Numeric::kOk || fut_result == data::ResultCode::Numeric::kNeedCompletion) {
1355 f.first.update.setCorrelationId(director_repo.getCorrelationId());
1356 auto update_mode = fut_result == data::ResultCode::Numeric::kOk ? InstalledVersionUpdateMode::kCurrent
1357 : InstalledVersionUpdateMode::kPending;
1358 storage->saveInstalledVersion(f.first.serial.ToString(), f.first.update, update_mode);
1361 storage->saveEcuInstallationResult(f.first.serial, f.first.install_res);
1362 reports.push_back(f.first);
1367 std::string SotaUptaneClient::secondaryTreehubCredentials()
const {
1368 if (config.tls.pkey_source != CryptoSource::kFile || config.tls.cert_source != CryptoSource::kFile ||
1369 config.tls.ca_source != CryptoSource::kFile) {
1370 LOG_ERROR <<
"Cannot send OSTree update to a secondary when not using file as credential sources";
1373 std::string ca, cert, pkey;
1374 if (!storage->loadTlsCreds(&ca, &cert, &pkey)) {
1375 LOG_ERROR <<
"Could not load tls credentials from storage";
1379 std::string treehub_url = config.pacman.ostree_server;
1380 std::map<std::string, std::string> archive_map = {
1381 {
"ca.pem", ca}, {
"client.pem", cert}, {
"pkey.pem", pkey}, {
"server.url", treehub_url}};
1384 std::stringstream as;
1385 Utils::writeArchive(archive_map, as);
1388 }
catch (std::runtime_error &exc) {
1389 LOG_ERROR <<
"Could not create credentials archive: " << exc.what();
1398 void SotaUptaneClient::checkAndUpdatePendingSecondaries() {
1400 std::vector<std::pair<Uptane::EcuSerial, Uptane::Hash>> pending_ecus;
1401 storage->getPendingEcus(&pending_ecus);
1403 for (
const auto &pending_ecu : pending_ecus) {
1404 if (primaryEcuSerial() == pending_ecu.first) {
1407 auto &sec = secondaries[pending_ecu.first];
1408 const auto &manifest = sec->getManifest();
1409 if (!manifest.verifySignature(sec->getPublicKey())) {
1410 LOG_ERROR <<
"Invalid signature of the manifest reported by secondary: "
1411 <<
" serial: " << pending_ecu.first <<
" manifest: " << manifest;
1415 auto current_ecu_hash = manifest.installedImageHash();
1416 if (pending_ecu.second == current_ecu_hash) {
1417 LOG_INFO <<
"The pending update " << current_ecu_hash <<
" has been installed on " << pending_ecu.first;
1418 boost::optional<Uptane::Target> pending_version;
1419 if (storage->loadInstalledVersions(pending_ecu.first.ToString(),
nullptr, &pending_version)) {
1420 storage->saveEcuInstallationResult(pending_ecu.first,
1423 storage->saveInstalledVersion(pending_ecu.first.ToString(), *pending_version,
1424 InstalledVersionUpdateMode::kCurrent);
1426 report_queue->enqueue(std_::make_unique<EcuInstallationCompletedReport>(
1427 pending_ecu.first, pending_version->correlation_id(),
true));
1430 std::string raw_report;
1431 computeDeviceInstallationResult(&ir, &raw_report);
1432 storage->storeDeviceInstallationResult(ir, raw_report, pending_version->correlation_id());
1438 boost::optional<Uptane::HardwareIdentifier> SotaUptaneClient::ecuHwId(
const Uptane::EcuSerial &serial)
const {
1439 if (serial == primary_ecu_serial_ || serial.ToString().empty()) {
1440 if (primary_ecu_hw_id_ == Uptane::HardwareIdentifier::Unknown()) {
1443 return primary_ecu_hw_id_;
1446 const auto it = secondaries.find(serial);
1447 if (it != secondaries.end()) {
1448 return it->second->getHwId();