1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
|
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/ash/components/dbus/fwupd/fwupd_client.h"
#include <cstdint>
#include <memory>
#include <optional>
#include <utility>
#include "ash/constants/ash_features.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "base/values.h"
#include "chromeos/ash/components/dbus/fwupd/dbus_constants.h"
#include "chromeos/ash/components/dbus/fwupd/fake_fwupd_client.h"
#include "chromeos/ash/components/dbus/fwupd/fwupd_properties_dbus.h"
#include "chromeos/ash/components/dbus/fwupd/fwupd_request.h"
#include "chromeos/ash/components/install_attributes/install_attributes.h"
#include "components/device_event_log/device_event_log.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_proxy.h"
#include "url/gurl.h"
namespace ash {
namespace {
// This enum should match the UpdatePriority enum here:
// ash/webui/firmware_update_ui/mojom/firmware_update.mojom
enum UpdatePriority { kLow, kMedium, kHigh, kCritical };
// Global singleton instance. Always set.
FwupdClient* g_instance = nullptr;
// Global singleton for fake instance. Only set when a InitializeFake is used.
// If not null, matches g_instance.
FakeFwupdClient* g_fake_instance = nullptr;
const char kCabFileExtension[] = ".cab";
const int kSha256Length = 64;
// Dict key for the IsInternal device flag.
const char kIsInternalKey[] = "IsInternal";
// Dict key for the Reboot device flag.
const char kNeedsRebootKey[] = "NeedsReboot";
// Dict key for the HasTrustedReport release flag.
const char kHasTrustedReportKey[] = "HasTrustedReport";
// Dict key for the Locations field in a release.
const char kLocationsKey[] = "Locations";
// Base URL of the ChromeOS mirror of LVFS.
const char kLVFSMirrorBaseURL[] =
"https://storage.googleapis.com/chromeos-localmirror/lvfs/";
// String to FwupdDbusResult conversion
// Consistent with
// https://github.com/fwupd/fwupd/blob/988f27fd96c5334089ec5daf9c4b2a34f5c6943a/libfwupd/fwupd-error.c#L26
FwupdDbusResult GetFwupdDbusResult(const std::string& error_name) {
if (error_name == std::string(kFwupdErrorName_Internal)) {
return FwupdDbusResult::kInternalError;
} else if (error_name == std::string(kFwupdErrorName_VersionNewer)) {
return FwupdDbusResult::kVersionNewerError;
} else if (error_name == std::string(kFwupdErrorName_VersionSame)) {
return FwupdDbusResult::kVersionSameError;
} else if (error_name == std::string(kFwupdErrorName_AlreadyPending)) {
return FwupdDbusResult::kAlreadyPendingError;
} else if (error_name == std::string(kFwupdErrorName_AuthFailed)) {
return FwupdDbusResult::kAuthFailedError;
} else if (error_name == std::string(kFwupdErrorName_Read)) {
return FwupdDbusResult::kReadError;
} else if (error_name == std::string(kFwupdErrorName_Write)) {
return FwupdDbusResult::kWriteError;
} else if (error_name == std::string(kFwupdErrorName_InvalidFile)) {
return FwupdDbusResult::kInvalidFileError;
} else if (error_name == std::string(kFwupdErrorName_NotFound)) {
return FwupdDbusResult::kNotFoundError;
} else if (error_name == std::string(kFwupdErrorName_NothingToDo)) {
return FwupdDbusResult::kNothingToDoError;
} else if (error_name == std::string(kFwupdErrorName_NotSupported)) {
return FwupdDbusResult::kNotSupportedError;
} else if (error_name == std::string(kFwupdErrorName_SignatureInvalid)) {
return FwupdDbusResult::kSignatureInvalidError;
} else if (error_name == std::string(kFwupdErrorName_AcPowerRequired)) {
return FwupdDbusResult::kAcPowerRequiredError;
} else if (error_name == std::string(kFwupdErrorName_PermissionDenied)) {
return FwupdDbusResult::kPermissionDeniedError;
} else if (error_name == std::string(kFwupdErrorName_BrokenSystem)) {
return FwupdDbusResult::kBrokenSystemError;
} else if (error_name == std::string(kFwupdErrorName_BatteryLevelTooLow)) {
return FwupdDbusResult::kBatteryLevelTooLowError;
} else if (error_name == std::string(kFwupdErrorName_NeedsUserAction)) {
return FwupdDbusResult::kNeedsUserActionError;
} else if (error_name == std::string(kFwupdErrorName_AuthExpired)) {
return FwupdDbusResult::kAuthExpiredError;
}
FIRMWARE_LOG(ERROR) << "No matching error found for: " << error_name;
return FwupdDbusResult::kUnknownError;
}
std::string ParseCheckSum(const std::string& raw_sum) {
// The raw checksum string from fwupd can be formatted as:
// "SHA{Option},SHA{Option}" or "SHA{Option}". Grab the SHA256 when possible.
const std::size_t delim_pos = raw_sum.find_first_of(",");
if (delim_pos != std::string::npos) {
DCHECK(raw_sum.size() > 0);
if (delim_pos >= raw_sum.size() - 1) {
return "";
}
const std::string first = raw_sum.substr(0, delim_pos);
const std::string second = raw_sum.substr(delim_pos + 1);
if (first.length() == kSha256Length) {
return first;
}
if (second.length() == kSha256Length) {
return second;
}
return "";
}
// Only one checksum available, use it if it's a sha256 checksum.
if (raw_sum.length() != kSha256Length) {
return "";
}
return raw_sum;
}
std::optional<DeviceRequestId> GetDeviceRequestIdFromFwupdString(
std::string fwupd_device_id_string) {
static base::NoDestructor<FwupdStringToRequestIdMap>
fwupdStringToRequestIdMap(
{{kFwupdDeviceRequestId_DoNotPowerOff,
DeviceRequestId::kDoNotPowerOff},
{kFwupdDeviceRequestId_ReplugInstall,
DeviceRequestId::kReplugInstall},
{kFwupdDeviceRequestId_InsertUSBCable,
DeviceRequestId::kInsertUSBCable},
{kFwupdDeviceRequestId_RemoveUSBCable,
DeviceRequestId::kRemoveUSBCable},
{kFwupdDeviceRequestId_PressUnlock, DeviceRequestId::kPressUnlock},
{kFwupdDeviceRequestId_RemoveReplug, DeviceRequestId::kRemoveReplug},
{kFwupdDeviceRequestId_ReplugPower, DeviceRequestId::kReplugPower}});
if (fwupdStringToRequestIdMap->contains(fwupd_device_id_string)) {
return fwupdStringToRequestIdMap->at(fwupd_device_id_string);
} else {
return std::nullopt;
}
}
class FwupdClientImpl : public FwupdClient {
public:
FwupdClientImpl() = default;
FwupdClientImpl(const FwupdClientImpl&) = delete;
FwupdClientImpl& operator=(const FwupdClientImpl&) = delete;
~FwupdClientImpl() override = default;
void Init(dbus::Bus* bus) override {
DCHECK(bus);
proxy_ = bus->GetObjectProxy(kFwupdServiceName,
dbus::ObjectPath(kFwupdServicePath));
DCHECK(proxy_);
proxy_->ConnectToSignal(
kFwupdServiceInterface, kFwupdDeviceAddedSignalName,
base::BindRepeating(&FwupdClientImpl::OnDeviceAddedReceived,
weak_ptr_factory_.GetWeakPtr()),
base::BindOnce(&FwupdClientImpl::OnSignalConnected,
weak_ptr_factory_.GetWeakPtr()));
proxy_->ConnectToSignal(
kFwupdServiceInterface, kFwupdDeviceRequestReceivedSignalName,
base::BindRepeating(&FwupdClientImpl::OnDeviceRequestReceived,
weak_ptr_factory_.GetWeakPtr()),
base::BindOnce(&FwupdClientImpl::OnSignalConnected,
weak_ptr_factory_.GetWeakPtr()));
properties_ = std::make_unique<FwupdDbusProperties>(
proxy_, base::BindRepeating(&FwupdClientImpl::OnPropertyChanged,
weak_ptr_factory_.GetWeakPtr()));
properties_->ConnectSignals();
properties_->GetAll();
SetFwupdFeatureFlags();
}
void SetFwupdFeatureFlags() override {
// Enable interactive updates in fwupd by setting the "requests"
// FwupdFeatureFlag when the Firmware Updates v2 feature flag is enabled.
if (base::FeatureList::IsEnabled(features::kFirmwareUpdateUIV2)) {
dbus::MethodCall method_call(kFwupdServiceInterface,
kFwupdSetFeatureFlagsMethodName);
dbus::MessageWriter writer(&method_call);
writer.AppendUint64(kRequestsFeatureFlag);
proxy_->CallMethodWithErrorResponse(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::BindOnce(&FwupdClientImpl::SetFeatureFlagsCallback,
weak_ptr_factory_.GetWeakPtr()));
}
}
void RequestUpdates(const std::string& device_id) override {
FIRMWARE_LOG(USER) << "fwupd: RequestUpdates called for: " << device_id;
dbus::MethodCall method_call(kFwupdServiceInterface,
kFwupdGetUpgradesMethodName);
dbus::MessageWriter writer(&method_call);
writer.AppendString(device_id);
proxy_->CallMethodWithErrorResponse(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::BindOnce(&FwupdClientImpl::RequestUpdatesCallback,
weak_ptr_factory_.GetWeakPtr(), device_id));
}
void RequestDevices() override {
FIRMWARE_LOG(USER) << "fwupd: RequestDevices called";
dbus::MethodCall method_call(kFwupdServiceInterface,
kFwupdGetDevicesMethodName);
proxy_->CallMethodWithErrorResponse(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::BindOnce(&FwupdClientImpl::RequestDevicesCallback,
weak_ptr_factory_.GetWeakPtr()));
}
void InstallUpdate(
const std::string& device_id,
base::ScopedFD file_descriptor,
FirmwareInstallOptions options,
base::OnceCallback<void(FwupdDbusResult)> callback) override {
FIRMWARE_LOG(USER) << "fwupd: InstallUpdate called for id: " << device_id;
dbus::MethodCall method_call(kFwupdServiceInterface,
kFwupdInstallMethodName);
dbus::MessageWriter writer(&method_call);
writer.AppendString(device_id);
writer.AppendFileDescriptor(file_descriptor.get());
// Write the options in form of "a{sv}".
dbus::MessageWriter array_writer(nullptr);
writer.OpenArray("{sv}", &array_writer);
for (const auto& option : options) {
dbus::MessageWriter dict_entry_writer(nullptr);
array_writer.OpenDictEntry(&dict_entry_writer);
dict_entry_writer.AppendString(option.first);
dict_entry_writer.AppendVariantOfBool(option.second);
array_writer.CloseContainer(&dict_entry_writer);
}
writer.CloseContainer(&array_writer);
// TODO(michaelcheco): Investigate whether or not the estimated install time
// multiplied by some factor can be used in place of
// `TIMEOUT_MAX`.
proxy_->CallMethodWithErrorResponse(
&method_call, dbus::ObjectProxy::TIMEOUT_MAX,
base::BindOnce(&FwupdClientImpl::InstallUpdateCallback,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void UpdateMetadata(
const std::string& remote_id,
base::ScopedFD data_file_descriptor,
base::ScopedFD sig_file_descriptor,
base::OnceCallback<void(FwupdDbusResult)> callback) override {
FIRMWARE_LOG(USER) << "fwupd: UpdateMetadata called for remote id: "
<< remote_id;
dbus::MethodCall method_call(kFwupdServiceInterface,
kFwupdUpdateMetadataMethodName);
dbus::MessageWriter writer(&method_call);
writer.AppendString(remote_id);
writer.AppendFileDescriptor(data_file_descriptor.get());
writer.AppendFileDescriptor(sig_file_descriptor.get());
proxy_->CallMethodWithErrorResponse(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::BindOnce(&FwupdClientImpl::UpdateMetadataCallback,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
private:
// Pops a string-to-variant-string dictionary from the reader.
base::Value::Dict PopStringToStringDictionary(dbus::MessageReader* reader) {
dbus::MessageReader array_reader(nullptr);
if (!reader->PopArray(&array_reader)) {
FIRMWARE_LOG(ERROR) << "Failed to pop array into the array reader.";
return base::Value::Dict();
}
base::Value::Dict result;
while (array_reader.HasMoreData()) {
dbus::MessageReader entry_reader(nullptr);
dbus::MessageReader variant_reader(nullptr);
std::string key;
std::string value_string;
uint32_t value_uint = 0;
const bool success = array_reader.PopDictEntry(&entry_reader) &&
entry_reader.PopString(&key) &&
entry_reader.PopVariant(&variant_reader);
if (!success) {
FIRMWARE_LOG(ERROR) << "Failed to get a dictionary entry. ";
return base::Value::Dict();
}
// Values in the response can have different types. The fields we are
// interested in, are all either strings, arrays of strings, uint64, or
// uint32.
// Some fields in the response have other types, but we don't use them, so
// we just skip them.
const dbus::Message::DataType data_type = variant_reader.GetDataType();
if (data_type == dbus::Message::UINT32) {
variant_reader.PopUint32(&value_uint);
// Value doesn't support unsigned numbers, so this has to be converted
// to int.
result.Set(key, (int)value_uint);
} else if (data_type == dbus::Message::STRING) {
variant_reader.PopString(&value_string);
result.Set(key, value_string);
} else if (data_type == dbus::Message::UINT64) {
// Value doesn't support lossless storage of uint64_t, so
// convert flags to boolean keys.
if (key == "Flags") {
uint64_t value_uint64 = 0;
variant_reader.PopUint64(&value_uint64);
const bool is_internal =
(value_uint64 & kInternalDeviceFlag) == kInternalDeviceFlag;
result.Set(kIsInternalKey, is_internal);
const bool needs_reboot =
(value_uint64 & kNeedsRebootDeviceFlag) == kNeedsRebootDeviceFlag;
result.Set(kNeedsRebootKey, needs_reboot);
} else if (key == "TrustFlags") {
uint64_t value_uint64 = 0;
variant_reader.PopUint64(&value_uint64);
const bool has_trusted_report =
(value_uint64 & kTrustedReportsReleaseFlag) ==
kTrustedReportsReleaseFlag;
result.Set(kHasTrustedReportKey, has_trusted_report);
}
} else if (data_type == dbus::Message::ARRAY && key == kLocationsKey) {
std::vector<std::string> strings;
variant_reader.PopArrayOfStrings(&strings);
base::Value::List list;
for (const auto& s : strings) {
list.Append(s);
}
result.Set(kLocationsKey, std::move(list));
}
}
return result;
}
void RequestUpdatesCallback(const std::string& device_id,
dbus::Response* response,
dbus::ErrorResponse* error_response) {
bool can_parse = true;
if (!response) {
can_parse = false;
FIRMWARE_LOG(DEBUG) << "No updates found, reason: "
<< (error_response ? error_response->ToString()
: std::string("No response"));
} else if (error_response) {
// Returning updates and still getting an error response means this is a
// real error.
FIRMWARE_LOG(ERROR) << "Request Updates had error message: "
<< error_response->ToString();
}
dbus::MessageReader reader(response);
dbus::MessageReader array_reader(nullptr);
if (can_parse && !reader.PopArray(&array_reader)) {
FIRMWARE_LOG(ERROR) << "Failed to parse string from DBus Signal";
can_parse = false;
}
const bool needs_trusted_report =
!features::IsFlexFirmwareUpdateEnabled() &&
!features::IsFwupdDeveloperModeEnabled();
FwupdUpdateList updates;
while (can_parse && array_reader.HasMoreData()) {
// Parse update description.
base::Value::Dict dict = PopStringToStringDictionary(&array_reader);
if (dict.empty()) {
FIRMWARE_LOG(ERROR) << "Failed to parse the update description.";
// Ran into an error, exit early.
break;
}
const std::string* version = dict.FindString("Version");
const std::string* description = dict.FindString("Description");
std::optional<int> priority = dict.FindInt("Urgency");
const base::FilePath filepath = GetUpdatePathFromDict(dict);
const std::string* checksum = dict.FindString("Checksum");
std::optional<bool> trusted_report = dict.FindBool(kHasTrustedReportKey);
const bool has_trusted_report =
trusted_report.has_value() && trusted_report.value();
FIRMWARE_LOG(DEBUG) << "Trusted Reports required: "
<< needs_trusted_report
<< "; Trusted Reports found: " << has_trusted_report;
const bool missing_trusted_report =
needs_trusted_report && !has_trusted_report;
std::string sha_checksum;
if (checksum) {
sha_checksum = ParseCheckSum(*checksum);
}
std::string description_value = "";
if (description) {
description_value = *description;
} else {
FIRMWARE_LOG(ERROR)
<< "Device: " << device_id << " is missing its description text.";
}
// If priority isn't specified we use default of low priority.
if (!priority) {
FIRMWARE_LOG(ERROR)
<< "Device: " << device_id
<< " is missing its priority field, using default of low priority.";
}
int priority_value = priority.value_or(UpdatePriority::kLow);
const bool success = version && !filepath.empty() &&
!sha_checksum.empty() && !missing_trusted_report;
// TODO(michaelcheco): Confirm that this is the expected behavior.
if (success) {
FIRMWARE_LOG(USER) << "fwupd: Found update version for device: "
<< device_id << " with version: " << *version;
updates.emplace_back(*version, description_value, priority_value,
filepath, sha_checksum);
} else {
if (!version) {
FIRMWARE_LOG(ERROR)
<< "Device: " << device_id << " is missing its version field.";
}
if (filepath.empty()) {
FIRMWARE_LOG(ERROR) << "Device: " << device_id
<< " has a missing or invalid filename field.";
}
if (!checksum) {
FIRMWARE_LOG(ERROR)
<< "Device: " << device_id << " is missing its checksum field.";
}
}
}
FIRMWARE_LOG(USER) << "fwupd: Updates for: " << device_id << ": "
<< updates.size();
for (auto& observer : observers_) {
observer.OnUpdateListResponse(device_id, &updates);
}
}
void RequestDevicesCallback(dbus::Response* response,
dbus::ErrorResponse* error_response) {
if (!response) {
FIRMWARE_LOG(ERROR) << "No Dbus response received from fwupd.";
return;
}
dbus::MessageReader reader(response);
dbus::MessageReader array_reader(nullptr);
if (!reader.PopArray(&array_reader)) {
FIRMWARE_LOG(ERROR) << "Failed to parse string from DBus Signal";
return;
}
const bool allow_internal =
features::IsFlexFirmwareUpdateEnabled() &&
!InstallAttributes::Get()->IsEnterpriseManaged();
FwupdDeviceList devices;
while (array_reader.HasMoreData()) {
// Parse device description.
base::Value::Dict dict = PopStringToStringDictionary(&array_reader);
if (dict.empty()) {
FIRMWARE_LOG(ERROR) << "Failed to parse the device description.";
return;
}
std::optional<bool> is_internal = dict.FindBool(kIsInternalKey);
const std::string* name = dict.FindString("Name");
// Ignore internal devices unless firmware updates for Flex are enabled.
if (!allow_internal && is_internal.has_value() && is_internal.value()) {
if (name) {
FIRMWARE_LOG(DEBUG) << "Ignoring internal device: " << *name;
} else {
FIRMWARE_LOG(DEBUG) << "Ignoring unnamed internal device.";
}
continue;
}
const std::string* id = dict.FindString("DeviceId");
if (!id) {
FIRMWARE_LOG(ERROR) << "No device id found.";
continue;
}
if (!name) {
FIRMWARE_LOG(ERROR) << "No name found for device: " << *id;
continue;
}
std::optional<bool> needs_reboot = dict.FindBool(kNeedsRebootKey);
FIRMWARE_LOG(DEBUG) << "fwupd: Device found: " << *id << " " << *name;
devices.emplace_back(*id, *name, needs_reboot.value_or(false));
}
FIRMWARE_LOG(USER) << "fwupd: Devices found: " << devices.size();
for (auto& observer : observers_) {
observer.OnDeviceListResponse(&devices);
}
}
void InstallUpdateCallback(base::OnceCallback<void(FwupdDbusResult)> callback,
dbus::Response* response,
dbus::ErrorResponse* error_response) {
FwupdDbusResult result = FwupdDbusResult::kSuccess;
if (error_response) {
FIRMWARE_LOG(ERROR) << "Firmware install failed with error message: "
<< error_response->ToString();
result = GetFwupdDbusResult(error_response->GetErrorName());
}
FIRMWARE_LOG(USER) << "fwupd: InstallUpdate returned with: "
<< static_cast<int>(result);
std::move(callback).Run(result);
}
void OnSignalConnected(const std::string& interface_name,
const std::string& signal_name,
bool is_connected) {
if (!is_connected) {
FIRMWARE_LOG(ERROR) << "Failed to connect to signal " << signal_name;
}
}
// TODO(swifton): This is a stub implementation.
void OnDeviceAddedReceived(dbus::Signal* signal) {
if (client_is_in_testing_mode_) {
++device_signal_call_count_for_testing_;
}
}
void OnDeviceRequestReceived(dbus::Signal* signal) {
FIRMWARE_LOG(EVENT) << "fwupd: Received device request";
dbus::MessageReader signal_reader(signal);
dbus::MessageReader array_reader(nullptr);
if (!signal_reader.PopArray(&array_reader)) {
FIRMWARE_LOG(ERROR) << "Failed to pop array into the array reader.";
return;
}
std::string request_id_string;
uint32_t request_kind;
while (array_reader.HasMoreData()) {
dbus::MessageReader dict_entry_reader(nullptr);
dbus::MessageReader value_reader(nullptr);
std::string key;
if (!array_reader.PopDictEntry(&dict_entry_reader) ||
!dict_entry_reader.PopString(&key) ||
!dict_entry_reader.PopVariant(&value_reader)) {
FIRMWARE_LOG(ERROR)
<< "Failed to pop dict entry into the entry reader.";
return;
}
if (key == kFwupdDeviceRequestKey_AppstreamId) {
if (!value_reader.PopString(&request_id_string)) {
FIRMWARE_LOG(ERROR)
<< "Failed to pop string for AppstreamId (DeviceRequestId).";
return;
}
} else if (key == kFwupdDeviceRequestKey_RequestKind) {
if (!value_reader.PopUint32(&request_kind)) {
FIRMWARE_LOG(ERROR) << "Failed to pop uint32 for RequestKind";
return;
}
}
}
if (request_id_string.empty()) {
FIRMWARE_LOG(ERROR)
<< "Could not parse request_id from DeviceRequest signal.";
return;
}
std::optional<DeviceRequestId> request_id =
GetDeviceRequestIdFromFwupdString(request_id_string);
if (!request_id.has_value()) {
FIRMWARE_LOG(ERROR) << "Could not get DeviceRequestId for string "
<< request_id_string;
return;
}
for (auto& observer : observers_) {
observer.OnDeviceRequestResponse(FwupdRequest(
static_cast<uint32_t>(request_id.value()), request_kind));
}
}
void OnPropertyChanged(const std::string& name) {
for (auto& observer : observers_) {
observer.OnPropertiesChangedResponse(properties_.get());
}
}
void SetFeatureFlagsCallback(dbus::Response* response,
dbus::ErrorResponse* error_response) {
// No need to take any specific action here.
if (!response) {
FIRMWARE_LOG(ERROR) << "No D-Bus response received from fwupd.";
return;
}
}
void UpdateMetadataCallback(
base::OnceCallback<void(FwupdDbusResult)> callback,
dbus::Response* response,
dbus::ErrorResponse* error_response) {
FwupdDbusResult result = FwupdDbusResult::kSuccess;
if (error_response) {
FIRMWARE_LOG(ERROR) << "UpdateMetadata failed with error message: "
<< error_response->ToString();
result = GetFwupdDbusResult(error_response->GetErrorName());
}
FIRMWARE_LOG(USER) << "UpdateMetadata returned with: "
<< static_cast<int>(result);
std::move(callback).Run(result);
}
raw_ptr<dbus::ObjectProxy> proxy_ = nullptr;
// Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed.
base::WeakPtrFactory<FwupdClientImpl> weak_ptr_factory_{this};
};
} // namespace
base::FilePath GetUpdatePathFromDict(const base::Value::Dict& dict) {
// Get the locations field.
const base::Value::List* locations = dict.FindList(kLocationsKey);
if (!locations || locations->empty()) {
FIRMWARE_LOG(ERROR) << "Missing or empty locations";
return base::FilePath();
}
// Get the first location as a string.
const std::string* location = locations->front().GetIfString();
if (!location) {
FIRMWARE_LOG(ERROR) << "Location is not a string";
return base::FilePath();
}
// Convert to a GURL to validate and canonicalize the URL.
const GURL url(*location);
if (!url.is_valid()) {
FIRMWARE_LOG(ERROR) << "Invalid location URL: " << *location;
return base::FilePath();
}
// Convert to a FilePath
base::FilePath path(url.spec());
// Force return; don't authenticate URL further.
if (features::IsFwupdDeveloperModeEnabled()) {
FIRMWARE_LOG(DEBUG)
<< "Developer mode detected; URI authentication skipped";
return path;
}
// Verify the extension.
if (path.Extension() != kCabFileExtension) {
FIRMWARE_LOG(ERROR) << "Invalid location extension: " << path;
return base::FilePath();
}
// No modification needed for "file://" paths.
if (url.SchemeIsFile()) {
return path;
}
// Reject other URL schemes.
if (!url.SchemeIsHTTPOrHTTPS()) {
FIRMWARE_LOG(ERROR) << "Invalid location scheme: " << path;
return base::FilePath();
}
// For remote paths, ensure that the URL is on the LVFS mirror. This
// ensures that the default server "https://fwupd.org/..." is not used.
if (url.GetWithoutFilename() != kLVFSMirrorBaseURL) {
FIRMWARE_LOG(ERROR) << "Location URL is not on the LVFS mirror: " << path;
return base::FilePath();
}
return path;
}
void FwupdClient::AddObserver(FwupdClient::Observer* observer) {
observers_.AddObserver(observer);
}
void FwupdClient::RemoveObserver(FwupdClient::Observer* observer) {
observers_.RemoveObserver(observer);
}
FwupdClient::FwupdClient() {
DCHECK(!g_instance);
g_instance = this;
}
FwupdClient::~FwupdClient() {
DCHECK_EQ(g_instance, this);
g_instance = nullptr;
}
// static
FwupdClient* FwupdClient::Get() {
return g_instance;
}
// static
FakeFwupdClient* FwupdClient::GetFake() {
return g_fake_instance;
}
// static
void FwupdClient::Initialize(dbus::Bus* bus) {
CHECK(bus);
(new FwupdClientImpl())->Init(bus);
}
// static
void FwupdClient::InitializeFake() {
g_fake_instance = new FakeFwupdClient();
g_fake_instance->Init(nullptr);
}
// static
void FwupdClient::Shutdown() {
CHECK(g_instance);
delete g_instance;
}
} // namespace ash
|