forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebRTCParent.sys.mjs
1484 lines (1368 loc) · 50.1 KB
/
WebRTCParent.sys.mjs
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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/. */
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
SitePermissions: "resource:///modules/SitePermissions.sys.mjs",
webrtcUI: "resource:///modules/webrtcUI.sys.mjs",
});
XPCOMUtils.defineLazyServiceGetter(
lazy,
"OSPermissions",
"@mozilla.org/ospermissionrequest;1",
"nsIOSPermissionRequest"
);
export class WebRTCParent extends JSWindowActorParent {
didDestroy() {
// Media stream tracks end on unload, so call stopRecording() on them early
// *before* we go away, to ensure we're working with the right principal.
this.stopRecording(this.manager.outerWindowId);
lazy.webrtcUI.forgetStreamsFromBrowserContext(this.browsingContext);
// Must clear activePerms here to prevent them from being read by laggard
// stopRecording() calls, which due to IPC, may come in *after* navigation.
// This is to prevent granting temporary grace periods to the wrong page.
lazy.webrtcUI.activePerms.delete(this.manager.outerWindowId);
}
getBrowser() {
return this.browsingContext.top.embedderElement;
}
receiveMessage(aMessage) {
switch (aMessage.name) {
case "rtcpeer:Request": {
let params = Object.freeze(
Object.assign(
{
origin: this.manager.documentPrincipal.origin,
},
aMessage.data
)
);
let blockers = Array.from(lazy.webrtcUI.peerConnectionBlockers);
(async function () {
for (let blocker of blockers) {
try {
let result = await blocker(params);
if (result == "deny") {
return false;
}
} catch (err) {
console.error(`error in PeerConnection blocker: ${err.message}`);
}
}
return true;
})().then(decision => {
let message;
if (decision) {
lazy.webrtcUI.emitter.emit("peer-request-allowed", params);
message = "rtcpeer:Allow";
} else {
lazy.webrtcUI.emitter.emit("peer-request-blocked", params);
message = "rtcpeer:Deny";
}
this.sendAsyncMessage(message, {
callID: params.callID,
windowID: params.windowID,
});
});
break;
}
case "rtcpeer:CancelRequest": {
let params = Object.freeze({
origin: this.manager.documentPrincipal.origin,
callID: aMessage.data,
});
lazy.webrtcUI.emitter.emit("peer-request-cancel", params);
break;
}
case "webrtc:Request": {
let data = aMessage.data;
// Record third party origins for telemetry.
let isThirdPartyOrigin =
this.manager.documentPrincipal.origin !=
this.manager.topWindowContext.documentPrincipal.origin;
data.isThirdPartyOrigin = isThirdPartyOrigin;
data.origin = this.manager.topWindowContext.documentPrincipal.origin;
let browser = this.getBrowser();
if (browser.fxrPermissionPrompt) {
// For Firefox Reality on Desktop, switch to a different mechanism to
// prompt the user since fewer permissions are available and since many
// UI dependencies are not available.
browser.fxrPermissionPrompt(data);
} else {
prompt(this, this.getBrowser(), data);
}
break;
}
case "webrtc:StopRecording":
this.stopRecording(
aMessage.data.windowID,
aMessage.data.mediaSource,
aMessage.data.rawID
);
break;
case "webrtc:CancelRequest": {
let browser = this.getBrowser();
// browser can be null when closing the window
if (browser) {
removePrompt(browser, aMessage.data);
}
break;
}
case "webrtc:UpdateIndicators": {
let { data } = aMessage;
data.documentURI = this.manager.documentURI?.spec;
if (data.windowId) {
if (!data.remove) {
data.principal = this.manager.topWindowContext.documentPrincipal;
}
lazy.webrtcUI.streamAddedOrRemoved(this.browsingContext, data);
}
this.updateIndicators(data);
break;
}
}
}
updateIndicators(aData) {
let browsingContext = this.browsingContext;
let state = lazy.webrtcUI.updateIndicators(browsingContext.top);
let browser = this.getBrowser();
if (!browser) {
return;
}
state.browsingContext = browsingContext;
state.windowId = aData.windowId;
let tabbrowser = browser.ownerGlobal.gBrowser;
if (tabbrowser) {
tabbrowser.updateBrowserSharing(browser, {
webRTC: state,
});
}
}
denyRequest(aRequest) {
this.sendAsyncMessage("webrtc:Deny", {
callID: aRequest.callID,
windowID: aRequest.windowID,
});
}
//
// Deny the request because the browser does not have access to the
// camera or microphone due to OS security restrictions. The user may
// have granted camera/microphone access to the site, but not have
// allowed the browser access in OS settings.
//
denyRequestNoPermission(aRequest) {
this.sendAsyncMessage("webrtc:Deny", {
callID: aRequest.callID,
windowID: aRequest.windowID,
noOSPermission: true,
});
}
//
// Check if we have permission to access the camera or screen-sharing and/or
// microphone at the OS level. Triggers a request to access the device if access
// is needed and the permission state has not yet been determined.
//
async checkOSPermission(camNeeded, micNeeded, scrNeeded) {
// Don't trigger OS permission requests for fake devices. Fake devices don't
// require OS permission and the dialogs are problematic in automated testing
// (where fake devices are used) because they require user interaction.
if (
!scrNeeded &&
Services.prefs.getBoolPref("media.navigator.streams.fake", false)
) {
return true;
}
let camStatus = {},
micStatus = {};
if (camNeeded || micNeeded) {
lazy.OSPermissions.getMediaCapturePermissionState(camStatus, micStatus);
}
if (camNeeded) {
let camPermission = camStatus.value;
let camAccessible = await this.checkAndGetOSPermission(
camPermission,
lazy.OSPermissions.requestVideoCapturePermission
);
if (!camAccessible) {
return false;
}
}
if (micNeeded) {
let micPermission = micStatus.value;
let micAccessible = await this.checkAndGetOSPermission(
micPermission,
lazy.OSPermissions.requestAudioCapturePermission
);
if (!micAccessible) {
return false;
}
}
let scrStatus = {};
if (scrNeeded) {
lazy.OSPermissions.getScreenCapturePermissionState(scrStatus);
if (scrStatus.value == lazy.OSPermissions.PERMISSION_STATE_DENIED) {
lazy.OSPermissions.maybeRequestScreenCapturePermission();
return false;
}
}
return true;
}
//
// Given a device's permission, return true if the device is accessible. If
// the device's permission is not yet determined, request access to the device.
// |requestPermissionFunc| must return a promise that resolves with true
// if the device is accessible and false otherwise.
//
async checkAndGetOSPermission(devicePermission, requestPermissionFunc) {
if (
devicePermission == lazy.OSPermissions.PERMISSION_STATE_DENIED ||
devicePermission == lazy.OSPermissions.PERMISSION_STATE_RESTRICTED
) {
return false;
}
if (devicePermission == lazy.OSPermissions.PERMISSION_STATE_NOTDETERMINED) {
let deviceAllowed = await requestPermissionFunc();
if (!deviceAllowed) {
return false;
}
}
return true;
}
stopRecording(aOuterWindowId, aMediaSource, aRawId) {
for (let { browsingContext, state } of lazy.webrtcUI._streams) {
if (browsingContext == this.browsingContext) {
let { principal } = state;
for (let { mediaSource, rawId } of state.devices) {
if (aRawId && (aRawId != rawId || aMediaSource != mediaSource)) {
continue;
}
// Deactivate this device (no aRawId means all devices).
this.deactivateDevicePerm(
aOuterWindowId,
mediaSource,
rawId,
principal
);
}
}
}
}
/**
* Add a device record to webrtcUI.activePerms, denoting a device as in use.
* Important to call for permission grace periods to work correctly.
*/
activateDevicePerm(aOuterWindowId, aMediaSource, aId) {
if (!lazy.webrtcUI.activePerms.has(this.manager.outerWindowId)) {
lazy.webrtcUI.activePerms.set(this.manager.outerWindowId, new Map());
}
lazy.webrtcUI.activePerms
.get(this.manager.outerWindowId)
.set(aOuterWindowId + aMediaSource + aId, aMediaSource);
}
/**
* Remove a device record from webrtcUI.activePerms, denoting a device as
* no longer in use by the site. Meaning: gUM requests for this device will
* no longer be implicitly granted through the webrtcUI.activePerms mechanism.
*
* However, if webrtcUI.deviceGracePeriodTimeoutMs is defined, the implicit
* grant is extended for an additional period of time through SitePermissions.
*/
deactivateDevicePerm(
aOuterWindowId,
aMediaSource,
aId,
aPermissionPrincipal
) {
// If we don't have active permissions for the given window anymore don't
// set a grace period. This happens if there has been a user revoke and
// webrtcUI clears the permissions.
if (!lazy.webrtcUI.activePerms.has(this.manager.outerWindowId)) {
return;
}
let map = lazy.webrtcUI.activePerms.get(this.manager.outerWindowId);
map.delete(aOuterWindowId + aMediaSource + aId);
// Add a permission grace period for camera and microphone only
if (
(aMediaSource != "camera" && aMediaSource != "microphone") ||
!this.browsingContext.top.embedderElement
) {
return;
}
let gracePeriodMs = lazy.webrtcUI.deviceGracePeriodTimeoutMs;
if (gracePeriodMs > 0) {
// A grace period is extended (even past navigation) to this outer window
// + origin + deviceId only. This avoids re-prompting without the user
// having to persist permission to the site, in a common case of a web
// conference asking them for the camera in a lobby page, before
// navigating to the actual meeting room page. Does not survive tab close.
//
// Caution: since navigation causes deactivation, we may be in the middle
// of one. We must pass in a principal & URI for SitePermissions to use
// instead of browser.currentURI, because the latter may point to a new
// page already, and we must not leak permission to unrelated pages.
//
let permissionName = [aMediaSource, aId].join("^");
lazy.SitePermissions.setForPrincipal(
aPermissionPrincipal,
permissionName,
lazy.SitePermissions.ALLOW,
lazy.SitePermissions.SCOPE_TEMPORARY,
this.browsingContext.top.embedderElement,
gracePeriodMs
);
}
}
/**
* Checks if the principal has sufficient permissions
* to fulfill the given request. If the request can be
* fulfilled, a message is sent to the child
* signaling that WebRTC permissions were given and
* this function will return true.
*/
checkRequestAllowed(aRequest, aPrincipal) {
if (!aRequest.secure) {
return false;
}
// Always prompt for screen sharing
if (aRequest.sharingScreen) {
return false;
}
let {
callID,
windowID,
audioInputDevices,
videoInputDevices,
audioOutputDevices,
hasInherentAudioConstraints,
hasInherentVideoConstraints,
audioOutputId,
} = aRequest;
if (audioOutputDevices?.length) {
// Prompt if a specific device is not requested, available and allowed.
let device = audioOutputDevices.find(({ id }) => id == audioOutputId);
if (
!device ||
!lazy.SitePermissions.getForPrincipal(
aPrincipal,
["speaker", device.id].join("^"),
this.getBrowser()
).state == lazy.SitePermissions.ALLOW
) {
return false;
}
this.sendAsyncMessage("webrtc:Allow", {
callID,
windowID,
devices: [device.deviceIndex],
});
return true;
}
let { perms } = Services;
if (
perms.testExactPermissionFromPrincipal(aPrincipal, "MediaManagerVideo")
) {
perms.removeFromPrincipal(aPrincipal, "MediaManagerVideo");
}
// Don't use persistent permissions from the top-level principal
// if we're handling a potentially insecure third party
// through a wildcard ("*") allow attribute.
let limited = aRequest.secondOrigin;
let map = lazy.webrtcUI.activePerms.get(this.manager.outerWindowId);
// We consider a camera or mic active if it is active or was active within a
// grace period of milliseconds ago.
const isAllowed = ({ mediaSource, rawId }, permissionID) =>
map?.get(windowID + mediaSource + rawId) ||
(!limited &&
(lazy.SitePermissions.getForPrincipal(aPrincipal, permissionID).state ==
lazy.SitePermissions.ALLOW ||
lazy.SitePermissions.getForPrincipal(
aPrincipal,
[mediaSource, rawId].join("^"),
this.getBrowser()
).state == lazy.SitePermissions.ALLOW));
let microphone;
if (audioInputDevices.length) {
for (let device of audioInputDevices) {
if (isAllowed(device, "microphone")) {
microphone = device;
break;
}
if (hasInherentAudioConstraints) {
// Inherent constraints suggest site is looking for a specific mic
break;
}
// Some sites don't look too hard at what they get, and spam gUM without
// adjusting what they ask for to match what they got last time. To keep
// users in charge and reduce prompts, ignore other constraints by
// returning the most-fit microphone a site already has access to.
}
if (!microphone) {
return false;
}
}
let camera;
if (videoInputDevices.length) {
for (let device of videoInputDevices) {
if (isAllowed(device, "camera")) {
camera = device;
break;
}
if (hasInherentVideoConstraints) {
// Inherent constraints suggest site is looking for a specific camera
break;
}
// Some sites don't look too hard at what they get, and spam gUM without
// adjusting what they ask for to match what they got last time. To keep
// users in charge and reduce prompts, ignore other constraints by
// returning the most-fit camera a site already has access to.
}
if (!camera) {
return false;
}
}
let devices = [];
if (camera) {
perms.addFromPrincipal(
aPrincipal,
"MediaManagerVideo",
perms.ALLOW_ACTION,
perms.EXPIRE_SESSION
);
devices.push(camera.deviceIndex);
this.activateDevicePerm(windowID, camera.mediaSource, camera.rawId);
}
if (microphone) {
devices.push(microphone.deviceIndex);
this.activateDevicePerm(
windowID,
microphone.mediaSource,
microphone.rawId
);
}
this.checkOSPermission(!!camera, !!microphone, false).then(
havePermission => {
if (havePermission) {
this.sendAsyncMessage("webrtc:Allow", { callID, windowID, devices });
} else {
this.denyRequestNoPermission(aRequest);
}
}
);
return true;
}
}
function prompt(aActor, aBrowser, aRequest) {
let {
audioInputDevices,
videoInputDevices,
audioOutputDevices,
sharingScreen,
sharingAudio,
requestTypes,
} = aRequest;
let principal =
Services.scriptSecurityManager.createContentPrincipalFromOrigin(
aRequest.origin
);
// For add-on principals, we immediately check for permission instead
// of waiting for the notification to focus. This allows for supporting
// cases such as browserAction popups where no prompt is shown.
if (principal.addonPolicy) {
let isPopup = false;
let isBackground = false;
for (let view of principal.addonPolicy.extension.views) {
if (view.viewType == "popup" && view.xulBrowser == aBrowser) {
isPopup = true;
}
if (view.viewType == "background" && view.xulBrowser == aBrowser) {
isBackground = true;
}
}
// Recording from background pages is considered too sensitive and will
// always be denied.
if (isBackground) {
aActor.denyRequest(aRequest);
return;
}
// If the request comes from a popup, we don't want to show the prompt,
// but we do want to allow the request if the user previously gave permission.
if (isPopup) {
if (!aActor.checkRequestAllowed(aRequest, principal, aBrowser)) {
aActor.denyRequest(aRequest);
}
return;
}
}
// If the user has already denied access once in this tab,
// deny again without even showing the notification icon.
for (const type of requestTypes) {
const permissionID =
type == "AudioCapture" ? "microphone" : type.toLowerCase();
if (
lazy.SitePermissions.getForPrincipal(principal, permissionID, aBrowser)
.state == lazy.SitePermissions.BLOCK
) {
aActor.denyRequest(aRequest);
return;
}
}
let chromeDoc = aBrowser.ownerDocument;
const localization = new Localization(
["browser/webrtcIndicator.ftl", "branding/brand.ftl"],
true
);
/** @type {"Screen" | "Camera" | null} */
let reqVideoInput = null;
if (videoInputDevices.length) {
reqVideoInput = sharingScreen ? "Screen" : "Camera";
}
/** @type {"AudioCapture" | "Microphone" | null} */
let reqAudioInput = null;
if (audioInputDevices.length) {
reqAudioInput = sharingAudio ? "AudioCapture" : "Microphone";
}
const reqAudioOutput = !!audioOutputDevices.length;
const stringId = getPromptMessageId(
reqVideoInput,
reqAudioInput,
reqAudioOutput,
!!aRequest.secondOrigin
);
let message;
let originToShow;
if (principal.schemeIs("file")) {
message = localization.formatValueSync(stringId + "-with-file");
originToShow = null;
} else {
message = localization.formatValueSync(stringId, {
origin: "<>",
thirdParty: "{}",
});
originToShow = lazy.webrtcUI.getHostOrExtensionName(principal.URI);
}
let notification; // Used by action callbacks.
const actionL10nIds = [{ id: "webrtc-action-allow" }];
let notificationSilencingEnabled = Services.prefs.getBoolPref(
"privacy.webrtc.allowSilencingNotifications"
);
const isNotNowLabelEnabled =
reqAudioOutput || allowedOrActiveCameraOrMicrophone(aBrowser);
let secondaryActions = [];
if (reqAudioOutput || (notificationSilencingEnabled && sharingScreen)) {
// We want to free up the checkbox at the bottom of the permission
// panel for the notification silencing option, so we use a
// different configuration for the permissions panel when
// notification silencing is enabled.
let permissionName = reqAudioOutput ? "speaker" : "screen";
// When selecting speakers, we always offer 'Not now' instead of 'Block'.
// When selecting screens, we offer 'Not now' if and only if we have a
// (temporary) allow permission for some mic/cam device.
const id = isNotNowLabelEnabled
? "webrtc-action-not-now"
: "webrtc-action-block";
actionL10nIds.push({ id }, { id: "webrtc-action-always-block" });
secondaryActions = [
{
callback() {
aActor.denyRequest(aRequest);
if (!isNotNowLabelEnabled) {
lazy.SitePermissions.setForPrincipal(
principal,
permissionName,
lazy.SitePermissions.BLOCK,
lazy.SitePermissions.SCOPE_TEMPORARY,
notification.browser
);
}
},
},
{
callback() {
aActor.denyRequest(aRequest);
lazy.SitePermissions.setForPrincipal(
principal,
permissionName,
lazy.SitePermissions.BLOCK,
lazy.SitePermissions.SCOPE_PERSISTENT,
notification.browser
);
},
},
];
} else {
// We have a (temporary) allow permission for some device
// hence we offer a 'Not now' label instead of 'Block'.
const id = isNotNowLabelEnabled
? "webrtc-action-not-now"
: "webrtc-action-block";
actionL10nIds.push({ id });
secondaryActions = [
{
callback(aState) {
aActor.denyRequest(aRequest);
const isPersistent = aState?.checkboxChecked;
// Choosing 'Not now' will not set a block permission
// we just deny the request. This enables certain use cases
// where sites want to switch devices, but users back out of the permission request
// (See Bug 1609578).
// Selecting 'Remember this decision' and clicking 'Not now' will set a persistent block
if (!isPersistent && isNotNowLabelEnabled) {
return;
}
// Denying a camera / microphone prompt means we set a temporary or
// persistent permission block. There may still be active grace period
// permissions at this point. We need to remove them.
clearTemporaryGrants(
notification.browser,
reqVideoInput === "Camera",
!!reqAudioInput
);
const scope = isPersistent
? lazy.SitePermissions.SCOPE_PERSISTENT
: lazy.SitePermissions.SCOPE_TEMPORARY;
if (reqAudioInput) {
lazy.SitePermissions.setForPrincipal(
principal,
"microphone",
lazy.SitePermissions.BLOCK,
scope,
notification.browser
);
}
if (reqVideoInput) {
lazy.SitePermissions.setForPrincipal(
principal,
sharingScreen ? "screen" : "camera",
lazy.SitePermissions.BLOCK,
scope,
notification.browser
);
}
},
},
];
}
// The formatMessagesSync method returns an array of results
// for each message that was requested, and for the ones with
// attributes, returns an attributes array with objects like:
// { name: "label", value: "somevalue" }
const [mainMessage, ...secondaryMessages] = localization
.formatMessagesSync(actionL10nIds)
.map(msg =>
msg.attributes.reduce(
(acc, { name, value }) => ({ ...acc, [name]: value }),
{}
)
);
const mainAction = {
label: mainMessage.label,
accessKey: mainMessage.accesskey,
// The real callback will be set during the "showing" event. The
// empty function here is so that PopupNotifications.show doesn't
// reject the action.
callback() {},
};
for (let i = 0; i < secondaryActions.length; ++i) {
secondaryActions[i].label = secondaryMessages[i].label;
secondaryActions[i].accessKey = secondaryMessages[i].accesskey;
}
let options = {
name: originToShow,
persistent: true,
hideClose: true,
eventCallback(aTopic, aNewBrowser, isCancel) {
if (aTopic == "swapping") {
return true;
}
let doc = this.browser.ownerDocument;
// Clean-up video streams of screensharing previews.
if (
reqVideoInput !== "Screen" ||
aTopic == "dismissed" ||
aTopic == "removed"
) {
let video = doc.getElementById("webRTC-previewVideo");
video.deviceId = null; // Abort previews still being started.
if (video.stream) {
video.stream.getTracks().forEach(t => t.stop());
video.stream = null;
video.src = null;
doc.getElementById("webRTC-preview").hidden = true;
}
let menupopup = doc.getElementById("webRTC-selectWindow-menupopup");
if (menupopup._commandEventListener) {
menupopup.removeEventListener(
"command",
menupopup._commandEventListener
);
menupopup._commandEventListener = null;
}
}
if (aTopic == "removed" && notification && isCancel) {
// The notification has been cancelled (e.g. due to entering
// full-screen). Also cancel the webRTC request.
aActor.denyRequest(aRequest);
} else if (
aTopic == "shown" &&
audioOutputDevices.length > 1 &&
!notification.wasDismissed
) {
// Focus the list on first show so that arrow keys select the speaker.
doc.getElementById("webRTC-selectSpeaker-richlistbox").focus();
}
if (aTopic != "showing") {
return false;
}
// If BLOCK has been set persistently in the permission manager or has
// been set on the tab, then it is handled synchronously before we add
// the notification.
// Handling of ALLOW is delayed until the popupshowing event,
// to avoid granting permissions automatically to background tabs.
if (aActor.checkRequestAllowed(aRequest, principal, aBrowser)) {
this.remove();
return true;
}
/**
* Prepare the device selector for one kind of device.
* @param {Object[]} devices - available devices of this kind.
* @param {string} IDPrefix - indicating kind of device and so
* associated UI elements.
* @param {string[]} describedByIDs - an array to which might be
* appended ids of elements that describe the panel, for the caller to
* use in the aria-describedby attribute.
*/
function listDevices(devices, IDPrefix, describedByIDs) {
let labelID = `${IDPrefix}-single-device-label`;
let list;
let itemParent;
if (IDPrefix == "webRTC-selectSpeaker") {
list = doc.getElementById(`${IDPrefix}-richlistbox`);
itemParent = list;
} else {
itemParent = doc.getElementById(`${IDPrefix}-menupopup`);
list = itemParent.parentNode; // menulist
}
while (itemParent.lastChild) {
itemParent.removeChild(itemParent.lastChild);
}
// Removing the child nodes of a menupopup doesn't clear the value
// attribute of its menulist. Similary for richlistbox state. This can
// have unfortunate side effects when the list is rebuilt with a
// different content, so we set the selectedIndex explicitly to reset
// state.
let defaultIndex = 0;
for (let device of devices) {
let item = addDeviceToList(list, device.name, device.deviceIndex);
if (IDPrefix == "webRTC-selectSpeaker") {
item.addEventListener("dblclick", event => {
// Allow the chosen speakers via
// .popup-notification-primary-button so that
// "security.notification_enable_delay" is checked.
event.target.closest("popupnotification").button.doCommand();
});
if (device.id == aRequest.audioOutputId) {
defaultIndex = device.deviceIndex;
}
}
}
list.selectedIndex = defaultIndex;
let label = doc.getElementById(labelID);
if (devices.length == 1) {
describedByIDs.push(`${IDPrefix}-icon`, labelID);
label.value = devices[0].name;
label.hidden = false;
list.hidden = true;
} else {
label.hidden = true;
list.hidden = false;
}
}
let notificationElement = doc.getElementById(
"webRTC-shareDevices-notification"
);
function checkDisabledWindowMenuItem() {
let list = doc.getElementById("webRTC-selectWindow-menulist");
let item = list.selectedItem;
if (!item || item.hasAttribute("disabled")) {
notificationElement.setAttribute("invalidselection", "true");
} else {
notificationElement.removeAttribute("invalidselection");
}
}
function listScreenShareDevices(menupopup, devices) {
while (menupopup.lastChild) {
menupopup.removeChild(menupopup.lastChild);
}
// Removing the child nodes of the menupopup doesn't clear the value
// attribute of the menulist. This can have unfortunate side effects
// when the list is rebuilt with a different content, so we remove
// the value attribute and unset the selectedItem explicitly.
menupopup.parentNode.removeAttribute("value");
menupopup.parentNode.selectedItem = null;
// "Select a Window or Screen" is the default because we can't and don't
// want to pick a 'default' window to share (Full screen is "scary").
addDeviceToList(
menupopup.parentNode,
localization.formatValueSync("webrtc-pick-window-or-screen"),
"-1"
);
menupopup.appendChild(doc.createXULElement("menuseparator"));
let isPipeWireDetected = false;
// Build the list of 'devices'.
let monitorIndex = 1;
for (let i = 0; i < devices.length; ++i) {
let device = devices[i];
let type = device.mediaSource;
let name;
if (device.canRequestOsLevelPrompt) {
// When we share content by PipeWire add only one item to the device
// list. When it's selected PipeWire portal dialog is opened and
// user confirms actual window/screen sharing there.
// Don't mark it as scary as there's an extra confirmation step by
// PipeWire portal dialog.
isPipeWireDetected = true;
let item = addDeviceToList(
menupopup.parentNode,
localization.formatValueSync("webrtc-share-pipe-wire-portal"),
i,
type
);
item.deviceId = device.rawId;
item.mediaSource = type;
// In this case the OS sharing dialog will be the only option and
// can be safely pre-selected.
menupopup.parentNode.selectedItem = item;
continue;
} else if (type == "screen") {
// Building screen list from available screens.
if (device.name == "Primary Monitor") {
name = localization.formatValueSync("webrtc-share-entire-screen");
} else {
name = localization.formatValueSync("webrtc-share-monitor", {
monitorIndex,
});
++monitorIndex;
}
} else {
name = device.name;
if (type == "application") {
// The application names returned by the platform are of the form:
// <window count>\x1e<application name>
const [count, appName] = name.split("\x1e");
name = localization.formatValueSync("webrtc-share-application", {
appName,
windowCount: parseInt(count),
});
}
}
let item = addDeviceToList(menupopup.parentNode, name, i, type);
item.deviceId = device.rawId;
item.mediaSource = type;
if (device.scary) {
item.scary = true;
}
}
// Always re-select the "No <type>" item.
doc
.getElementById("webRTC-selectWindow-menulist")
.removeAttribute("value");
doc.getElementById("webRTC-all-windows-shared").hidden = true;
menupopup._commandEventListener = event => {
checkDisabledWindowMenuItem();
let video = doc.getElementById("webRTC-previewVideo");
if (video.stream) {
video.stream.getTracks().forEach(t => t.stop());
video.stream = null;
}
const { deviceId, mediaSource, scary } = event.target;
if (deviceId == undefined) {
doc.getElementById("webRTC-preview").hidden = true;
video.src = null;
return;
}
let warning = doc.getElementById("webRTC-previewWarning");
let warningBox = doc.getElementById("webRTC-previewWarningBox");
warningBox.hidden = !scary;
let chromeWin = doc.defaultView;
if (scary) {
const warnId =
mediaSource == "screen"
? "webrtc-share-screen-warning"
: "webrtc-share-browser-warning";
doc.l10n.setAttributes(warning, warnId);
const learnMore = doc.getElementById(
"webRTC-previewWarning-learnMore"
);
const baseURL = Services.urlFormatter.formatURLPref(
"app.support.baseURL"
);
learnMore.setAttribute("href", baseURL + "screenshare-safety");
doc.l10n.setAttributes(learnMore, "webrtc-share-screen-learn-more");
// On Catalina, we don't want to blow our chance to show the
// OS-level helper prompt to enable screen recording if the user
// intends to reject anyway. OTOH showing it when they click Allow
// is too late. A happy middle is to show it when the user makes a
// choice in the picker. This already happens implicitly if the
// user chooses "Entire desktop", as a side-effect of our preview,
// we just need to also do it if they choose "Firefox". These are
// the lone two options when permission is absent on Catalina.
// Ironically, these are the two sources marked "scary" from a
// web-sharing perspective, which is why this code resides here.
// A restart doesn't appear to be necessary in spite of OS wording.
let scrStatus = {};
lazy.OSPermissions.getScreenCapturePermissionState(scrStatus);
if (scrStatus.value == lazy.OSPermissions.PERMISSION_STATE_DENIED) {
lazy.OSPermissions.maybeRequestScreenCapturePermission();
}
}
let perms = Services.perms;
let chromePrincipal =
Services.scriptSecurityManager.getSystemPrincipal();