File: hid.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (433 lines) | stat: -rw-r--r-- 15,814 bytes parent folder | download | duplicates (6)
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
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/modules/hid/hid.h"

#include <utility>

#include "services/device/public/cpp/device_features.h"
#include "services/network/public/mojom/permissions_policy/permissions_policy_feature.mojom-blink.h"
#include "third_party/blink/public/mojom/service_worker/service_worker.mojom-blink.h"
#include "third_party/blink/public/platform/browser_interface_broker_proxy.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_hid_device_filter.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_hid_device_request_options.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/execution_context/navigator_base.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/hid/hid_connection_event.h"
#include "third_party/blink/renderer/modules/hid/hid_device.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"

namespace blink {

namespace {

const char kContextGone[] = "Script context has shut down.";
const char kFeaturePolicyBlocked[] =
    "Access to the feature \"hid\" is disallowed by permissions policy.";

// Carries out basic checks for the web-exposed APIs, to make sure the minimum
// requirements for them to be served are met. Returns true if any conditions
// fail to be met, generating an appropriate exception as well. Otherwise,
// returns false to indicate the call should be allowed.
bool ShouldBlockHidServiceCall(LocalDOMWindow* window,
                               ExecutionContext* context,
                               ExceptionState* exception_state) {
  if (!context) {
    if (exception_state) {
      exception_state->ThrowDOMException(DOMExceptionCode::kNotSupportedError,
                                         kContextGone);
    }
    return true;
  }

  // For window and dedicated workers, reject the request if the top-level frame
  // has an opaque origin. For Service Workers, we use their security origin
  // directly as they do not use delegated permissions.
  const SecurityOrigin* security_origin = nullptr;
  if (context->IsWindow()) {
    security_origin =
        window->GetFrame()->Top()->GetSecurityContext()->GetSecurityOrigin();
  } else if (context->IsDedicatedWorkerGlobalScope()) {
    security_origin = static_cast<WorkerGlobalScope*>(context)
                          ->top_level_frame_security_origin();
  } else if (context->IsServiceWorkerGlobalScope()) {
    security_origin = context->GetSecurityOrigin();
  } else {
    NOTREACHED();
  }
  if (security_origin->IsOpaque()) {
    if (exception_state) {
      exception_state->ThrowSecurityError(
          "Access to the WebHID API is denied from contexts where the "
          "top-level "
          "document has an opaque origin.");
    }
    return true;
  }

  if (!context->IsFeatureEnabled(network::mojom::PermissionsPolicyFeature::kHid,
                                 ReportOptions::kReportOnFailure)) {
    if (exception_state) {
      exception_state->ThrowSecurityError(kFeaturePolicyBlocked);
    }
    return true;
  }

  return false;
}

void RejectWithTypeError(const String& message,
                         ScriptPromiseResolverBase* resolver) {
  ScriptState::Scope scope(resolver->GetScriptState());
  v8::Isolate* isolate = resolver->GetScriptState()->GetIsolate();
  resolver->Reject(V8ThrowException::CreateTypeError(isolate, message));
}

}  // namespace

const char HID::kSupplementName[] = "HID";

HID* HID::hid(NavigatorBase& navigator) {
  HID* hid = Supplement<NavigatorBase>::From<HID>(navigator);
  if (!hid) {
    hid = MakeGarbageCollected<HID>(navigator);
    ProvideTo(navigator, hid);
  }
  return hid;
}

HID::HID(NavigatorBase& navigator)
    : Supplement<NavigatorBase>(navigator),
      service_(navigator.GetExecutionContext()),
      receiver_(this, navigator.GetExecutionContext()) {
  if (!base::FeatureList::IsEnabled(
          features::kWebHidAttributeAllowsBackForwardCache)) {
    auto* context = GetExecutionContext();
    if (context) {
      feature_handle_for_scheduler_ = context->GetScheduler()->RegisterFeature(
          SchedulingPolicy::Feature::kWebHID,
          {SchedulingPolicy::DisableBackForwardCache()});
    }
  }
}

HID::~HID() {
  DCHECK(get_devices_promises_.empty());
  DCHECK(request_device_promises_.empty());
}

ExecutionContext* HID::GetExecutionContext() const {
  return GetSupplementable()->GetExecutionContext();
}

const AtomicString& HID::InterfaceName() const {
  return event_target_names::kHID;
}

void HID::AddedEventListener(const AtomicString& event_type,
                             RegisteredEventListener& listener) {
  EventTarget::AddedEventListener(event_type, listener);

  if (event_type != event_type_names::kConnect &&
      event_type != event_type_names::kDisconnect) {
    return;
  }

  auto* context = GetExecutionContext();
  if (ShouldBlockHidServiceCall(GetSupplementable()->DomWindow(), context,
                                nullptr)) {
    return;
  }

  if (context->IsServiceWorkerGlobalScope()) {
    auto* service_worker_global_scope =
        static_cast<ServiceWorkerGlobalScope*>(context);
    if (service_worker_global_scope->did_evaluate_script()) {
      String message = String::Format(
          "Event handler of '%s' event must be added on the initial evaluation "
          "of worker script. More info: "
          "https://developer.chrome.com/docs/extensions/mv3/service_workers/"
          "events/",
          event_type.Utf8().c_str());
      GetExecutionContext()->AddConsoleMessage(
          mojom::blink::ConsoleMessageSource::kJavaScript,
          mojom::blink::ConsoleMessageLevel::kWarning, message);
    }
  }

  EnsureServiceConnection();
}

void HID::DeviceAdded(device::mojom::blink::HidDeviceInfoPtr device_info) {
  auto* device = GetOrCreateDevice(std::move(device_info));

  DispatchEvent(*MakeGarbageCollected<HIDConnectionEvent>(
      event_type_names::kConnect, device));
}

void HID::DeviceRemoved(device::mojom::blink::HidDeviceInfoPtr device_info) {
  auto* device = GetOrCreateDevice(std::move(device_info));

  DispatchEvent(*MakeGarbageCollected<HIDConnectionEvent>(
      event_type_names::kDisconnect, device));
}

void HID::DeviceChanged(device::mojom::blink::HidDeviceInfoPtr device_info) {
  auto it = device_cache_.find(device_info->guid);
  if (it != device_cache_.end()) {
    it->value->UpdateDeviceInfo(std::move(device_info));
    return;
  }

  // If the GUID is not in the |device_cache_| then this is the first time we
  // have been notified for this device.
  DeviceAdded(std::move(device_info));
}

ScriptPromise<IDLSequence<HIDDevice>> HID::getDevices(
    ScriptState* script_state,
    ExceptionState& exception_state) {
  if (ShouldBlockHidServiceCall(GetSupplementable()->DomWindow(),
                                GetExecutionContext(), &exception_state)) {
    return ScriptPromise<IDLSequence<HIDDevice>>();
  }

  auto* resolver = MakeGarbageCollected<HIDDeviceResolver>(
      script_state, exception_state.GetContext());
  get_devices_promises_.insert(resolver);

  EnsureServiceConnection();
  service_->GetDevices(WTF::BindOnce(
      &HID::FinishGetDevices, WrapPersistent(this), WrapPersistent(resolver)));
  return resolver->Promise();
}

ScriptPromise<IDLSequence<HIDDevice>> HID::requestDevice(
    ScriptState* script_state,
    const HIDDeviceRequestOptions* options,
    ExceptionState& exception_state) {
  // requestDevice requires a window to satisfy the user activation requirement
  // and to show a chooser dialog.
  auto* window = GetSupplementable()->DomWindow();
  if (!window) {
    exception_state.ThrowDOMException(DOMExceptionCode::kNotSupportedError,
                                      kContextGone);
    return ScriptPromise<IDLSequence<HIDDevice>>();
  }

  if (ShouldBlockHidServiceCall(window, GetExecutionContext(),
                                &exception_state)) {
    return ScriptPromise<IDLSequence<HIDDevice>>();
  }

  if (!LocalFrame::HasTransientUserActivation(window->GetFrame())) {
    exception_state.ThrowSecurityError(
        "Must be handling a user gesture to show a permission request.");
    return ScriptPromise<IDLSequence<HIDDevice>>();
  }

  auto* resolver = MakeGarbageCollected<HIDDeviceResolver>(
      script_state, exception_state.GetContext());
  auto promise = resolver->Promise();
  request_device_promises_.insert(resolver);

  Vector<mojom::blink::HidDeviceFilterPtr> mojo_filters;
  if (options->hasFilters()) {
    mojo_filters.reserve(options->filters().size());
    for (const auto& filter : options->filters()) {
      String error_message = CheckDeviceFilterValidity(*filter);
      if (error_message) {
        RejectWithTypeError(error_message, resolver);
        return promise;
      }
      mojo_filters.push_back(ConvertDeviceFilter(*filter));
    }
  }
  DCHECK_EQ(options->filters().size(), mojo_filters.size());

  Vector<mojom::blink::HidDeviceFilterPtr> mojo_exclusion_filters;
  if (options->hasExclusionFilters()) {
    if (options->exclusionFilters().size() == 0) {
      exception_state.ThrowTypeError(
          "'exclusionFilters', if present, must contain at least one filter.");
      return ScriptPromise<IDLSequence<HIDDevice>>();
    }
    mojo_exclusion_filters.reserve(options->exclusionFilters().size());
    for (const auto& exclusion_filter : options->exclusionFilters()) {
      String error_message = CheckDeviceFilterValidity(*exclusion_filter);
      if (error_message) {
        RejectWithTypeError(error_message, resolver);
        return promise;
      }
      mojo_exclusion_filters.push_back(ConvertDeviceFilter(*exclusion_filter));
    }
    DCHECK_EQ(options->exclusionFilters().size(),
              mojo_exclusion_filters.size());
  }

  EnsureServiceConnection();
  service_->RequestDevice(
      std::move(mojo_filters), std::move(mojo_exclusion_filters),
      WTF::BindOnce(&HID::FinishRequestDevice, WrapPersistent(this),
                    WrapPersistent(resolver)));
  return promise;
}

void HID::Connect(
    const String& device_guid,
    mojo::PendingRemote<device::mojom::blink::HidConnectionClient> client,
    device::mojom::blink::HidManager::ConnectCallback callback) {
  EnsureServiceConnection();
  service_->Connect(device_guid, std::move(client), std::move(callback));
}

void HID::Forget(device::mojom::blink::HidDeviceInfoPtr device_info,
                 mojom::blink::HidService::ForgetCallback callback) {
  EnsureServiceConnection();
  service_->Forget(std::move(device_info), std::move(callback));
}

HIDDevice* HID::GetOrCreateDevice(device::mojom::blink::HidDeviceInfoPtr info) {
  auto it = device_cache_.find(info->guid);
  if (it != device_cache_.end()) {
    return it->value.Get();
  }

  const String guid = info->guid;
  HIDDevice* device = MakeGarbageCollected<HIDDevice>(this, std::move(info),
                                                      GetExecutionContext());
  device_cache_.insert(guid, device);
  return device;
}

void HID::FinishGetDevices(
    HIDDeviceResolver* resolver,
    Vector<device::mojom::blink::HidDeviceInfoPtr> device_infos) {
  DCHECK(get_devices_promises_.Contains(resolver));
  get_devices_promises_.erase(resolver);

  HeapVector<Member<HIDDevice>> devices;
  for (auto& device_info : device_infos)
    devices.push_back(GetOrCreateDevice(std::move(device_info)));

  resolver->Resolve(devices);
}

void HID::FinishRequestDevice(
    HIDDeviceResolver* resolver,
    Vector<device::mojom::blink::HidDeviceInfoPtr> device_infos) {
  DCHECK(request_device_promises_.Contains(resolver));
  request_device_promises_.erase(resolver);

  HeapVector<Member<HIDDevice>> devices;
  for (auto& device_info : device_infos) {
    auto* device = GetOrCreateDevice(std::move(device_info));
    device->ResetIsForgotten();
    devices.push_back(device);
  }

  resolver->Resolve(devices);
}

void HID::EnsureServiceConnection() {
  DCHECK(GetExecutionContext());

  if (service_.is_bound())
    return;

  auto task_runner =
      GetExecutionContext()->GetTaskRunner(TaskType::kMiscPlatformAPI);
  GetExecutionContext()->GetBrowserInterfaceBroker().GetInterface(
      service_.BindNewPipeAndPassReceiver(task_runner));
  service_.set_disconnect_handler(
      WTF::BindOnce(&HID::CloseServiceConnection, WrapWeakPersistent(this)));
  DCHECK(!receiver_.is_bound());
  service_->RegisterClient(receiver_.BindNewEndpointAndPassRemote(task_runner));
}

void HID::CloseServiceConnection() {
  service_.reset();
  receiver_.reset();

  // Script may execute during a call to Resolve(). Swap these sets to prevent
  // concurrent modification.
  HeapHashSet<Member<HIDDeviceResolver>> get_devices_promises;
  get_devices_promises_.swap(get_devices_promises);
  for (HIDDeviceResolver* resolver : get_devices_promises) {
    resolver->Resolve(HeapVector<Member<HIDDevice>>());
  }

  HeapHashSet<Member<HIDDeviceResolver>> request_device_promises;
  request_device_promises_.swap(request_device_promises);
  for (HIDDeviceResolver* resolver : request_device_promises) {
    resolver->Resolve(HeapVector<Member<HIDDevice>>());
  }
}

mojom::blink::HidDeviceFilterPtr HID::ConvertDeviceFilter(
    const HIDDeviceFilter& filter) {
  DCHECK(!CheckDeviceFilterValidity(filter));

  auto mojo_filter = mojom::blink::HidDeviceFilter::New();
  if (filter.hasVendorId()) {
    if (filter.hasProductId()) {
      mojo_filter->device_ids =
          mojom::blink::DeviceIdFilter::NewVendorAndProduct(
              mojom::blink::VendorAndProduct::New(filter.vendorId(),
                                                  filter.productId()));
    } else {
      mojo_filter->device_ids =
          mojom::blink::DeviceIdFilter::NewVendor(filter.vendorId());
    }
  }
  if (filter.hasUsagePage()) {
    if (filter.hasUsage()) {
      mojo_filter->usage = mojom::blink::UsageFilter::NewUsageAndPage(
          device::mojom::blink::HidUsageAndPage::New(filter.usage(),
                                                     filter.usagePage()));
    } else {
      mojo_filter->usage =
          mojom::blink::UsageFilter::NewPage(filter.usagePage());
    }
  }
  return mojo_filter;
}

String HID::CheckDeviceFilterValidity(const HIDDeviceFilter& filter) {
  if (!filter.hasVendorId() && !filter.hasProductId() &&
      !filter.hasUsagePage() && !filter.hasUsage()) {
    return "A filter must provide a property to filter by.";
  }

  if (filter.hasProductId() && !filter.hasVendorId()) {
    return "A filter containing a productId must also contain a vendorId.";
  }

  if (filter.hasUsage() && !filter.hasUsagePage()) {
    return "A filter containing a usage must also contain a usagePage.";
  }

  return String();
}

void HID::Trace(Visitor* visitor) const {
  visitor->Trace(service_);
  visitor->Trace(get_devices_promises_);
  visitor->Trace(request_device_promises_);
  visitor->Trace(device_cache_);
  visitor->Trace(receiver_);
  EventTarget::Trace(visitor);
  Supplement<NavigatorBase>::Trace(visitor);
}

}  // namespace blink