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
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "PresentationRequest.h"
#include <utility>
#include "AvailabilityCollection.h"
#include "ControllerConnectionCollection.h"
#include "Presentation.h"
#include "PresentationAvailability.h"
#include "PresentationCallbacks.h"
#include "PresentationLog.h"
#include "PresentationTransportBuilderConstructor.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/Navigator.h"
#include "mozilla/dom/PresentationConnectionAvailableEvent.h"
#include "mozilla/dom/PresentationRequestBinding.h"
#include "mozilla/dom/Promise.h"
#include "nsContentSecurityManager.h"
#include "nsCycleCollectionParticipant.h"
#include "nsGlobalWindow.h"
#include "nsIPresentationService.h"
#include "nsIURI.h"
#include "nsIUUIDGenerator.h"
#include "nsNetUtil.h"
#include "nsSandboxFlags.h"
#include "nsServiceManagerUtils.h"
namespace mozilla {
namespace dom {
NS_IMPL_ADDREF_INHERITED(PresentationRequest, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(PresentationRequest, DOMEventTargetHelper)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(PresentationRequest)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
static nsresult GetAbsoluteURL(const nsAString& aUrl, nsIURI* aBaseUri,
Document* aDocument, nsAString& aAbsoluteUrl) {
nsCOMPtr<nsIURI> uri;
nsresult rv;
if (aDocument) {
rv = NS_NewURI(getter_AddRefs(uri), aUrl,
aDocument->GetDocumentCharacterSet(), aBaseUri);
} else {
rv = NS_NewURI(getter_AddRefs(uri), aUrl, nullptr, aBaseUri);
}
if (NS_FAILED(rv)) {
return rv;
}
nsAutoCString spec;
uri->GetSpec(spec);
CopyUTF8toUTF16(spec, aAbsoluteUrl);
return NS_OK;
}
/* static */
already_AddRefed<PresentationRequest> PresentationRequest::Constructor(
const GlobalObject& aGlobal, const nsAString& aUrl, ErrorResult& aRv) {
Sequence<nsString> urls;
if (!urls.AppendElement(aUrl, fallible)) {
aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
return nullptr;
}
return Constructor(aGlobal, urls, aRv);
}
/* static */
already_AddRefed<PresentationRequest> PresentationRequest::Constructor(
const GlobalObject& aGlobal, const Sequence<nsString>& aUrls,
ErrorResult& aRv) {
nsCOMPtr<nsPIDOMWindowInner> window =
do_QueryInterface(aGlobal.GetAsSupports());
if (!window) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
if (aUrls.IsEmpty()) {
aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return nullptr;
}
// Resolve relative URL to absolute URL
nsCOMPtr<nsIURI> baseUri = window->GetDocBaseURI();
nsTArray<nsString> urls;
for (const auto& url : aUrls) {
nsAutoString absoluteUrl;
nsresult rv =
GetAbsoluteURL(url, baseUri, window->GetExtantDoc(), absoluteUrl);
if (NS_WARN_IF(NS_FAILED(rv))) {
aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
return nullptr;
}
urls.AppendElement(absoluteUrl);
}
RefPtr<PresentationRequest> request =
new PresentationRequest(window, std::move(urls));
return NS_WARN_IF(!request->Init()) ? nullptr : request.forget();
}
PresentationRequest::PresentationRequest(nsPIDOMWindowInner* aWindow,
nsTArray<nsString>&& aUrls)
: DOMEventTargetHelper(aWindow), mUrls(std::move(aUrls)) {}
PresentationRequest::~PresentationRequest() = default;
bool PresentationRequest::Init() { return true; }
/* virtual */
JSObject* PresentationRequest::WrapObject(JSContext* aCx,
JS::Handle<JSObject*> aGivenProto) {
return PresentationRequest_Binding::Wrap(aCx, this, aGivenProto);
}
already_AddRefed<Promise> PresentationRequest::Start(ErrorResult& aRv) {
return StartWithDevice(VoidString(), aRv);
}
already_AddRefed<Promise> PresentationRequest::StartWithDevice(
const nsAString& aDeviceId, ErrorResult& aRv) {
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetOwner());
if (NS_WARN_IF(!global)) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
// Get the origin.
nsAutoString origin;
nsresult rv = nsContentUtils::GetUTFOrigin(global->PrincipalOrNull(), origin);
if (NS_WARN_IF(NS_FAILED(rv))) {
aRv.Throw(rv);
return nullptr;
}
nsCOMPtr<Document> doc = GetOwner()->GetExtantDoc();
if (NS_WARN_IF(!doc)) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
RefPtr<Promise> promise = Promise::Create(global, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
if (nsContentUtils::ShouldResistFingerprinting()) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
if (IsProhibitMixedSecurityContexts(doc) && !IsAllURLAuthenticated()) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
if (doc->GetSandboxFlags() & SANDBOXED_PRESENTATION) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
RefPtr<Navigator> navigator =
nsGlobalWindowInner::Cast(GetOwner())->Navigator();
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
RefPtr<Presentation> presentation = navigator->GetPresentation(aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
if (presentation->IsStartSessionUnsettled()) {
promise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
return promise.forget();
}
// Generate a session ID.
nsCOMPtr<nsIUUIDGenerator> uuidgen =
do_GetService("@mozilla.org/uuid-generator;1");
if (NS_WARN_IF(!uuidgen)) {
promise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
return promise.forget();
}
nsID uuid;
uuidgen->GenerateUUIDInPlace(&uuid);
char buffer[NSID_LENGTH];
uuid.ToProvidedString(buffer);
nsAutoString id;
CopyASCIItoUTF16(Span(buffer, NSID_LENGTH - 1), id);
nsCOMPtr<nsIPresentationService> service =
do_GetService(PRESENTATION_SERVICE_CONTRACTID);
if (NS_WARN_IF(!service)) {
promise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
return promise.forget();
}
presentation->SetStartSessionUnsettled(true);
// Get xul:browser element in parent process or nsWindowRoot object in child
// process. If it's in child process, the corresponding xul:browser element
// will be obtained at PresentationRequestParent::DoRequest in its parent
// process.
nsCOMPtr<EventTarget> handler = GetOwner()->GetChromeEventHandler();
nsCOMPtr<nsIPrincipal> principal = doc->NodePrincipal();
nsCOMPtr<nsIPresentationServiceCallback> callback =
new PresentationRequesterCallback(this, id, promise);
nsCOMPtr<nsIPresentationTransportBuilderConstructor> constructor =
PresentationTransportBuilderConstructor::Create();
rv = service->StartSession(mUrls, id, origin, aDeviceId,
GetOwner()->WindowID(), handler, principal,
callback, constructor);
if (NS_WARN_IF(NS_FAILED(rv))) {
promise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
NotifyPromiseSettled();
}
return promise.forget();
}
already_AddRefed<Promise> PresentationRequest::Reconnect(
const nsAString& aPresentationId, ErrorResult& aRv) {
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetOwner());
if (NS_WARN_IF(!global)) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsCOMPtr<Document> doc = GetOwner()->GetExtantDoc();
if (NS_WARN_IF(!doc)) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
RefPtr<Promise> promise = Promise::Create(global, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
if (nsContentUtils::ShouldResistFingerprinting()) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
if (IsProhibitMixedSecurityContexts(doc) && !IsAllURLAuthenticated()) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
if (doc->GetSandboxFlags() & SANDBOXED_PRESENTATION) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
nsString presentationId = nsString(aPresentationId);
nsCOMPtr<nsIRunnable> r = NewRunnableMethod<nsString, RefPtr<Promise>>(
"dom::PresentationRequest::FindOrCreatePresentationConnection", this,
&PresentationRequest::FindOrCreatePresentationConnection, presentationId,
promise);
if (NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(r)))) {
promise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
}
return promise.forget();
}
void PresentationRequest::FindOrCreatePresentationConnection(
const nsAString& aPresentationId, Promise* aPromise) {
MOZ_ASSERT(aPromise);
if (NS_WARN_IF(!GetOwner())) {
aPromise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
return;
}
RefPtr<PresentationConnection> connection =
ControllerConnectionCollection::GetSingleton()->FindConnection(
GetOwner()->WindowID(), aPresentationId,
nsIPresentationService::ROLE_CONTROLLER);
if (connection) {
nsAutoString url;
connection->GetUrl(url);
if (mUrls.Contains(url)) {
switch (connection->State()) {
case PresentationConnectionState::Closed:
// We found the matched connection.
break;
case PresentationConnectionState::Connecting:
case PresentationConnectionState::Connected:
aPromise->MaybeResolve(connection);
return;
case PresentationConnectionState::Terminated:
// A terminated connection cannot be reused.
connection = nullptr;
break;
default:
MOZ_CRASH("Unknown presentation session state.");
return;
}
} else {
connection = nullptr;
}
}
nsCOMPtr<nsIPresentationService> service =
do_GetService(PRESENTATION_SERVICE_CONTRACTID);
if (NS_WARN_IF(!service)) {
aPromise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
return;
}
nsCOMPtr<nsIPresentationServiceCallback> callback =
new PresentationReconnectCallback(this, aPresentationId, aPromise,
connection);
nsresult rv = service->ReconnectSession(
mUrls, aPresentationId, nsIPresentationService::ROLE_CONTROLLER,
callback);
if (NS_WARN_IF(NS_FAILED(rv))) {
aPromise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
}
}
already_AddRefed<Promise> PresentationRequest::GetAvailability(
ErrorResult& aRv) {
PRES_DEBUG("%s\n", __func__);
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetOwner());
if (NS_WARN_IF(!global)) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsCOMPtr<Document> doc = GetOwner()->GetExtantDoc();
if (NS_WARN_IF(!doc)) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
RefPtr<Promise> promise = Promise::Create(global, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
if (nsContentUtils::ShouldResistFingerprinting()) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
if (IsProhibitMixedSecurityContexts(doc) && !IsAllURLAuthenticated()) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
if (doc->GetSandboxFlags() & SANDBOXED_PRESENTATION) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
FindOrCreatePresentationAvailability(promise);
return promise.forget();
}
void PresentationRequest::FindOrCreatePresentationAvailability(
RefPtr<Promise>& aPromise) {
MOZ_ASSERT(aPromise);
if (NS_WARN_IF(!GetOwner())) {
aPromise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
return;
}
AvailabilityCollection* collection = AvailabilityCollection::GetSingleton();
if (NS_WARN_IF(!collection)) {
aPromise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
return;
}
RefPtr<PresentationAvailability> availability =
collection->Find(GetOwner()->WindowID(), mUrls);
if (!availability) {
availability =
PresentationAvailability::Create(GetOwner(), mUrls, aPromise);
} else {
PRES_DEBUG(">resolve with same object\n");
// Fetching cached available devices is asynchronous in our implementation,
// we need to ensure the promise is resolved in order.
if (availability->IsCachedValueReady()) {
aPromise->MaybeResolve(availability);
return;
}
availability->EnqueuePromise(aPromise);
}
if (!availability) {
aPromise->MaybeReject(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return;
}
}
nsresult PresentationRequest::DispatchConnectionAvailableEvent(
PresentationConnection* aConnection) {
if (nsContentUtils::ShouldResistFingerprinting()) {
return NS_OK;
}
PresentationConnectionAvailableEventInit init;
init.mConnection = aConnection;
RefPtr<PresentationConnectionAvailableEvent> event =
PresentationConnectionAvailableEvent::Constructor(
this, u"connectionavailable"_ns, init);
if (NS_WARN_IF(!event)) {
return NS_ERROR_FAILURE;
}
event->SetTrusted(true);
RefPtr<AsyncEventDispatcher> asyncDispatcher =
new AsyncEventDispatcher(this, event);
return asyncDispatcher->PostDOMEvent();
}
void PresentationRequest::NotifyPromiseSettled() {
PRES_DEBUG("%s\n", __func__);
if (!GetOwner()) {
return;
}
RefPtr<Navigator> navigator =
nsGlobalWindowInner::Cast(GetOwner())->Navigator();
if (!navigator) {
return;
}
ErrorResult rv;
RefPtr<Presentation> presentation = navigator->GetPresentation(rv);
if (presentation) {
presentation->SetStartSessionUnsettled(false);
}
}
bool PresentationRequest::IsProhibitMixedSecurityContexts(Document* aDocument) {
MOZ_ASSERT(aDocument);
if (nsContentUtils::IsChromeDoc(aDocument)) {
return true;
}
nsCOMPtr<Document> doc = aDocument;
while (doc && !nsContentUtils::IsChromeDoc(doc)) {
if (nsContentUtils::HttpsStateIsModern(doc)) {
return true;
}
doc = doc->GetInProcessParentDocument();
}
return false;
}
bool PresentationRequest::IsPrioriAuthenticatedURL(const nsAString& aUrl) {
nsCOMPtr<nsIURI> uri;
if (NS_FAILED(NS_NewURI(getter_AddRefs(uri), aUrl))) {
return false;
}
nsAutoCString scheme;
nsresult rv = uri->GetScheme(scheme);
if (NS_WARN_IF(NS_FAILED(rv))) {
return false;
}
if (scheme.EqualsLiteral("data")) {
return true;
}
nsAutoCString uriSpec;
rv = uri->GetSpec(uriSpec);
if (NS_WARN_IF(NS_FAILED(rv))) {
return false;
}
if (uriSpec.EqualsLiteral("about:blank") ||
uriSpec.EqualsLiteral("about:srcdoc")) {
return true;
}
OriginAttributes attrs;
nsCOMPtr<nsIPrincipal> principal =
BasePrincipal::CreateContentPrincipal(uri, attrs);
if (NS_WARN_IF(!principal)) {
return false;
}
return principal->GetIsOriginPotentiallyTrustworthy();
}
bool PresentationRequest::IsAllURLAuthenticated() {
for (const auto& url : mUrls) {
if (!IsPrioriAuthenticatedURL(url)) {
return false;
}
}
return true;
}
} // namespace dom
} // namespace mozilla
|