-
Notifications
You must be signed in to change notification settings - Fork 13
/
native-messaging-portal.patch
1783 lines (1748 loc) · 63.3 KB
/
native-messaging-portal.patch
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
From 1bbaeb5baa715290a3bb981169e6d56bc02afb1e Mon Sep 17 00:00:00 2001
From: Amin Bandali <bandali@canonical.com>
Date: Mon, 12 Feb 2024 21:53:54 -0500
Subject: [PATCH] NativeMessaging patch from Snap nightly
---
modules/libpref/init/StaticPrefList.yaml | 10 +
python/mozbuild/mozbuild/mozinfo.py | 3 +
.../configs/unittests/linux_unittest.py | 7 +-
.../extensions/NativeMessaging.sys.mjs | 72 ++
.../extensions/NativeMessagingPortal.cpp | 619 ++++++++++++++++++
.../extensions/NativeMessagingPortal.h | 74 +++
toolkit/components/extensions/components.conf | 12 +
toolkit/components/extensions/moz.build | 8 +
.../extensions/nsINativeMessagingPortal.idl | 71 ++
.../test/xpcshell/native_messaging.toml | 4 +
.../test_ext_native_messaging_portal.js | 378 +++++++++++
toolkit/modules/subprocess/Subprocess.sys.mjs | 13 +
.../subprocess/subprocess_common.sys.mjs | 32 +-
.../subprocess/subprocess_unix.sys.mjs | 4 +
.../subprocess/subprocess_unix.worker.js | 24 +-
.../modules/subprocess/subprocess_win.sys.mjs | 6 +
.../subprocess/subprocess_win.worker.js | 6 +
.../subprocess/subprocess_worker_common.js | 31 +-
.../test/xpcshell/test_subprocess.js | 77 +++
widget/gtk/WidgetUtilsGtk.cpp | 2 +
widget/gtk/WidgetUtilsGtk.h | 1 +
21 files changed, 1446 insertions(+), 8 deletions(-)
create mode 100644 toolkit/components/extensions/NativeMessagingPortal.cpp
create mode 100644 toolkit/components/extensions/NativeMessagingPortal.h
create mode 100644 toolkit/components/extensions/nsINativeMessagingPortal.idl
create mode 100644 toolkit/components/extensions/test/xpcshell/test_ext_native_messaging_portal.js
diff --git a/modules/libpref/init/StaticPrefList.yaml b/modules/libpref/init/StaticPrefList.yaml
index 8ba1d8b35b6d1..7eb6701c58040 100644
--- a/modules/libpref/init/StaticPrefList.yaml
+++ b/modules/libpref/init/StaticPrefList.yaml
@@ -15666,6 +15666,16 @@
value: 2
mirror: always
+# Whether to use XDG portal for native messaging.
+# https://github.com/flatpak/xdg-desktop-portal/issues/655
+# - 0: never
+# - 1: always
+# - 2: auto (true for snap and flatpak or GTK_USE_PORTAL=1, false otherwise)
+- name: widget.use-xdg-desktop-portal.native-messaging
+ type: int32_t
+ value: 2
+ mirror: always
+
# Whether to try to use XDG portal for settings / look-and-feel information.
# https://flatpak.github.io/xdg-desktop-portal/#gdbus-org.freedesktop.portal.Settings
# - 0: never
diff --git a/python/mozbuild/mozbuild/mozinfo.py b/python/mozbuild/mozbuild/mozinfo.py
index b640c5f1d0f31..4d98af5f32051 100644
--- a/python/mozbuild/mozbuild/mozinfo.py
+++ b/python/mozbuild/mozbuild/mozinfo.py
@@ -151,6 +151,9 @@ def build_dict(config, env=os.environ):
):
d["android_min_sdk"] = substs["MOZ_ANDROID_MIN_SDK_VERSION"]
+ if "MOZ_ENABLE_DBUS" in substs:
+ d["dbus_enabled"] = bool(substs.get("MOZ_ENABLE_DBUS"))
+
return d
diff --git a/testing/mozharness/configs/unittests/linux_unittest.py b/testing/mozharness/configs/unittests/linux_unittest.py
index 801f57eb14f9e..977cfbe4068c4 100644
--- a/testing/mozharness/configs/unittests/linux_unittest.py
+++ b/testing/mozharness/configs/unittests/linux_unittest.py
@@ -34,7 +34,12 @@ else:
#####
config = {
###
- "virtualenv_modules": ["six==1.13.0", "vcversioner==2.16.0.0"],
+ "virtualenv_modules": [
+ "six==1.13.0",
+ "vcversioner==2.16.0.0",
+ "dbus-python==1.2.18",
+ "python-dbusmock==0.28.4",
+ ],
"installer_path": INSTALLER_PATH,
"binary_path": BINARY_PATH,
"xpcshell_name": XPCSHELL_NAME,
diff --git a/toolkit/components/extensions/NativeMessaging.sys.mjs b/toolkit/components/extensions/NativeMessaging.sys.mjs
index dcd8fe7807892..23398fc4c7fb0 100644
--- a/toolkit/components/extensions/NativeMessaging.sys.mjs
+++ b/toolkit/components/extensions/NativeMessaging.sys.mjs
@@ -19,6 +19,13 @@ ChromeUtils.defineESModuleGetters(lazy, {
const { ExtensionError, promiseTimeout } = ExtensionUtils;
+XPCOMUtils.defineLazyServiceGetter(
+ lazy,
+ "portal",
+ "@mozilla.org/extensions/native-messaging-portal;1",
+ "nsINativeMessagingPortal"
+);
+
// For a graceful shutdown (i.e., when the extension is unloaded or when it
// explicitly calls disconnect() on a native port), how long we give the native
// application to exit before we start trying to kill it. (in milliseconds)
@@ -67,6 +74,14 @@ export class NativeApp extends EventEmitter {
this.sendQueue = [];
this.writePromise = null;
this.cleanupStarted = false;
+ this.portalSessionHandle = null;
+
+ if ("@mozilla.org/extensions/native-messaging-portal;1" in Cc) {
+ if (lazy.portal.shouldUse()) {
+ this._initPortal();
+ return;
+ }
+ }
this.startupPromise = lazy.NativeManifests.lookupManifest(
"stdio",
@@ -125,6 +140,54 @@ export class NativeApp extends EventEmitter {
});
}
+ _initPortal() {
+ this.startupPromise = this._doInitPortal();
+ }
+
+ async _doInitPortal() {
+ let available = await lazy.portal.available;
+
+ if (!available) {
+ this.startupPromise = null;
+ let err = new ExtensionError("Native messaging portal is not available");
+ Cu.reportError(err);
+ this._cleanup(err);
+ return;
+ }
+
+ try {
+ let handle = await lazy.portal.createSession(this.name);
+ this.portalSessionHandle = handle;
+ let pipes;
+ try {
+ pipes = await lazy.portal.start(
+ handle,
+ this.name,
+ this.context.extension.id
+ );
+ } catch (err) {
+ if (err.name == "NotFoundError") {
+ throw new ExtensionError(`No such native application ${this.name}`);
+ } else {
+ throw err;
+ }
+ }
+ this.proc = await lazy.Subprocess.connectRunning([
+ pipes.stdin,
+ pipes.stdout,
+ pipes.stderr,
+ ]);
+ this.startupPromise = null;
+ this._startRead();
+ this._startWrite();
+ this._startStderrRead();
+ } catch (err) {
+ this.startupPromise = null;
+ Cu.reportError(err instanceof Error ? err : err.message);
+ this._cleanup(err);
+ }
+ }
+
/**
* Open a connection to a native messaging host.
*
@@ -301,6 +364,15 @@ export class NativeApp extends EventEmitter {
await this.startupPromise;
+ if (this.portalSessionHandle) {
+ await this.writePromise;
+ await lazy.portal.closeSession(this.portalSessionHandle).then(_ => {
+ this.portalSessionHandle = null;
+ this.proc = null;
+ });
+ return;
+ }
+
if (!this.proc) {
// Failed to initialize proc in the constructor.
return;
diff --git a/toolkit/components/extensions/NativeMessagingPortal.cpp b/toolkit/components/extensions/NativeMessagingPortal.cpp
new file mode 100644
index 0000000000000..5e6c6423dba14
--- /dev/null
+++ b/toolkit/components/extensions/NativeMessagingPortal.cpp
@@ -0,0 +1,619 @@
+/* -*- 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 "NativeMessagingPortal.h"
+
+#include <gio/gunixfdlist.h>
+#include <glib.h>
+
+#include "mozilla/ClearOnShutdown.h"
+#include "mozilla/GUniquePtr.h"
+#include "mozilla/Logging.h"
+#include "mozilla/UniquePtrExtensions.h"
+#include "mozilla/WidgetUtilsGtk.h"
+#include "mozilla/dom/Promise.h"
+
+#include <string.h>
+
+static mozilla::LazyLogModule gNativeMessagingPortalLog(
+ "NativeMessagingPortal");
+
+#ifdef MOZ_LOGGING
+# define LOG_NMP(...) \
+ MOZ_LOG(gNativeMessagingPortalLog, mozilla::LogLevel::Debug, (__VA_ARGS__))
+#else
+# define LOG_NMP(args)
+#endif
+
+namespace mozilla::extensions {
+
+NS_IMPL_ISUPPORTS(NativeMessagingPortal, nsINativeMessagingPortal)
+
+/* static */
+already_AddRefed<NativeMessagingPortal> NativeMessagingPortal::GetSingleton() {
+ static StaticRefPtr<NativeMessagingPortal> sInstance;
+
+ if (MOZ_UNLIKELY(!sInstance)) {
+ sInstance = new NativeMessagingPortal();
+ ClearOnShutdown(&sInstance);
+ }
+
+ return do_AddRef(sInstance);
+}
+
+static void LogError(const char* aMethod, const GError& aError) {
+ g_warning("%s error: %s", aMethod, aError.message);
+}
+
+static void RejectPromiseWithErrorMessage(dom::Promise& aPromise,
+ const GError& aError) {
+ aPromise.MaybeRejectWithOperationError(nsDependentCString(aError.message));
+}
+
+static nsresult GetPromise(JSContext* aCx, RefPtr<dom::Promise>& aPromise) {
+ nsIGlobalObject* globalObject = xpc::CurrentNativeGlobal(aCx);
+ if (NS_WARN_IF(!globalObject)) {
+ return NS_ERROR_UNEXPECTED;
+ }
+ ErrorResult result;
+ aPromise = dom::Promise::Create(globalObject, result);
+ if (NS_WARN_IF(result.Failed())) {
+ return result.StealNSResult();
+ }
+ return NS_OK;
+}
+
+struct CallbackData {
+ explicit CallbackData(dom::Promise& aPromise,
+ const gchar* aSessionHandle = nullptr)
+ : promise(&aPromise), sessionHandle(g_strdup(aSessionHandle)) {}
+ RefPtr<dom::Promise> promise;
+ GUniquePtr<gchar> sessionHandle;
+ guint subscription_id = 0;
+};
+
+NativeMessagingPortal::NativeMessagingPortal() {
+ LOG_NMP("NativeMessagingPortal::NativeMessagingPortal()");
+ mCancellable = dont_AddRef(g_cancellable_new());
+ g_dbus_proxy_new_for_bus(G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, nullptr,
+ "org.freedesktop.portal.Desktop",
+ "/org/freedesktop/portal/desktop",
+ "org.freedesktop.portal.WebExtensions", mCancellable,
+ &NativeMessagingPortal::OnProxyReady, this);
+}
+
+NativeMessagingPortal::~NativeMessagingPortal() {
+ LOG_NMP("NativeMessagingPortal::~NativeMessagingPortal()");
+
+ g_cancellable_cancel(mCancellable);
+
+ // Close all active sessions
+ for (const auto& it : mSessions) {
+ if (it.second != SessionState::Active) {
+ continue;
+ }
+ GUniquePtr<GError> error;
+ RefPtr<GDBusProxy> proxy = dont_AddRef(g_dbus_proxy_new_for_bus_sync(
+ G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, nullptr,
+ "org.freedesktop.portal.Desktop", it.first.c_str(),
+ "org.freedesktop.portal.Session", nullptr, getter_Transfers(error)));
+ if (!proxy) {
+ LOG_NMP("failed to get a D-Bus proxy: %s", error->message);
+ LogError(__func__, *error);
+ continue;
+ }
+ RefPtr<GVariant> res = dont_AddRef(
+ g_dbus_proxy_call_sync(proxy, "Close", nullptr, G_DBUS_CALL_FLAGS_NONE,
+ -1, nullptr, getter_Transfers(error)));
+ if (!res) {
+ LOG_NMP("failed to close session: %s", error->message);
+ LogError(__func__, *error);
+ }
+ }
+}
+
+NS_IMETHODIMP
+NativeMessagingPortal::ShouldUse(bool* aResult) {
+ *aResult = widget::ShouldUsePortal(widget::PortalKind::NativeMessaging);
+ LOG_NMP("will %sbe used", *aResult ? "" : "not ");
+ return NS_OK;
+}
+
+struct NativeMessagingPortal::DelayedCall {
+ using DelayedMethodCall = void (NativeMessagingPortal::*)(dom::Promise&,
+ GVariant*);
+
+ DelayedCall(DelayedMethodCall aCallback, dom::Promise& aPromise,
+ GVariant* aArgs = nullptr)
+ : callback(aCallback), promise(&aPromise), args(aArgs) {
+ LOG_NMP("NativeMessagingPortal::DelayedCall::DelayedCall()");
+ }
+ ~DelayedCall() {
+ LOG_NMP("NativeMessagingPortal::DelayedCall::~DelayedCall()");
+ }
+
+ DelayedMethodCall callback;
+ RefPtr<dom::Promise> promise;
+ RefPtr<GVariant> args;
+};
+
+/* static */
+void NativeMessagingPortal::OnProxyReady(GObject* source, GAsyncResult* result,
+ gpointer user_data) {
+ NativeMessagingPortal* self = static_cast<NativeMessagingPortal*>(user_data);
+ GUniquePtr<GError> error;
+ self->mProxy = dont_AddRef(
+ g_dbus_proxy_new_for_bus_finish(result, getter_Transfers(error)));
+ if (self->mProxy) {
+ LOG_NMP("D-Bus proxy ready for name %s, path %s, interface %s",
+ g_dbus_proxy_get_name(self->mProxy),
+ g_dbus_proxy_get_object_path(self->mProxy),
+ g_dbus_proxy_get_interface_name(self->mProxy));
+ } else {
+ LOG_NMP("failed to get a D-Bus proxy: %s", error->message);
+ LogError(__func__, *error);
+ }
+ self->mInitialized = true;
+ while (!self->mPending.empty()) {
+ auto pending = std::move(self->mPending.front());
+ self->mPending.pop_front();
+ (self->*pending->callback)(*pending->promise, pending->args.get());
+ }
+}
+
+NS_IMETHODIMP
+NativeMessagingPortal::GetAvailable(JSContext* aCx, dom::Promise** aPromise) {
+ RefPtr<dom::Promise> promise;
+ MOZ_TRY(GetPromise(aCx, promise));
+
+ if (mInitialized) {
+ MaybeDelayedIsAvailable(*promise, nullptr);
+ } else {
+ auto delayed = MakeUnique<DelayedCall>(
+ &NativeMessagingPortal::MaybeDelayedIsAvailable, *promise);
+ mPending.push_back(std::move(delayed));
+ }
+
+ promise.forget(aPromise);
+ return NS_OK;
+}
+
+void NativeMessagingPortal::MaybeDelayedIsAvailable(dom::Promise& aPromise,
+ GVariant* aArgs) {
+ MOZ_ASSERT(!aArgs);
+
+ bool available = false;
+ if (mProxy) {
+ RefPtr<GVariant> version =
+ dont_AddRef(g_dbus_proxy_get_cached_property(mProxy, "version"));
+ if (version) {
+ if (g_variant_get_uint32(version) >= 1) {
+ available = true;
+ }
+ }
+ }
+
+ LOG_NMP("is %savailable", available ? "" : "not ");
+ aPromise.MaybeResolve(available);
+}
+
+NS_IMETHODIMP
+NativeMessagingPortal::CreateSession(const nsACString& aApplication,
+ JSContext* aCx, dom::Promise** aPromise) {
+ RefPtr<dom::Promise> promise;
+ MOZ_TRY(GetPromise(aCx, promise));
+
+ // Creating a session requires passing a unique token that will be used as the
+ // suffix for the session handle, and it should be a valid D-Bus object path
+ // component (i.e. it contains only the characters "[A-Z][a-z][0-9]_", see
+ // https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling-object-path
+ // and
+ // https://flatpak.github.io/xdg-desktop-portal/#gdbus-org.freedesktop.portal.Session).
+ // The token should be unique and not guessable. To avoid clashes with calls
+ // made from unrelated libraries, it is a good idea to use a per-library
+ // prefix combined with a random number.
+ // Here, we build the token by concatenating MOZ_APP_NAME (e.g. "firefox"),
+ // with the name of the native application (sanitized to remove invalid
+ // characters, see
+ // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_manifests#native_messaging_manifests),
+ // and a random number.
+ const nsCString& application = PromiseFlatCString(aApplication);
+ GUniquePtr<gchar> sanitizedApplicationName(g_strdup(application.get()));
+ g_strdelimit(sanitizedApplicationName.get(), ".", '_');
+ GUniquePtr<gchar> token(g_strdup_printf("%s_%s_%u", MOZ_APP_NAME,
+ sanitizedApplicationName.get(),
+ g_random_int()));
+ RefPtr<GVariant> args = dont_AddRef(g_variant_new_string(token.get()));
+
+ if (mInitialized) {
+ MaybeDelayedCreateSession(*promise, args);
+ } else {
+ auto delayed = MakeUnique<DelayedCall>(
+ &NativeMessagingPortal::MaybeDelayedCreateSession, *promise, args);
+ mPending.push_back(std::move(delayed));
+ }
+
+ promise.forget(aPromise);
+ return NS_OK;
+}
+
+void NativeMessagingPortal::MaybeDelayedCreateSession(dom::Promise& aPromise,
+ GVariant* aArgs) {
+ MOZ_ASSERT(g_variant_is_of_type(aArgs, G_VARIANT_TYPE_STRING));
+
+ if (!mProxy) {
+ return aPromise.MaybeRejectWithOperationError(
+ "No D-Bus proxy for the native messaging portal");
+ }
+
+ LOG_NMP("creating session with handle suffix %s",
+ g_variant_get_string(aArgs, nullptr));
+
+ GVariantBuilder options;
+ g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT);
+ g_variant_builder_add(&options, "{sv}", "session_handle_token",
+ g_variant_ref_sink(aArgs));
+ auto callbackData = MakeUnique<CallbackData>(aPromise);
+ g_dbus_proxy_call(mProxy, "CreateSession", g_variant_new("(a{sv})", &options),
+ G_DBUS_CALL_FLAGS_NONE, -1, nullptr,
+ &NativeMessagingPortal::OnCreateSessionDone,
+ callbackData.release());
+}
+
+/* static */
+void NativeMessagingPortal::OnCreateSessionDone(GObject* source,
+ GAsyncResult* result,
+ gpointer user_data) {
+ GDBusProxy* proxy = G_DBUS_PROXY(source);
+ UniquePtr<CallbackData> callbackData(static_cast<CallbackData*>(user_data));
+
+ GUniquePtr<GError> error;
+ RefPtr<GVariant> res = dont_AddRef(
+ g_dbus_proxy_call_finish(proxy, result, getter_Transfers(error)));
+ if (res) {
+ RefPtr<GVariant> sessionHandle =
+ dont_AddRef(g_variant_get_child_value(res, 0));
+ gsize length;
+ const char* value = g_variant_get_string(sessionHandle, &length);
+ LOG_NMP("session created with handle %s", value);
+ RefPtr<NativeMessagingPortal> portal = GetSingleton();
+ portal->mSessions[value] = SessionState::Active;
+
+ GDBusConnection* connection = g_dbus_proxy_get_connection(proxy);
+ // The "Closed" signal is emitted e.g. when the user denies access to the
+ // native application when the shell prompts them.
+ auto subscription_id_ptr = MakeUnique<guint>(0);
+ *subscription_id_ptr = g_dbus_connection_signal_subscribe(
+ connection, "org.freedesktop.portal.Desktop",
+ "org.freedesktop.portal.Session", "Closed", value, nullptr,
+ G_DBUS_SIGNAL_FLAGS_NONE, &NativeMessagingPortal::OnSessionClosedSignal,
+ subscription_id_ptr.get(), [](gpointer aUserData) {
+ UniquePtr<guint> release(reinterpret_cast<guint*>(aUserData));
+ });
+ Unused << subscription_id_ptr.release(); // Ownership transferred above.
+
+ callbackData->promise->MaybeResolve(nsDependentCString(value, length));
+ } else {
+ LOG_NMP("failed to create session: %s", error->message);
+ LogError(__func__, *error);
+ RejectPromiseWithErrorMessage(*callbackData->promise, *error);
+ }
+}
+
+NS_IMETHODIMP
+NativeMessagingPortal::CloseSession(const nsACString& aHandle, JSContext* aCx,
+ dom::Promise** aPromise) {
+ const nsCString& sessionHandle = PromiseFlatCString(aHandle);
+
+ if (!g_variant_is_object_path(sessionHandle.get())) {
+ LOG_NMP("cannot close session %s, invalid handle", sessionHandle.get());
+ return NS_ERROR_INVALID_ARG;
+ }
+
+ auto sessionIterator = mSessions.find(sessionHandle.get());
+ if (sessionIterator == mSessions.end()) {
+ LOG_NMP("cannot close session %s, unknown handle", sessionHandle.get());
+ return NS_ERROR_INVALID_ARG;
+ }
+
+ if (sessionIterator->second != SessionState::Active) {
+ LOG_NMP("cannot close session %s, not active", sessionHandle.get());
+ return NS_ERROR_FAILURE;
+ }
+
+ RefPtr<dom::Promise> promise;
+ MOZ_TRY(GetPromise(aCx, promise));
+
+ sessionIterator->second = SessionState::Closing;
+ LOG_NMP("closing session %s", sessionHandle.get());
+ auto callbackData = MakeUnique<CallbackData>(*promise, sessionHandle.get());
+ g_dbus_proxy_new_for_bus(
+ G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, nullptr,
+ "org.freedesktop.portal.Desktop", sessionHandle.get(),
+ "org.freedesktop.portal.Session", nullptr,
+ &NativeMessagingPortal::OnCloseSessionProxyReady, callbackData.release());
+
+ promise.forget(aPromise);
+ return NS_OK;
+}
+
+/* static */
+void NativeMessagingPortal::OnCloseSessionProxyReady(GObject* source,
+ GAsyncResult* result,
+ gpointer user_data) {
+ UniquePtr<CallbackData> callbackData(static_cast<CallbackData*>(user_data));
+
+ GUniquePtr<GError> error;
+ RefPtr<GDBusProxy> proxy = dont_AddRef(
+ g_dbus_proxy_new_for_bus_finish(result, getter_Transfers(error)));
+ if (!proxy) {
+ LOG_NMP("failed to close session: %s", error->message);
+ LogError(__func__, *error);
+ return RejectPromiseWithErrorMessage(*callbackData->promise, *error);
+ }
+
+ g_dbus_proxy_call(proxy, "Close", nullptr, G_DBUS_CALL_FLAGS_NONE, -1,
+ nullptr, &NativeMessagingPortal::OnCloseSessionDone,
+ callbackData.release());
+}
+
+/* static */
+void NativeMessagingPortal::OnCloseSessionDone(GObject* source,
+ GAsyncResult* result,
+ gpointer user_data) {
+ GDBusProxy* proxy = G_DBUS_PROXY(source);
+ UniquePtr<CallbackData> callbackData(static_cast<CallbackData*>(user_data));
+
+ RefPtr<NativeMessagingPortal> portal = GetSingleton();
+ GUniquePtr<GError> error;
+ RefPtr<GVariant> res = dont_AddRef(
+ g_dbus_proxy_call_finish(proxy, result, getter_Transfers(error)));
+ if (res) {
+ LOG_NMP("session %s closed", callbackData->sessionHandle.get());
+ portal->mSessions.erase(callbackData->sessionHandle.get());
+ callbackData->promise->MaybeResolve(NS_OK);
+ } else {
+ LOG_NMP("failed to close session %s: %s", callbackData->sessionHandle.get(),
+ error->message);
+ LogError(__func__, *error);
+ portal->mSessions[callbackData->sessionHandle.get()] = SessionState::Error;
+ RejectPromiseWithErrorMessage(*callbackData->promise, *error);
+ }
+}
+
+/* static */
+void NativeMessagingPortal::OnSessionClosedSignal(
+ GDBusConnection* bus, const gchar* sender_name, const gchar* object_path,
+ const gchar* interface_name, const gchar* signal_name, GVariant* parameters,
+ gpointer user_data) {
+ guint subscription_id = *reinterpret_cast<guint*>(user_data);
+ LOG_NMP("session %s was closed by the portal", object_path);
+ g_dbus_connection_signal_unsubscribe(bus, subscription_id);
+ RefPtr<NativeMessagingPortal> portal = GetSingleton();
+ portal->mSessions.erase(object_path);
+}
+
+NS_IMETHODIMP
+NativeMessagingPortal::Start(const nsACString& aHandle, const nsACString& aName,
+ const nsACString& aExtension, JSContext* aCx,
+ dom::Promise** aPromise) {
+ const nsCString& sessionHandle = PromiseFlatCString(aHandle);
+ const nsCString& name = PromiseFlatCString(aName);
+ const nsCString& extension = PromiseFlatCString(aExtension);
+
+ if (!g_variant_is_object_path(sessionHandle.get())) {
+ LOG_NMP("cannot start %s, invalid session handle %s", name.get(),
+ sessionHandle.get());
+ return NS_ERROR_INVALID_ARG;
+ }
+
+ auto sessionIterator = mSessions.find(sessionHandle.get());
+ if (sessionIterator == mSessions.end()) {
+ LOG_NMP("cannot start %s, unknown session handle %s", name.get(),
+ sessionHandle.get());
+ return NS_ERROR_INVALID_ARG;
+ }
+
+ if (sessionIterator->second != SessionState::Active) {
+ LOG_NMP("cannot start %s, inactive session %s", name.get(),
+ sessionHandle.get());
+ return NS_ERROR_FAILURE;
+ }
+
+ if (!mProxy) {
+ LOG_NMP("cannot start %s, missing D-Bus proxy", name.get());
+ return NS_ERROR_FAILURE;
+ }
+
+ RefPtr<dom::Promise> promise;
+ MOZ_TRY(GetPromise(aCx, promise));
+
+ auto callbackData = MakeUnique<CallbackData>(*promise, sessionHandle.get());
+ auto* releasedCallbackData = callbackData.release();
+
+ LOG_NMP("starting %s, requested by %s in session %s", name.get(),
+ extension.get(), sessionHandle.get());
+
+ GDBusConnection* connection = g_dbus_proxy_get_connection(mProxy);
+ GUniquePtr<gchar> senderName(
+ g_strdup(g_dbus_connection_get_unique_name(connection)));
+ g_strdelimit(senderName.get(), ".", '_');
+ GUniquePtr<gchar> handleToken(
+ g_strdup_printf("%s/%d", MOZ_APP_NAME, g_random_int_range(0, G_MAXINT)));
+ GUniquePtr<gchar> requestPath(
+ g_strdup_printf("/org/freedesktop/portal/desktop/request/%s/%s",
+ senderName.get() + 1, handleToken.get()));
+ releasedCallbackData->subscription_id = g_dbus_connection_signal_subscribe(
+ connection, "org.freedesktop.portal.Desktop",
+ "org.freedesktop.portal.Request", "Response", requestPath.get(), nullptr,
+ G_DBUS_SIGNAL_FLAGS_NONE,
+ &NativeMessagingPortal::OnStartRequestResponseSignal,
+ releasedCallbackData, nullptr);
+
+ auto callbackDataCopy =
+ MakeUnique<CallbackData>(*promise, sessionHandle.get());
+ GVariantBuilder options;
+ g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT);
+ g_variant_builder_add(&options, "{sv}", "handle_token",
+ g_variant_new_string(handleToken.get()));
+ g_dbus_proxy_call(mProxy, "Start",
+ g_variant_new("(ossa{sv})", sessionHandle.get(), name.get(),
+ extension.get(), &options),
+ G_DBUS_CALL_FLAGS_NONE, -1, nullptr,
+ &NativeMessagingPortal::OnStartDone,
+ callbackDataCopy.release());
+
+ promise.forget(aPromise);
+ return NS_OK;
+}
+
+/* static */
+void NativeMessagingPortal::OnStartDone(GObject* source, GAsyncResult* result,
+ gpointer user_data) {
+ GDBusProxy* proxy = G_DBUS_PROXY(source);
+ UniquePtr<CallbackData> callbackData(static_cast<CallbackData*>(user_data));
+
+ GUniquePtr<GError> error;
+ RefPtr<GVariant> handle = dont_AddRef(
+ g_dbus_proxy_call_finish(proxy, result, getter_Transfers(error)));
+ if (handle) {
+ handle = dont_AddRef(g_variant_get_child_value(handle, 0));
+ LOG_NMP(
+ "native application start requested in session %s, pending response "
+ "for %s",
+ callbackData->sessionHandle.get(),
+ g_variant_get_string(handle, nullptr));
+ } else {
+ LOG_NMP("failed to start native application in session %s: %s",
+ callbackData->sessionHandle.get(), error->message);
+ LogError(__func__, *error);
+ RejectPromiseWithErrorMessage(*callbackData->promise, *error);
+ }
+}
+
+/* static */
+void NativeMessagingPortal::OnStartRequestResponseSignal(
+ GDBusConnection* bus, const gchar* sender_name, const gchar* object_path,
+ const gchar* interface_name, const gchar* signal_name, GVariant* parameters,
+ gpointer user_data) {
+ UniquePtr<CallbackData> callbackData(static_cast<CallbackData*>(user_data));
+
+ LOG_NMP("got response signal for %s in session %s", object_path,
+ callbackData->sessionHandle.get());
+ g_dbus_connection_signal_unsubscribe(bus, callbackData->subscription_id);
+
+ RefPtr<GVariant> result =
+ dont_AddRef(g_variant_get_child_value(parameters, 0));
+ guint32 value = g_variant_get_uint32(result);
+ if (value == 0) {
+ LOG_NMP(
+ "native application start successful in session %s, requesting file "
+ "descriptors",
+ callbackData->sessionHandle.get());
+ RefPtr<NativeMessagingPortal> portal = GetSingleton();
+ GVariantBuilder options;
+ g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT);
+ g_dbus_proxy_call_with_unix_fd_list(
+ portal->mProxy.get(), "GetPipes",
+ g_variant_new("(oa{sv})", callbackData->sessionHandle.get(), &options),
+ G_DBUS_CALL_FLAGS_NONE, -1, nullptr, nullptr,
+ &NativeMessagingPortal::OnGetPipesDone, callbackData.release());
+ } else if (value == 1) {
+ LOG_NMP("native application start canceled by user in session %s",
+ callbackData->sessionHandle.get());
+ callbackData->promise->MaybeRejectWithAbortError(
+ "Native application start canceled by user");
+ } else {
+ LOG_NMP("native application start failed in session %s",
+ callbackData->sessionHandle.get());
+ callbackData->promise->MaybeRejectWithNotFoundError(
+ "Native application start failed");
+ }
+}
+
+static gint GetFD(const RefPtr<GVariant>& result, GUnixFDList* fds,
+ gint index) {
+ RefPtr<GVariant> value =
+ dont_AddRef(g_variant_get_child_value(result, index));
+ GUniquePtr<GError> error;
+ gint fd = g_unix_fd_list_get(fds, g_variant_get_handle(value),
+ getter_Transfers(error));
+ if (fd == -1) {
+ LOG_NMP("failed to get file descriptor at index %d: %s", index,
+ error->message);
+ LogError("GetFD", *error);
+ }
+ return fd;
+}
+
+/* static */
+void NativeMessagingPortal::OnGetPipesDone(GObject* source,
+ GAsyncResult* result,
+ gpointer user_data) {
+ GDBusProxy* proxy = G_DBUS_PROXY(source);
+ UniquePtr<CallbackData> callbackData(static_cast<CallbackData*>(user_data));
+ auto promise = callbackData->promise;
+
+ RefPtr<GUnixFDList> fds;
+ GUniquePtr<GError> error;
+ RefPtr<GVariant> pipes =
+ dont_AddRef(g_dbus_proxy_call_with_unix_fd_list_finish(
+ proxy, getter_AddRefs(fds), result, getter_Transfers(error)));
+
+ if (!pipes) {
+ LOG_NMP(
+ "failed to get file descriptors for native application in session %s: "
+ "%s",
+ callbackData->sessionHandle.get(), error->message);
+ LogError(__func__, *error);
+ return RejectPromiseWithErrorMessage(*promise, *error);
+ }
+
+ gint32 _stdin = GetFD(pipes, fds, 0);
+ gint32 _stdout = GetFD(pipes, fds, 1);
+ gint32 _stderr = GetFD(pipes, fds, 2);
+ LOG_NMP(
+ "got file descriptors for native application in session %s: (%d, %d, %d)",
+ callbackData->sessionHandle.get(), _stdin, _stdout, _stderr);
+
+ if (_stdin == -1 || _stdout == -1 || _stderr == -1) {
+ return promise->MaybeRejectWithOperationError("Invalid file descriptor");
+ }
+
+ dom::AutoJSAPI jsapi;
+ if (NS_WARN_IF(!jsapi.Init(promise->GetGlobalObject()))) {
+ return promise->MaybeRejectWithUnknownError(
+ "Failed to initialize JS context");
+ }
+ JSContext* cx = jsapi.cx();
+
+ JS::Rooted<JSObject*> jsPipes(cx, JS_NewPlainObject(cx));
+ if (!jsPipes) {
+ return promise->MaybeRejectWithOperationError(
+ "Failed to create a JS object to hold the file descriptors");
+ }
+
+ auto setPipeProperty = [&](const char* name, int32_t value) {
+ JS::Rooted<JS::Value> jsValue(cx, JS::Value::fromInt32(value));
+ return JS_SetProperty(cx, jsPipes, name, jsValue);
+ };
+ if (!setPipeProperty("stdin", _stdin)) {
+ return promise->MaybeRejectWithOperationError(
+ "Failed to set the 'stdin' property on the JS object");
+ }
+ if (!setPipeProperty("stdout", _stdout)) {
+ return promise->MaybeRejectWithOperationError(
+ "Failed to set the 'stdout' property on the JS object");
+ }
+ if (!setPipeProperty("stderr", _stderr)) {
+ return promise->MaybeRejectWithOperationError(
+ "Failed to set the 'stderr' property on the JS object");
+ }
+
+ promise->MaybeResolve(jsPipes);
+}
+
+} // namespace mozilla::extensions
diff --git a/toolkit/components/extensions/NativeMessagingPortal.h b/toolkit/components/extensions/NativeMessagingPortal.h
new file mode 100644
index 0000000000000..20bb8c349cc83
--- /dev/null
+++ b/toolkit/components/extensions/NativeMessagingPortal.h
@@ -0,0 +1,74 @@
+/* -*- 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/. */
+
+#ifndef mozilla_extensions_NativeMessagingPortal_h
+#define mozilla_extensions_NativeMessagingPortal_h
+
+#include "nsINativeMessagingPortal.h"
+
+#include <gio/gio.h>
+
+#include "mozilla/GRefPtr.h"
+#include "mozilla/UniquePtr.h"
+
+#include <deque>
+#include <unordered_map>
+
+namespace mozilla::extensions {
+
+enum class SessionState { Active, Closing, Error };
+
+class NativeMessagingPortal : public nsINativeMessagingPortal {
+ public:
+ NS_DECL_NSINATIVEMESSAGINGPORTAL
+ NS_DECL_ISUPPORTS
+
+ static already_AddRefed<NativeMessagingPortal> GetSingleton();
+
+ private:
+ NativeMessagingPortal();
+ virtual ~NativeMessagingPortal();
+
+ RefPtr<GDBusProxy> mProxy;
+ bool mInitialized = false;
+ RefPtr<GCancellable> mCancellable;
+
+ struct DelayedCall;
+ std::deque<UniquePtr<DelayedCall>> mPending;
+
+ using SessionsMap = std::unordered_map<std::string, SessionState>;
+ SessionsMap mSessions;
+
+ // Callbacks
+ static void OnProxyReady(GObject* source, GAsyncResult* result,
+ gpointer user_data);
+ void MaybeDelayedIsAvailable(dom::Promise&, GVariant*);
+ void MaybeDelayedCreateSession(dom::Promise&, GVariant*);
+ static void OnCreateSessionDone(GObject* source, GAsyncResult* result,
+ gpointer user_data);
+ static void OnCloseSessionProxyReady(GObject* source, GAsyncResult* result,
+ gpointer user_data);
+ static void OnCloseSessionDone(GObject* source, GAsyncResult* result,
+ gpointer user_data);
+ static void OnSessionClosedSignal(GDBusConnection* bus,
+ const gchar* sender_name,
+ const gchar* object_path,
+ const gchar* interface_name,
+ const gchar* signal_name,
+ GVariant* parameters, gpointer user_data);
+ static void OnStartDone(GObject* source, GAsyncResult* result,
+ gpointer user_data);
+ static void OnStartRequestResponseSignal(
+ GDBusConnection* bus, const gchar* sender_name, const gchar* object_path,
+ const gchar* interface_name, const gchar* signal_name,
+ GVariant* parameters, gpointer user_data);
+ static void OnGetPipesDone(GObject* source, GAsyncResult* result,
+ gpointer user_data);
+};
+
+} // namespace mozilla::extensions
+
+#endif // mozilla_extensions_NativeMessagingPortal_h
diff --git a/toolkit/components/extensions/components.conf b/toolkit/components/extensions/components.conf
index 0b6461f13dd62..628adc096cc75 100644
--- a/toolkit/components/extensions/components.conf
+++ b/toolkit/components/extensions/components.conf
@@ -14,3 +14,15 @@ Classes = [
'categories': {'app-startup': 'ExtensionsChild'},
},
]
+
+if buildconfig.substs['MOZ_WIDGET_TOOLKIT'] == 'gtk' and defined('MOZ_ENABLE_DBUS'):
+ Classes += [
+ {
+ 'cid': '{8a9a1406-d700-4221-8615-1d84b0d213fb}',
+ 'contract_ids': ['@mozilla.org/extensions/native-messaging-portal;1'],
+ 'singleton': True,
+ 'type': 'mozilla::extensions::NativeMessagingPortal',
+ 'constructor': 'mozilla::extensions::NativeMessagingPortal::GetSingleton',
+ 'headers': ['mozilla/extensions/NativeMessagingPortal.h'],
+ },
+ ]
diff --git a/toolkit/components/extensions/moz.build b/toolkit/components/extensions/moz.build
index 9f22293d6de6d..bdfc9a41e1496 100644
--- a/toolkit/components/extensions/moz.build
+++ b/toolkit/components/extensions/moz.build
@@ -76,6 +76,7 @@ XPIDL_SOURCES += [
"extIWebNavigation.idl",
"mozIExtensionAPIRequestHandling.idl",
"mozIExtensionProcessScript.idl",
+ "nsINativeMessagingPortal.idl",
]
XPIDL_MODULE = "webextensions"
@@ -102,6 +103,13 @@ UNIFIED_SOURCES += [
"WebExtensionPolicy.cpp",
]
+if CONFIG["MOZ_WIDGET_TOOLKIT"] == "gtk" and CONFIG["MOZ_ENABLE_DBUS"]:
+ EXPORTS.mozilla.extensions += ["NativeMessagingPortal.h"]
+ UNIFIED_SOURCES += ["NativeMessagingPortal.cpp"]
+ CXXFLAGS += CONFIG["MOZ_DBUS_GLIB_CFLAGS"]
+ CXXFLAGS += CONFIG["MOZ_GTK3_CFLAGS"]
+ DEFINES["MOZ_APP_NAME"] = '"%s"' % CONFIG["MOZ_APP_NAME"]
+
XPCOM_MANIFESTS += [
"components.conf",
]
diff --git a/toolkit/components/extensions/nsINativeMessagingPortal.idl b/toolkit/components/extensions/nsINativeMessagingPortal.idl
new file mode 100644
index 0000000000000..30ae5f35bffba
--- /dev/null
+++ b/toolkit/components/extensions/nsINativeMessagingPortal.idl
@@ -0,0 +1,71 @@
+/* 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 "nsISupports.idl"
+
+/**
+ * An interface to talk to the WebExtensions XDG desktop portal,
+ * for sandboxed browsers (e.g. packaged as a snap or a flatpak).
+ * See https://github.com/flatpak/xdg-desktop-portal/issues/655.
+ */
+[scriptable, builtinclass, uuid(7c3003e8-6d10-46cc-b754-70cd889871e7)]
+interface nsINativeMessagingPortal : nsISupports
+{
+ /**
+ * Whether client code should use the portal, or fall back to the "legacy"
+ * implementation that spawns and communicates directly with native
+ * applications.
+ */
+ boolean shouldUse();
+
+ /**
+ * Whether the portal is available and can be talked to. It is an error to
+ * call other methods in this interface if the portal isn't available.
+ *
+ * @returns Promise that resolves with a boolean that reflects
+ the availability of the portal.
+ */
+ [implicit_jscontext]
+ readonly attribute Promise available;
+
+ /**
+ * Create a native messaging session.
+ *
+ * @param aApplication The name of the native application which the portal is
+ * being requested to talk to. See
+ * https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_manifests#native_messaging_manifests.
+ *
+ * @returns Promise that resolves with a string that represents the
+ session handle (a D-Bus object path of the form
+ /org/freedesktop/portal/desktop/session/SENDER/TOKEN).
+ */
+ [implicit_jscontext]
+ Promise createSession(in ACString aApplication);
+
+ /**
+ * Close a previously open session.
+ *
+ * @param aHandle The handle of a valid session.
+ *
+ * @returns Promise that resolves when the session is successfully closed.
+ */
+ [implicit_jscontext]