electron/shell/browser/usb/usb_chooser_context.cc
electron-roller[bot] 3e22f992b0
chore: bump chromium to 128.0.6611.0 (main) (#42779)
* chore: bump chromium in DEPS to 128.0.6577.0

* chore: bump chromium in DEPS to 128.0.6579.0

* 5675706: Reland "Reland "Reland "Reland "Add toolchains without PartitionAlloc-Everywhere for dump_syms et al""""

https://chromium-review.googlesource.com/c/chromium/src/+/5675706

* 5668597: [PDF Ink Signatures] Prompt download menu on save when there are edits

https://chromium-review.googlesource.com/c/chromium/src/+/5668597

* 5677014: Reland "Pull data_sharing_sdk from CIPD"

https://chromium-review.googlesource.com/c/chromium/src/+/5677014

* chore: fixup patch indices

* chore: bump chromium in DEPS to 128.0.6581.0

* chore: bump chromium in DEPS to 128.0.6583.0

* update patches

* 5455480: [Extensions] Allow service worker requests to continue without a cert

https://chromium-review.googlesource.com/c/chromium/src/+/5455480

* try to get some debugging output from script/push-patch.js

* chore: bump chromium in DEPS to 128.0.6585.0

* chore: bump chromium in DEPS to 128.0.6587.0

* update patches

* chore: bump chromium in DEPS to 128.0.6589.0

* more patch work

* maybe over here?

* chore: update patches

* 5673207: [HTTPS Upgrades] Disable in captive portal login webview

https://chromium-review.googlesource.com/c/chromium/src/+/5673207

* 5636785: Extensions: WAR: manifest.json's use_dynamic_url requires a dynamic url

https://chromium-review.googlesource.com/c/chromium/src/+/5636785

* chore: bump chromium in DEPS to 128.0.6591.0

* 5665458: Trigger WN2 page when feature is enabled

https://chromium-review.googlesource.com/c/chromium/src/+/5665458

* update patches

* chore: bump chromium in DEPS to 128.0.6593.0

* chore: bump chromium in DEPS to 128.0.6595.0

* chore: bump chromium in DEPS to 128.0.6597.0

* (patch update) 5694586: [compile hints] Remove the usage of v8::Isolate::SetJavaScriptCompileHintsMagicEnabledCallback API
https://chromium-review.googlesource.com/c/chromium/src/+/5694586

* update patches

* 5691287: Reland "Change blink::WebKeyboardEvent to use std::array in is members"
https://chromium-review.googlesource.com/c/chromium/src/+/5691287

The code changed here is modeled after code in `content/renderer/pepper/event_conversion.cc` that was also modified in this CL, so I took the same approach.

* 5529018: Cleanup EnableWebHidOnExtensionServiceWorker flag
https://chromium-review.googlesource.com/c/chromium/src/+/5529018

* 5526324: [Code Health] Add deprecation comment for base::SupportsWeakPtr.
https://chromium-review.googlesource.com/c/chromium/src/+/5526324

Note that this CL actually does make `SupportsWeakPtr` strictly restricted to existing implementations, no new ones. We could add a patch to add ourselves to this list, but it looks like we'll have to refactor this anyways in the near future. Since the refactor seems straightforward, let's try that first.

* chore: bump chromium in DEPS to 128.0.6598.0

* chore: update patches

* 5704737: Rename ExclusiveAccessContext::GetActiveWebContents to avoid conflict
https://chromium-review.googlesource.com/c/chromium/src/+/5704737

* chore: bump chromium in DEPS to 128.0.6601.0

* chore: update patches

* Add `base::StringPiece` header includes

Chromium is working on replacing `base::StringPiece` with `std::string_view`. (See the Chromium Bug below.) They're currently running mass codemods (across many multiple changes) to replace uses of `StringPiece` with `string_view`, including removing the header include for `StringPiece` in those files. This cascades down to our files that were implicitly depending on those includes through some other include.

They're on track to eventually deprecate and remove `StringPiece` so our code should be converted, but that can be done as an upgrade follow-up task. For now, adding the header back to files that need it should suffice for minimal upgrade changes.

Chromium Bug: https://issues.chromium.org/issues/40506050

* 5702737: GlobalRequestID: Avoid unwanted inlining and narrowing int conversions
https://chromium-review.googlesource.com/c/chromium/src/+/5702737

contender for smallest commit 2024

* 5706534: Rename GlobalFeatures to GlobalDesktopFeatures.
https://chromium-review.googlesource.com/c/chromium/src/+/5706534

* 5691321: ui: remove params variants of SelectFile listener functions
https://chromium-review.googlesource.com/c/chromium/src/+/5691321

* 5714949: [Extensions] Display re-enable dialog for MV2 disabled stage
https://chromium-review.googlesource.com/c/chromium/src/+/5714949

* chore: update libc++ filenames

* patch: disable scope reuse & associated dchecks in v8 (hopefully temp, upgrade follow-up)

* fixup! Add `base::StringPiece` header includes

* update MAS patch

5710330: Add crash keys to debug NativeWidgetMacNSWindowBorderlessFrame exception
https://chromium-review.googlesource.com/c/chromium/src/+/5710330

* chore: bump chromium in DEPS to 128.0.6603.0

* chore: update patches

* 5713258: Reland "Preparation for decoupling creation/initialization of context"
https://chromium-review.googlesource.com/c/chromium/src/+/5713258

When destroying a context, it must already be shutdown, and this change enforces it with a new CHECK.

We were overriding `BrowserContextKeyedServiceFactory::BrowserContextShutdown` with an empty implementation, which differed from the default implementation that notifies the `KeyedServiceFactory` that the context has shutdown. Since we were missing this notification, the CHECK would later trip when the service was being destoryed because it was not registered as shutdown when it was shutdown.

* chore: bump chromium in DEPS to 128.0.6605.2

* chore: update patches

* refactor: linux open/save dialog patch

Our existing implementation was relying on an opaque `void* params` parameter that was passed through `ui::SelectFileDialog`.

Recently, that parameter has been getting removed:
- 5691321: ui: remove params variants of SelectFile listener functions | https://chromium-review.googlesource.com/c/chromium/src/+/5691321
- 5709097: ui: remove SelectFileDialog impl params | https://chromium-review.googlesource.com/c/chromium/src/+/5709097
- https://issues.chromium.org/issues/340178601 "reconsider SelectFileDialog"

This restructures the patch to work with mostly the same mechanics, but directly on the `ui::SelectFileDialog` object. This nets us some wins in terms of a smaller patch.

* 5713262: DevTools UI binding AIDA client event returns response
https://chromium-review.googlesource.com/c/chromium/src/+/5713262

* fixup! refactor: linux open/save dialog patch

* chore: bump chromium in DEPS to 128.0.6606.0

* chore: update patches

* fixup! refactor: linux open/save dialog patch

* chore: bump chromium in DEPS to 128.0.6607.0

* chore: update printing.patch

Xref: https://chromium-review.googlesource.com/c/chromium/src/+/5722937

* fix: pwd error in electron-test, nan-test

fix: unshallow depot_tools before 3-way apply

* chore: e patches all

* fixup! fix: pwd error in electron-test, nan-test

* chore: bump chromium in DEPS to 128.0.6609.0

* chore: bump chromium in DEPS to 128.0.6611.0

* chore: update patches

* chore: update libcxx filenames

---------

Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com>
Co-authored-by: clavin <clavin@electronjs.org>
Co-authored-by: Charles Kerr <charles@charleskerr.com>
Co-authored-by: Alice Zhao <alice@makenotion.com>
2024-07-23 08:59:44 -07:00

346 lines
12 KiB
C++

// Copyright (c) 2022 Microsoft, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/usb/usb_chooser_context.h"
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/strings/string_piece.h"
#include "base/task/sequenced_task_runner.h"
#include "base/values.h"
#include "build/build_config.h"
#include "components/content_settings/core/common/content_settings.h"
#include "content/public/browser/device_service.h"
#include "services/device/public/cpp/usb/usb_ids.h"
#include "services/device/public/mojom/usb_device.mojom.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/usb_device_info_converter.h"
#include "shell/common/node_includes.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
constexpr char kDeviceNameKey[] = "productName";
constexpr char kDeviceIdKey[] = "deviceId";
constexpr int kUsbClassMassStorage = 0x08;
bool CanStorePersistentEntry(const device::mojom::UsbDeviceInfo& device_info) {
return device_info.serial_number && !device_info.serial_number->empty();
}
bool IsMassStorageInterface(const device::mojom::UsbInterfaceInfo& interface) {
for (auto& alternate : interface.alternates) {
if (alternate->class_code == kUsbClassMassStorage)
return true;
}
return false;
}
bool ShouldExposeDevice(const device::mojom::UsbDeviceInfo& device_info) {
// blink::USBDevice::claimInterface() disallows claiming mass storage
// interfaces, but explicitly prevent access in the browser process as
// ChromeOS would allow these interfaces to be claimed.
for (auto& configuration : device_info.configurations) {
if (configuration->interfaces.size() == 0) {
return true;
}
for (auto& interface : configuration->interfaces) {
if (!IsMassStorageInterface(*interface))
return true;
}
}
return false;
}
} // namespace
namespace electron {
void UsbChooserContext::DeviceObserver::OnDeviceAdded(
const device::mojom::UsbDeviceInfo& device_info) {}
void UsbChooserContext::DeviceObserver::OnDeviceRemoved(
const device::mojom::UsbDeviceInfo& device_info) {}
void UsbChooserContext::DeviceObserver::OnDeviceManagerConnectionError() {}
UsbChooserContext::UsbChooserContext(ElectronBrowserContext* context)
: browser_context_(context) {}
// static
base::Value UsbChooserContext::DeviceInfoToValue(
const device::mojom::UsbDeviceInfo& device_info) {
base::Value::Dict device_value;
device_value.Set(kDeviceNameKey, device_info.product_name
? *device_info.product_name
: base::StringPiece16());
device_value.Set(kDeviceVendorIdKey, device_info.vendor_id);
device_value.Set(kDeviceProductIdKey, device_info.product_id);
if (device_info.manufacturer_name) {
device_value.Set("manufacturerName", *device_info.manufacturer_name);
}
// CanStorePersistentEntry checks if |device_info.serial_number| is not empty.
if (CanStorePersistentEntry(device_info)) {
device_value.Set(kDeviceSerialNumberKey, *device_info.serial_number);
}
device_value.Set(kDeviceIdKey, device_info.guid);
device_value.Set("usbVersionMajor", device_info.usb_version_major);
device_value.Set("usbVersionMinor", device_info.usb_version_minor);
device_value.Set("usbVersionSubminor", device_info.usb_version_subminor);
device_value.Set("deviceClass", device_info.class_code);
device_value.Set("deviceSubclass", device_info.subclass_code);
device_value.Set("deviceProtocol", device_info.protocol_code);
device_value.Set("deviceVersionMajor", device_info.device_version_major);
device_value.Set("deviceVersionMinor", device_info.device_version_minor);
device_value.Set("deviceVersionSubminor",
device_info.device_version_subminor);
return base::Value(std::move(device_value));
}
void UsbChooserContext::InitDeviceList(
std::vector<device::mojom::UsbDeviceInfoPtr> devices) {
for (auto& device_info : devices) {
DCHECK(device_info);
if (ShouldExposeDevice(*device_info)) {
devices_.insert(
std::make_pair(device_info->guid, std::move(device_info)));
}
}
is_initialized_ = true;
while (!pending_get_devices_requests_.empty()) {
std::vector<device::mojom::UsbDeviceInfoPtr> device_list;
for (const auto& entry : devices_) {
device_list.push_back(entry.second->Clone());
}
std::move(pending_get_devices_requests_.front())
.Run(std::move(device_list));
pending_get_devices_requests_.pop();
}
}
void UsbChooserContext::EnsureConnectionWithDeviceManager() {
if (device_manager_)
return;
// Receive mojo::Remote<UsbDeviceManager> from DeviceService.
content::GetDeviceService().BindUsbDeviceManager(
device_manager_.BindNewPipeAndPassReceiver());
SetUpDeviceManagerConnection();
}
void UsbChooserContext::SetUpDeviceManagerConnection() {
DCHECK(device_manager_);
device_manager_.set_disconnect_handler(
base::BindOnce(&UsbChooserContext::OnDeviceManagerConnectionError,
base::Unretained(this)));
// Listen for added/removed device events.
DCHECK(!client_receiver_.is_bound());
device_manager_->EnumerateDevicesAndSetClient(
client_receiver_.BindNewEndpointAndPassRemote(),
base::BindOnce(&UsbChooserContext::InitDeviceList,
weak_factory_.GetWeakPtr()));
}
UsbChooserContext::~UsbChooserContext() {
OnDeviceManagerConnectionError();
for (auto& observer : device_observer_list_) {
observer.OnBrowserContextShutdown();
DCHECK(!device_observer_list_.HasObserver(&observer));
}
}
void UsbChooserContext::RevokeDevicePermissionWebInitiated(
const url::Origin& origin,
const device::mojom::UsbDeviceInfo& device) {
DCHECK(base::Contains(devices_, device.guid));
RevokeObjectPermissionInternal(origin, DeviceInfoToValue(device),
/*revoked_by_website=*/true);
}
void UsbChooserContext::RevokeObjectPermissionInternal(
const url::Origin& origin,
const base::Value& object,
bool revoked_by_website = false) {
const base::Value::Dict* object_dict = object.GetIfDict();
DCHECK(object_dict != nullptr);
if (object_dict->FindString(kDeviceSerialNumberKey) != nullptr) {
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context_->GetPermissionControllerDelegate());
permission_manager->RevokeDevicePermission(
static_cast<blink::PermissionType>(
WebContentsPermissionHelper::PermissionType::USB),
origin, object, browser_context_);
} else {
const std::string* guid = object_dict->FindString(kDeviceIdKey);
auto it = ephemeral_devices_.find(origin);
if (it != ephemeral_devices_.end()) {
it->second.erase(*guid);
if (it->second.empty())
ephemeral_devices_.erase(it);
}
}
api::Session* session = api::Session::FromBrowserContext(browser_context_);
if (session) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("device", object);
details.Set("origin", origin.Serialize());
session->Emit("usb-device-revoked", details);
}
}
void UsbChooserContext::GrantDevicePermission(
const url::Origin& origin,
const device::mojom::UsbDeviceInfo& device_info) {
if (CanStorePersistentEntry(device_info)) {
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context_->GetPermissionControllerDelegate());
permission_manager->GrantDevicePermission(
static_cast<blink::PermissionType>(
WebContentsPermissionHelper::PermissionType::USB),
origin, DeviceInfoToValue(device_info), browser_context_);
} else {
ephemeral_devices_[origin].insert(device_info.guid);
}
}
bool UsbChooserContext::HasDevicePermission(
const url::Origin& origin,
const device::mojom::UsbDeviceInfo& device_info) {
auto it = ephemeral_devices_.find(origin);
if (it != ephemeral_devices_.end() &&
base::Contains(it->second, device_info.guid)) {
return true;
}
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context_->GetPermissionControllerDelegate());
return permission_manager->CheckDevicePermission(
static_cast<blink::PermissionType>(
WebContentsPermissionHelper::PermissionType::USB),
origin, DeviceInfoToValue(device_info), browser_context_);
}
void UsbChooserContext::GetDevices(
device::mojom::UsbDeviceManager::GetDevicesCallback callback) {
if (!is_initialized_) {
EnsureConnectionWithDeviceManager();
pending_get_devices_requests_.push(std::move(callback));
return;
}
std::vector<device::mojom::UsbDeviceInfoPtr> device_list;
for (const auto& pair : devices_) {
device_list.push_back(pair.second->Clone());
}
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), std::move(device_list)));
}
void UsbChooserContext::GetDevice(
const std::string& guid,
base::span<const uint8_t> blocked_interface_classes,
mojo::PendingReceiver<device::mojom::UsbDevice> device_receiver,
mojo::PendingRemote<device::mojom::UsbDeviceClient> device_client) {
EnsureConnectionWithDeviceManager();
device_manager_->GetDevice(
guid,
std::vector<uint8_t>(blocked_interface_classes.begin(),
blocked_interface_classes.end()),
std::move(device_receiver), std::move(device_client));
}
const device::mojom::UsbDeviceInfo* UsbChooserContext::GetDeviceInfo(
const std::string& guid) {
DCHECK(is_initialized_);
auto it = devices_.find(guid);
return it == devices_.end() ? nullptr : it->second.get();
}
void UsbChooserContext::AddObserver(DeviceObserver* observer) {
EnsureConnectionWithDeviceManager();
device_observer_list_.AddObserver(observer);
}
void UsbChooserContext::RemoveObserver(DeviceObserver* observer) {
device_observer_list_.RemoveObserver(observer);
}
base::WeakPtr<UsbChooserContext> UsbChooserContext::AsWeakPtr() {
return weak_factory_.GetWeakPtr();
}
void UsbChooserContext::OnDeviceAdded(
device::mojom::UsbDeviceInfoPtr device_info) {
DCHECK(device_info);
// Update the device list.
DCHECK(!base::Contains(devices_, device_info->guid));
if (!ShouldExposeDevice(*device_info))
return;
devices_.insert(std::make_pair(device_info->guid, device_info->Clone()));
// Notify all observers.
for (auto& observer : device_observer_list_)
observer.OnDeviceAdded(*device_info);
}
void UsbChooserContext::OnDeviceRemoved(
device::mojom::UsbDeviceInfoPtr device_info) {
DCHECK(device_info);
if (!ShouldExposeDevice(*device_info)) {
DCHECK(!base::Contains(devices_, device_info->guid));
return;
}
// Update the device list.
DCHECK(base::Contains(devices_, device_info->guid));
devices_.erase(device_info->guid);
// Notify all device observers.
for (auto& observer : device_observer_list_)
observer.OnDeviceRemoved(*device_info);
// If the device was persistent, return. Otherwise, notify all permission
// observers that its permissions were revoked.
if (device_info->serial_number &&
!device_info->serial_number.value().empty()) {
return;
}
for (auto& map_entry : ephemeral_devices_) {
map_entry.second.erase(device_info->guid);
}
}
void UsbChooserContext::OnDeviceManagerConnectionError() {
device_manager_.reset();
client_receiver_.reset();
devices_.clear();
is_initialized_ = false;
ephemeral_devices_.clear();
// Notify all device observers.
for (auto& observer : device_observer_list_)
observer.OnDeviceManagerConnectionError();
}
} // namespace electron