electron/shell/browser/serial/serial_chooser_context.cc
electron-roller[bot] dd03cceda0
chore: bump chromium to 137.0.7128.1 (main) (#46482)
* chore: bump chromium in DEPS to 137.0.7107.0

* chore: bump chromium in DEPS to 137.0.7109.0

* chore: bump chromium in DEPS to 137.0.7111.0

* chore: bump chromium in DEPS to 137.0.7113.0

* 6384240: Remove double-declaration for accessibility on macOS | 6384240

* 6422872: Remove unused includes in isolation_info_mojom_traits.h | 6422872

* chore: update patches

* 6400733: Avoid ipc_message_macros.h usage in some foo_param_traits_macros.h files | 6400733

* chore: update patches

* 6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

* chore: iwyu

* refactor: prefer value initialization over memset()

From the looks up upstream commits in base/, it looks like memset()
could trigger `-Wunsafe-buffer-usage` warnings soon?

Value initialization is more C++ish and less error-prone anyway,
due to memset()'s easily swappable parameters.

* refactor: NotifyIcon::InitIconData() returns a NOTIFYICONDATA

This follows F.20 in the C++ Core Guidelines and also removes the need
for memset()

* 6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

remove all uses of:

- strcmp()

* fixup!  6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

* 6433203: Add a PassKey to RegisterDeleteDelegateCallback(). | 6433203

* chore: bump chromium in DEPS to 137.0.7115.0

* 6387077: [PermissionOptions] Generalize PermissionRequestDescription | 6387077

* chore: update patches

* 6387077: [PermissionOptions] Generalize PermissionRequestDescription | 6387077

* fix: add pragma for MacSDK unsafe buffers | 6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

* chore: bump chromium in DEPS to 137.0.7117.0

* chore: update patches

* chore: update filesnames.libcxx.gni

* 6431756: Replace SetOwnedByWidget() bool arg with a PassKey. | 6431756

* 6387077: [PermissionOptions] Generalize PermissionRequestDescription | 6387077

* 6428345: Remove ExtensionService usage from ChromeExtensionRegistrarDelegate | 6428345

* 6384315: Migrate extensions_enabled from ExtensionService to Registrar | 6384315

* 6428749: [extensions] Refactor ExtensionService for AddNewAndUpdateExtension. | 6428749

* chore: bump chromium in DEPS to 137.0.7119.0

* 6440290: corner-shape: support inset shadow | 6440290

* 6429230: FSA: Move blocked paths to the PermissionContext class | 6429230

* chore: update patches

* chore: bump chromium in DEPS to 137.0.7121.0

* chore: update patches

* fix: partially revert 6443473: Remove ItemDelete from the Mac version of AppleKeychain | 6443473

* fix: update filenames.libcxx.gni

* chore: bump chromium in DEPS to 137.0.7123.0

* chore: update patches

* chore: "grandfather in" electron views too

Lock further access to View::set_owned_by_client() | 6448510

* chore: update feat_corner_smoothing_css_rule_and_blink_painting.patch

corner-shape: support inset shadow | 6440290

* refactor: grandfather in AutofillPopupView as a subclass of WidgetDelegateView

Add a PassKey for std::make_unique<WidgetDelegateView>() | 6442265

* Provide dbus appmenu information on Wayland | 6405535

* [extensions] Move OnExtensionInstalled out of ExtensionService. | 6443325

* refactor: grandfather in NativeWindowViews for delete callbacks

6433203: Add a PassKey to RegisterDeleteDelegateCallback(). | 6433203

* chore: merge the four "grandfather" patches into one

* [A11yPerformance] Remove IsAccessibilityAllowed() | 6404386: [A11yPerformance] Remove IsAccessibilityAllowed() | 6404386

NB: the changes here are copied from the upstream changes in
chrome/browser/ui/webui/accessibility/accessibility_ui.cc

* 6420753: [PermissionOptions] Use PermissionDescriptorPtr in PermissionController | 6420753

* 6429573: [accessibility] Move mode change out of AccessibilityNotificationWaiter | 6429573

* chore: e patches all

* 6419936: [win] Change ScreenWin public static methods to virtual | 6419936

* 6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

remove all uses of:

- fprintf()
- fputs()
- snprintf()
- vsnprintf()

* fix: size conversion FTBFS on Win

* 6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

remove all uses of:

- wcscpy_s()

* 6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

remove all uses of:

- wcsncpy_s()

* chore: update mas_avoid_private_macos_api_usage.patch.patch

6394283: Remove double-declaration for accessibility on iOS | 6394283

Lots of context shear in this commit but the only interesting part is:

-+  return nullptr;
++  return {};

Which is needed because the return type is sometimes not a pointer.

* chore: e patches all

* chore: disable -Wmacro-redefined warning in electron_main_win.cc

* chore: bump chromium in DEPS to 137.0.7123.5

* refactor: patch electron PermissionTypes into blink

6387077: [PermissionOptions] Generalize PermissionRequestDescription | 6387077

* chore: e patches all

* chore: remove the box_painter_base.cc part of feat_corner_smoothing_css_rule_and_blink_painting.patch

as per code review @ https://github.com/electron/electron/pull/46482#pullrequestreview-2777338370

* test: enable window-smaller-than-64x64 test on Linux

* chore: bump chromium in DEPS to 137.0.7124.1

* chore: bump chromium in DEPS to 137.0.7125.1

* chore: bump chromium in DEPS to 137.0.7127.3

* 6459201: [Extensions] Remove ExtensionSystem::FinishDelayedInstallationIfReady() | 6459201

* 6454796: [Extensions] Move (most) registrar delayed install logic to //extensions | 6454796

* chore: bump chromium in DEPS to 137.0.7128.1

* chore: e patches all

* chore: node ./script/gen-libc++-filenames.js

* [views] Gate DesktopWindowTreeHostWin::window_enlargement_ behind flag

Refs 6428649

* feat: allow opt-out animated_content_sampler.

Refs 6438681

* Trigger CI

---------

Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com>
Co-authored-by: Keeley Hammond <khammond@slack-corp.com>
Co-authored-by: Charles Kerr <charles@charleskerr.com>
Co-authored-by: Keeley Hammond <vertedinde@electronjs.org>
Co-authored-by: deepak1556 <hop2deep@gmail.com>
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
2025-04-22 15:53:29 -04:00

289 lines
9.9 KiB
C++

// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "shell/browser/serial/serial_chooser_context.h"
#include <string>
#include <string_view>
#include <utility>
#include "base/base64.h"
#include "base/command_line.h"
#include "base/values.h"
#include "chrome/browser/serial/serial_blocklist.h"
#include "content/public/browser/device_service.h"
#include "content/public/browser/web_contents.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/serial_port_info_converter.h"
namespace electron {
namespace {
std::string EncodeToken(const base::UnguessableToken& token) {
const uint64_t data[2] = {token.GetHighForSerialization(),
token.GetLowForSerialization()};
return base::Base64Encode(base::as_byte_span(data));
}
base::Value PortInfoToValue(const device::mojom::SerialPortInfo& port) {
base::Value::Dict value;
if (port.display_name && !port.display_name->empty()) {
value.Set(kPortNameKey, *port.display_name);
} else {
value.Set(kPortNameKey, port.path.LossyDisplayName());
}
if (!SerialChooserContext::CanStorePersistentEntry(port)) {
value.Set(kTokenKey, EncodeToken(port.token));
return base::Value(std::move(value));
}
if (port.bluetooth_service_class_id &&
port.bluetooth_service_class_id->IsValid()) {
value.Set(kBluetoothDevicePathKey, port.path.LossyDisplayName());
} else {
#if BUILDFLAG(IS_WIN)
// Windows provides a handy device identifier which we can rely on to be
// sufficiently stable for identifying devices across restarts.
value.Set(kDeviceInstanceIdKey, port.device_instance_id);
#else
CHECK(port.has_vendor_id);
value.Set(kVendorIdKey, port.vendor_id);
CHECK(port.has_product_id);
value.Set(kProductIdKey, port.product_id);
CHECK(port.serial_number);
value.Set(kSerialNumberKey, *port.serial_number);
#if BUILDFLAG(IS_MAC)
CHECK(port.usb_driver_name && !port.usb_driver_name->empty());
value.Set(kUsbDriverKey, *port.usb_driver_name);
#endif // BUILDFLAG(IS_MAC)
#endif // BUILDFLAG(IS_WIN)
}
return base::Value(std::move(value));
}
} // namespace
SerialChooserContext::SerialChooserContext(ElectronBrowserContext* context)
: browser_context_(context) {}
SerialChooserContext::~SerialChooserContext() {
// Notify observers that the chooser context is about to be destroyed.
// Observers must remove themselves from the observer lists.
for (auto& observer : port_observer_list_) {
observer.OnSerialChooserContextShutdown();
DCHECK(!port_observer_list_.HasObserver(&observer));
}
}
void SerialChooserContext::GrantPortPermission(
const url::Origin& origin,
const device::mojom::SerialPortInfo& port,
content::RenderFrameHost* render_frame_host) {
port_info_.insert({port.token, port.Clone()});
if (CanStorePersistentEntry(port)) {
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context_->GetPermissionControllerDelegate());
permission_manager->GrantDevicePermission(blink::PermissionType::SERIAL,
origin, PortInfoToValue(port),
browser_context_);
return;
}
ephemeral_ports_[origin].insert(port.token);
}
bool SerialChooserContext::HasPortPermission(
const url::Origin& origin,
const device::mojom::SerialPortInfo& port,
content::RenderFrameHost* render_frame_host) {
bool blocklist_disabled = base::CommandLine::ForCurrentProcess()->HasSwitch(
kDisableSerialBlocklist);
if (!blocklist_disabled && SerialBlocklist::Get().IsExcluded(port)) {
return false;
}
auto it = ephemeral_ports_.find(origin);
if (it != ephemeral_ports_.end()) {
const std::set<base::UnguessableToken>& ports = it->second;
if (ports.contains(port.token))
return true;
}
if (!CanStorePersistentEntry(port))
return false;
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context_->GetPermissionControllerDelegate());
return permission_manager->CheckDevicePermission(
blink::PermissionType::SERIAL, origin, PortInfoToValue(port),
browser_context_);
}
void SerialChooserContext::RevokePortPermissionWebInitiated(
const url::Origin& origin,
const base::UnguessableToken& token,
content::RenderFrameHost* render_frame_host) {
auto it = port_info_.find(token);
if (it != port_info_.end()) {
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context_->GetPermissionControllerDelegate());
permission_manager->RevokeDevicePermission(
blink::PermissionType::SERIAL, origin, PortInfoToValue(*it->second),
browser_context_);
}
auto ephemeral = ephemeral_ports_.find(origin);
if (ephemeral != ephemeral_ports_.end()) {
std::set<base::UnguessableToken>& ports = ephemeral->second;
ports.erase(token);
}
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
api::Session* session =
api::Session::FromBrowserContext(web_contents->GetBrowserContext());
if (session) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("port", it->second);
details.SetGetter("frame", render_frame_host);
details.Set("origin", origin.Serialize());
session->Emit("serial-port-revoked", details);
}
}
// static
bool SerialChooserContext::CanStorePersistentEntry(
const device::mojom::SerialPortInfo& port) {
// If there is no display name then the path name will be used instead. The
// path name is not guaranteed to be stable. For example, on Linux the name
// "ttyUSB0" is reused for any USB serial device. A name like that would be
// confusing to show in settings when the device is disconnected.
if (!port.display_name || port.display_name->empty())
return false;
const bool has_bluetooth = port.bluetooth_service_class_id &&
port.bluetooth_service_class_id->IsValid() &&
!port.path.empty();
if (has_bluetooth) {
return true;
}
#if BUILDFLAG(IS_WIN)
return !port.device_instance_id.empty();
#else
const bool has_usb = port.has_vendor_id && port.has_product_id &&
port.serial_number && !port.serial_number->empty();
if (!has_usb) {
return false;
}
#if BUILDFLAG(IS_MAC)
// The combination of the standard USB vendor ID, product ID and serial
// number properties should be enough to uniquely identify a device
// however recent versions of macOS include built-in drivers for common
// types of USB-to-serial adapters while their manufacturers still
// recommend installing their custom drivers. When both are loaded two
// IOSerialBSDClient instances are found for each device. Including the
// USB driver name allows us to distinguish between the two.
if (!port.usb_driver_name || port.usb_driver_name->empty())
return false;
#endif // BUILDFLAG(IS_MAC)
return true;
#endif // BUILDFLAG(IS_WIN)
}
const device::mojom::SerialPortInfo* SerialChooserContext::GetPortInfo(
const base::UnguessableToken& token) {
DCHECK(is_initialized_);
auto it = port_info_.find(token);
return it == port_info_.end() ? nullptr : it->second.get();
}
device::mojom::SerialPortManager* SerialChooserContext::GetPortManager() {
EnsurePortManagerConnection();
return port_manager_.get();
}
void SerialChooserContext::AddPortObserver(PortObserver* observer) {
port_observer_list_.AddObserver(observer);
}
void SerialChooserContext::RemovePortObserver(PortObserver* observer) {
port_observer_list_.RemoveObserver(observer);
}
base::WeakPtr<SerialChooserContext> SerialChooserContext::AsWeakPtr() {
return weak_factory_.GetWeakPtr();
}
void SerialChooserContext::OnPortAdded(device::mojom::SerialPortInfoPtr port) {
if (!port_info_.contains(port->token))
port_info_.insert({port->token, port->Clone()});
for (auto& map_entry : ephemeral_ports_) {
std::set<base::UnguessableToken>& ports = map_entry.second;
ports.erase(port->token);
}
for (auto& observer : port_observer_list_)
observer.OnPortAdded(*port);
}
void SerialChooserContext::OnPortRemoved(
device::mojom::SerialPortInfoPtr port) {
for (auto& observer : port_observer_list_)
observer.OnPortRemoved(*port);
port_info_.erase(port->token);
}
void SerialChooserContext::EnsurePortManagerConnection() {
if (port_manager_)
return;
mojo::PendingRemote<device::mojom::SerialPortManager> manager;
content::GetDeviceService().BindSerialPortManager(
manager.InitWithNewPipeAndPassReceiver());
SetUpPortManagerConnection(std::move(manager));
}
void SerialChooserContext::SetUpPortManagerConnection(
mojo::PendingRemote<device::mojom::SerialPortManager> manager) {
port_manager_.Bind(std::move(manager));
port_manager_.set_disconnect_handler(
base::BindOnce(&SerialChooserContext::OnPortManagerConnectionError,
base::Unretained(this)));
port_manager_->SetClient(client_receiver_.BindNewPipeAndPassRemote());
port_manager_->GetDevices(base::BindOnce(&SerialChooserContext::OnGetDevices,
weak_factory_.GetWeakPtr()));
}
void SerialChooserContext::OnGetDevices(
std::vector<device::mojom::SerialPortInfoPtr> ports) {
for (auto& port : ports)
port_info_.insert({port->token, std::move(port)});
is_initialized_ = true;
}
void SerialChooserContext::OnPortManagerConnectionError() {
port_manager_.reset();
client_receiver_.reset();
port_info_.clear();
ephemeral_ports_.clear();
}
} // namespace electron