Repository navigation
Expand file tree
/
Copy pathportal.py
More file actions
2184 lines (1965 loc) · 91.5 KB
/
Copy pathportal.py
File metadata and controls
2184 lines (1965 loc) · 91.5 KB
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
"""Negotiate an EIS connection by driving a portal directly over D-Bus.
Not through :mod:`libei.oeffis` -- see that module instead for the simpler,
liboeffis-backed path.
Two portals, two directions. :class:`RemoteDesktopSession` negotiates
``org.freedesktop.portal.RemoteDesktop`` to *inject* input; below it,
:class:`InputCaptureSession` negotiates the separate
``org.freedesktop.portal.InputCapture`` to *receive* real input from the
user's own devices instead -- see its own class docstring, including why
it has never been run against a real portal. Everything in this module
docstring up to :class:`InputCaptureSession`'s own section is about
``RemoteDesktopSession`` specifically.
:mod:`libei.oeffis` wraps liboeffis, whose C API
(``oeffis_create_session()``) takes only a device-type bitmask -- it exposes
neither ``persist_mode`` nor the ``restore_token`` a caller needs to avoid
re-prompting the user on every run. Upstream's own documentation is explicit
about why: liboeffis is "intentionally kept simple, any more complex needs
should be handled by an application talking to DBus directly"
(https://libinput.pages.freedesktop.org/libei/api/group__liboeffis.html).
This module is that: the ``CreateSession`` -> ``SelectDevices`` -> ``Start``
-> ``ConnectToEIS`` sequence driven directly, with ``persist_mode`` and
``restore_token`` exposed as real parameters::
with RemoteDesktopSession.negotiate(
devices=DeviceType.POINTER | DeviceType.KEYBOARD,
persist_mode=PersistMode.UNTIL_REVOKED,
restore_token=saved_token, # None on the first run
) as session:
save_somewhere(session.restore_token) # for next time
sender = ei.Sender.create_for_fd(session.eis_fd, name="my-app")
... # inject input for as long as the session is needed
Three things worth knowing before building on this:
* **Blocking, not event-driven.** Unlike :class:`libei.oeffis.Oeffis`
(poll ``fd``, call ``dispatch()`` until it returns ``True``),
:meth:`RemoteDesktopSession.negotiate` runs its own nested
``GLib.MainLoop`` per D-Bus round trip and returns only once the whole
sequence has resolved, or raises. liboeffis is itself event-driven, which
is why ``Oeffis`` is; a caller driving GDBus directly already has
``GLib.MainLoop`` available to it, and there is no equivalent requirement
here to expose an async surface -- so this doesn't. Each round trip is
bounded by ``timeout`` (:class:`PortalTimeoutError` when it expires),
since a blocking call with no escape hatch is the one thing ``Oeffis``'s
pollable fd would otherwise buy you.
* **Close it when done.** The portal session outlives this object unless
``Session.Close()`` is called, and the EIS fd is owned by whoever
received it. :meth:`RemoteDesktopSession.close` (and the context-manager
form above) does both; see that method for what it does and does not
clean up.
* **Least automatically verified path in this package**, same caveat
:mod:`libei.oeffis` carries: nothing in CI can click through a real
consent dialog, so ``tests/test_portal.py`` exercises the
request/response orchestration against a fake D-Bus connection only.
Verified by hand 2026-09-01 against a real GNOME Wayland session
(xdg-desktop-portal, ``RemoteDesktop`` v2), end to end: a first run
raised the consent dialog and was approved with "Remember" checked
(5.4s), and a second run replaying the ``restore_token`` was granted
with no dialog at all (0.2s) -- which is the whole point of
``persist_mode``, and is also what proves the first run was a genuine
first-time authorisation rather than a pre-existing grant. Three devices
resumed on the returned fd: relative pointer, keyboard, then absolute
pointer -- in that order, which is exactly the device race ``ei``-side
callers have to handle. ``Session.Close()`` was exercised too. No input
was injected: emulation is ``libei.ei``'s job and is not what this
module does.
"""
from __future__ import annotations
import contextlib
import enum
import logging
import os
import time
import uuid
from typing import Any, NamedTuple
from .oeffis import DeviceType
logger = logging.getLogger("libei.portal")
__all__ = [
"DeviceType",
"PersistMode",
"PortalError",
"PortalVersionError",
"PortalDeniedError",
"PortalTimeoutError",
"PortalSessionClosedError",
"PortalProtocolError",
"RemoteDesktopSession",
"Activation",
"InputCaptureSession",
"is_available",
]
_BUS_NAME = "org.freedesktop.portal.Desktop"
_OBJECT_PATH = "/org/freedesktop/portal/desktop"
_REMOTE_DESKTOP = "org.freedesktop.portal.RemoteDesktop"
_INPUT_CAPTURE = "org.freedesktop.portal.InputCapture"
_REQUEST_INTERFACE = "org.freedesktop.portal.Request"
_SESSION_INTERFACE = "org.freedesktop.portal.Session"
_MIN_REMOTE_DESKTOP_VERSION = 2 # ConnectToEIS needs v2+
_MIN_INPUT_CAPTURE_VERSION = 2 # CreateSession2 is a v2-only method
_DEFAULT_TIMEOUT = 60.0
"""Seconds to wait for one portal round trip. Generous, because a user has
to see and answer the consent dialog `Start` raises -- but bounded, because
the alternative is a caller wedged forever if the portal dies after
accepting the call and before sending its `Response`."""
_GIO_DEFAULT_TIMEOUT_MSEC = 25_000
"""What GDBus's ``-1`` reply timeout actually is.
``call_sync(..., -1, ...)`` does not mean "wait forever" -- that is
``G_MAXINT`` -- it means GIO's own default, which is 25 seconds. Only used
to report the right number when a call left on that default runs out of
time; see `_call_sync`."""
_G_IO_ERROR_DOMAIN = "g-io-error-quark"
"""The GLib error domain GDBus reports its own reply timeout in.
Not one of the ``org.freedesktop.DBus.Error.*`` codes, as one might expect:
a ``call_sync()`` whose reply never arrives raises ``G_IO_ERROR_TIMED_OUT``
in this domain with the message "Timeout was reached" (checked against a
service that accepts a call and then deliberately never answers). See
`_is_reply_timeout`."""
_ALL_DEVICE_TYPES = DeviceType.KEYBOARD | DeviceType.POINTER | DeviceType.TOUCHSCREEN
"""Every bit the RemoteDesktop `types` bitmask defines.
`DeviceType.ALL_DEVICES` is liboeffis's own sentinel and is literally 0,
which the portal reads as *no* device types rather than all of them -- a
session that negotiates fine and then never resumes a single device. The
sentinel is translated to this before it reaches `SelectDevices`."""
class PersistMode(enum.IntEnum):
"""``SelectDevices``'s ``persist_mode`` option, per the RemoteDesktop XML."""
NONE = 0
WHILE_RUNNING = 1
UNTIL_REVOKED = 2
class PortalError(Exception):
"""Base class for this module's failures."""
class PortalVersionError(PortalError):
"""The compositor's RemoteDesktop portal is too old for ConnectToEIS."""
class PortalTimeoutError(PortalError):
"""A portal request did not answer within the timeout.
Distinct from a decline: the portal accepted the call and then never
sent its ``Response`` signal. Most often the consent dialog is simply
still waiting for a user, so raise the timeout rather than treating
this as a failure if that is expected.
"""
def __init__(self, step: str, timeout: float) -> None:
"""Name which step timed out and after how long."""
super().__init__(f"{step} did not answer within {timeout:g}s")
self.step = step
self.timeout = timeout
class PortalDeniedError(PortalError):
"""``CreateSession``, ``SelectDevices`` or ``Start`` was not approved.
Covers both an explicit user decline and any other non-zero portal
response code -- the portal spec does not guarantee a code means
"the user said no" versus some other failure, so this does not either.
"""
def __init__(self, step: str, message: str | None = None) -> None:
"""Name which step was refused and, where the portal gave one, why."""
super().__init__(message or f"{step} was not approved")
self.step = step
self.message = message
class PortalProtocolError(PortalError):
"""A portal signal arrived with a payload that does not match the spec.
Every signal :func:`_wait_for_signal` waits on is specified as
``(o session_handle, a{sv} options)``, and two kinds of mismatch used
to fail in two different, equally unhelpful ways. The *shape* being
wrong -- an empty tuple, a non-string handle, a wrong-length tuple, a
non-dict options -- either raised ``IndexError`` *inside* the GLib
signal callback, where PyGI prints the traceback to stderr and
swallows it so the wait hung invisibly (unboundedly, with
``timeout=None``), or slipped through to the caller and crashed it with
``ValueError``/``AttributeError``. A *value* inside a correctly-shaped
options being wrong -- an ``activation_id`` that is not an integer, a
``cursor_position`` that is not two numbers -- crashed the caller later
still, doing arithmetic on it. Both now end the wait with this error.
``detail`` distinguishes the two: ``None`` for a shape fault (the
default message names the expected shape), a phrase for a value fault
(naming the field). ``payload`` is whatever best shows the fault -- the
whole signal tuple for a shape fault, the options dict for a value one.
:func:`_request` raises it the same way for a ``Request``'s
``Response`` reply that does not match its own ``(u response, a{sv}
results)`` shape, and :meth:`InputCaptureSession.zones` for a result
value that is not the type the spec gives it -- always with a
``detail`` phrase, since the default shape message above is specific
to the session signals. ``step`` is then the method name, matching the
sibling errors raised from the same call.
:func:`_call_for_fd` -- both portals' ``ConnectToEIS``, whose reply is
an *index* into a separate out fd list -- raises it for
the three ways that pair can disagree: no fd list attached at all
(the out list is nullable), an index outside the list, and the dup
``g_unix_fd_list_get()`` does failing on fd exhaustion. ``payload`` is
the index in each case. Those used to reach the caller as an
``AttributeError``, a silent ``-1`` fd, and a raw ``GLib.Error``
respectively -- none of them catchable as a ``PortalError``.
"""
def __init__(self, step: str, payload: object, detail: str | None = None) -> None:
"""Name the signal, what arrived, and -- for a value fault -- which."""
reason = detail or (
"the portal spec gives it the shape (session_handle, options dict)"
)
super().__init__(
f"{step} arrived with a malformed payload: {reason}, got {payload!r}"
)
# `step` mirrors the attribute every sibling portal error raised
# from the same `_wait_for_signal` call site carries
# (PortalTimeoutError, PortalSessionClosedError), so a caller that
# catches PortalError and reads `.step` works across all of them.
self.step = step
self.payload = payload
self.detail = detail
class PortalSessionClosedError(PortalError):
"""The portal session ended while something was still waiting on it.
The ``org.freedesktop.portal.Session`` interface emits ``Closed`` when
the compositor or the portal ends a session from its side -- a
compositor restart, the portal process dying, a session revoked from a
settings panel. Distinct from :class:`PortalTimeoutError` (the session
is fine, the signal just has not come) and from
:class:`PortalDeniedError` (a request was answered, negatively): here
there is no session left to answer anything, so the wait that raised
this can never be satisfied by waiting longer.
"""
def __init__(self, step: str) -> None:
"""Name what was being waited for when the session went away."""
super().__init__(
f"the portal session was closed while waiting for {step}; "
"the compositor or portal ended it from its side"
)
self.step = step
def _gio() -> tuple[Any, Any] | None:
"""Import Gio and GLib, or return None.
Deferred so importing this module never requires PyGObject -- the same
"zero hard dependencies, probed at runtime" rule the rest of this
package follows. See is_available().
"""
try:
import gi
gi.require_version("Gio", "2.0")
from gi.repository import Gio, GLib
except Exception:
return None
return Gio, GLib
def is_available() -> bool:
"""Whether PyGObject (Gio) can be imported on this system.
Does not check for a running session bus or a portal implementation --
only whether the Python side this module needs is installed. A missing
session bus or portal surfaces as a `PortalError` from `negotiate()`.
"""
return _gio() is not None
def _glib_error(GLib: Any) -> Any:
"""``GLib.Error``, or a tuple that catches nothing where it is absent.
Every GDBus failure -- no session bus, no portal implementation behind
the name, a method that returns a D-Bus error -- arrives as this one
exception type. It is looked up rather than imported so that a test
double standing in for ``GLib`` need not define it: `except ()` catches
nothing, which is the right behaviour when there is no real GLib whose
errors could be raised in the first place.
"""
return getattr(GLib, "Error", ())
def _is_reply_timeout(Gio: Any, exc: Exception) -> bool:
"""Whether a GDBus failure is its own reply timeout expiring.
Worth telling apart from every other ``GLib.Error``, because it means
exactly what the nested loop's own timeout means -- nobody answered in
the time allowed -- and so should raise the `PortalTimeoutError` a
caller is documented to catch for that, not a generic `PortalError`.
Defensive throughout: a test double standing in for ``Gio`` need not
define ``IOErrorEnum``, and one standing in for ``GLib.Error`` need not
carry a domain or a code. An attribute that isn't there just means
"not a timeout", which is the safe answer -- the failure still reaches
the caller, only as the more general error.
"""
timed_out = getattr(getattr(Gio, "IOErrorEnum", None), "TIMED_OUT", None)
if timed_out is None:
return False
return (
getattr(exc, "domain", None) == _G_IO_ERROR_DOMAIN
and getattr(exc, "code", None) == timed_out
)
def _msec_until(deadline: float) -> int:
"""Milliseconds left before ``deadline``, never negative.
Both legs of a round trip -- the call that returns the request handle,
then the wait for its ``Response`` signal -- draw down the same
deadline, so ``timeout`` bounds the round trip rather than each half of
it separately, which would let a slow first leg quietly double the wait
a caller asked for. Zero is a legitimate answer: GLib fires a 0ms
timeout on the next main-loop iteration, which is the right thing for a
deadline that has already passed.
"""
return max(0, int((deadline - time.monotonic()) * 1000))
def _call_sync(
connection: Any,
Gio: Any,
GLib: Any,
busname: str,
object_path: str,
interface: str,
method: str,
parameters: Any,
reply_type: Any,
timeout_msec: int = -1,
) -> Any:
"""``call_sync``, with GDBus failures translated to `PortalError`.
Without this a `GLib.Error` propagates raw, so the no-session-bus and
no-portal-backend cases -- exactly the ones `is_available()` documents
as surfacing here, since it deliberately checks neither -- escape a
caller's `except PortalError`.
``timeout_msec`` is GDBus's own reply timeout, and defaults to its
``-1`` -- GIO's 25 seconds (see `_GIO_DEFAULT_TIMEOUT_MSEC`), which is
what `RemoteDesktopSession.close` leaves it at, having no caller-facing
timeout to honour. Anything reached from `negotiate` passes the
caller's own ``timeout`` instead, so that the bound on a round trip is
the documented one rather than a number this module never chose.
"""
try:
return connection.call_sync(
busname,
object_path,
interface,
method,
parameters,
reply_type,
Gio.DBusCallFlags.NONE,
timeout_msec,
None,
)
except _glib_error(GLib) as exc:
if _is_reply_timeout(Gio, exc):
expired = timeout_msec if timeout_msec >= 0 else _GIO_DEFAULT_TIMEOUT_MSEC
raise PortalTimeoutError(method, expired / 1000) from exc
raise PortalError(f"{method} failed on the D-Bus: {exc}") from exc
def _close_session(
connection: Any,
Gio: Any,
GLib: Any,
busname: str,
session_handle: str,
) -> None:
"""Call ``Session.Close()``, logging rather than raising on failure.
Shared by `RemoteDesktopSession.close` and `negotiate`'s failure path,
which need the same thing of it: the session may already be gone (the
portal restarted, the user revoked the grant), and neither a caller
tidying up nor an exception already unwinding is helped by a second
failure thrown over the top of the first.
"""
try:
_call_sync(
connection,
Gio,
GLib,
busname,
session_handle,
_SESSION_INTERFACE,
"Close",
None,
None,
)
except PortalError as exc:
logger.debug("closing the portal session failed: %s", exc)
def _returned_handle(reply: Any) -> str | None:
"""The request object path a Request-returning call replied with.
Every such portal method answers ``(o)``, but this stays defensive and
returns ``None`` on anything else: the value is only ever used as a
*second* path to listen on alongside the one derived from our own
handle_token, so a reply shaped unexpectedly is a reason to fall back to
that derived path, never to fail the negotiation outright.
"""
try:
unpacked = reply.unpack()
except Exception:
return None
if isinstance(unpacked, tuple) and len(unpacked) == 1:
handle = unpacked[0]
if isinstance(handle, str):
return handle
return None
def _request(
connection: Any,
Gio: Any,
GLib: Any,
busname: str,
interface: str,
method: str,
signature: str,
leading_args: tuple[Any, ...],
options: dict[str, Any],
timeout: float,
trailing_args: tuple[Any, ...] = (),
) -> tuple[int, Any]:
"""Call a Request-returning portal method, racelessly.
Subscribing to the ``Response`` signal only *after* the call that
returns its request handle is a real race, not a hypothetical one: a
fast, non-interactive response (no consent dialog involved, e.g.
``SelectDevices``) can arrive and be delivered before the subscription
is registered, hanging forever on a signal that already came and went.
Reproduced live (intermittent hangs at both ``SelectDevices`` and
``SelectSources`` in the code this was ported from). Fixed by choosing
the ``handle_token`` ourselves, computing the resulting request object
path up front, and subscribing to that exact path *before* making the
call at all -- the pattern xdg-desktop-portal's own documentation
describes.
Raises :class:`PortalTimeoutError` if the whole round trip -- the call
that returns the request handle, then the ``Response`` that answers it
-- exceeds ``timeout``. The nested loop is otherwise unbounded, and a
portal that dies after accepting the call sends no ``Response`` and no
error, leaving the caller wedged with nothing to poll and no way out.
Both legs share one deadline (see `_msec_until`), since a caller asking
for 60 seconds means the answer arrives inside 60 seconds, not inside
however many 60-second waits the sequence happens to be built from.
A ``Response`` whose payload does not match the spec's ``(u response,
a{sv} results)`` shape raises :class:`PortalProtocolError` rather than
being unpacked on faith -- the same hardening `_wait_for_signal`
applies to the signals it waits on, and for the same two reasons: a
wrong-arity payload used to raise inside the GLib callback, where PyGI
swallows it, degrading the step to a full-timeout
:class:`PortalTimeoutError`; a non-dict ``results`` instead slipped
through to the caller, whose ``.get()`` crashed with a raw
``AttributeError`` past ``except PortalError``. The guarantee callers
rely on is therefore structural: what this returns is always an
``int`` code and a ``dict`` of results.
``trailing_args``, appended after ``options`` in the call's parameter
tuple, exists for ``InputCapture.SetPointerBarriers`` -- the one
Request-returning method in either portal whose ``options`` is not its
last positional argument (``barriers`` and ``zone_set`` follow it).
Every RemoteDesktop call leaves this at its default, reproducing the
exact parameter tuple this function always built.
"""
deadline = time.monotonic() + timeout
unique_name = connection.get_unique_name()
escaped_sender = unique_name[1:].replace(".", "_")
token = uuid.uuid4().hex
options = dict(options)
options["handle_token"] = GLib.Variant("s", token)
expected_path = f"/org/freedesktop/portal/desktop/request/{escaped_sender}/{token}"
loop = GLib.MainLoop()
result: dict[str, Any] = {}
malformed: dict[str, Any] = {}
subscriptions: list[Any] = []
# Set inside the timeout callback rather than inferred from an empty
# `result` afterwards: a Response carrying no results is legitimate
# (SelectDevices answers with an empty dict), so "did the loop end
# because it timed out" has to be recorded, not deduced.
timed_out = False
# Distinct from `timed_out`: whether `on_timeout` ran at all, either
# path -- the flag the cleanup below keys "already removed?" on. See
# the matching pair in `_wait_for_signal`.
timeout_fired = False
def _settled() -> bool:
"""Whether some terminal outcome has already been recorded.
Same role as in `_wait_for_signal`: GLib dispatches every source
ready in one main-context iteration regardless of an earlier
``loop.quit()``, so a Response and the deadline can both fire in
the same poll -- the first recorded outcome wins, and a delivered
reply is never dropped for a timeout (or vice versa).
"""
return bool(result) or bool(malformed) or timed_out
def on_response(
_conn: Any,
_sender: Any,
_path: Any,
_iface: Any,
_signal: Any,
params: Any,
*_a: Any,
) -> None:
"""Record the first reply and quit the loop; later replies are ignored."""
if _settled(): # both subscriptions may fire; the first reply wins
return
args = params.unpack()
# Checked here, raised only after the loop: this runs inside a
# GLib callback, where PyGI prints an exception to stderr and
# swallows it -- a bare raise on a malformed Response would leave
# the loop running until the full timeout, misreported as
# PortalTimeoutError; a non-dict `results` let through instead
# crashed the caller's `.get()` with a raw AttributeError past
# `except PortalError`. Same hardening `_wait_for_signal` applies
# to the signals it waits on.
if (
not isinstance(args, tuple)
or len(args) != 2
or isinstance(args[0], bool)
or not isinstance(args[0], int)
or not isinstance(args[1], dict)
):
malformed["args"] = args
loop.quit()
return
result["code"], result["results"] = args
loop.quit()
def on_timeout() -> bool:
"""Stop the loop and record that it timed out rather than finished."""
nonlocal timed_out, timeout_fired
# Set first, before the early return: GLib removes the source the
# moment this returns False (which both paths do), so the finally
# block keys "already removed" on this, not on `timed_out` -- see
# the same dance in `_wait_for_signal`.
timeout_fired = True
if _settled():
# A Response delivered in the same poll as the deadline has
# already recorded its outcome; do not overwrite it.
return False
timed_out = True
loop.quit()
return False # one-shot; GLib removes the source when this is False
def subscribe(path: str) -> None:
"""Subscribe to Response on one path, keeping the handle alive."""
subscriptions.append(
connection.signal_subscribe(
busname,
_REQUEST_INTERFACE,
"Response",
path,
None,
Gio.DBusSignalFlags.NONE,
on_response,
None,
)
)
subscribe(expected_path)
try:
parameters = GLib.Variant(signature, (*leading_args, options, *trailing_args))
reply = _call_sync(
connection,
Gio,
GLib,
busname,
_OBJECT_PATH,
interface,
method,
parameters,
None,
_msec_until(deadline),
)
# The spec says the handle the call returns matches the path derived
# from our own handle_token, but a portal is free to hand back
# something else -- and some do. Listening on both is strictly safer
# than trusting either alone: watching only the derived path means a
# Response delivered to the returned handle is never seen, and the
# wait below then runs out the full timeout for no reason.
handle = _returned_handle(reply)
if handle is not None and handle != expected_path:
subscribe(handle)
# `if not _settled()` because a synchronous answer (a fast
# non-interactive Response, or a test double) can arrive during the
# call above, before run() is reached -- and quit() on a loop that
# is not running yet does not stop the later run(), so running it
# then would block with the reply already delivered. A malformed
# synchronous reply counts: it too has already quit a loop that
# was not running yet.
if not _settled():
timeout_source = GLib.timeout_add(_msec_until(deadline), on_timeout)
try:
loop.run()
finally:
# on_timeout() returns False, which is GLib's own signal to
# deregister a fired one-shot source -- removing it again
# here trips a real "Source ID N was not found when
# attempting to remove it" warning, the same bug already
# fixed for _wait_for_signal below. Only remove it when the
# *Response* woke the loop instead; leaving a live source in
# that case holds a reference to this closure and fires it
# into a dead loop on some later request. Keyed on
# `timeout_fired` (did on_timeout run), not `timed_out` (did
# the wait time out): a Response landing in the same poll as
# the deadline runs on_timeout down its `_settled` early
# return, which removes the source yet leaves `timed_out`
# False.
if not timeout_fired:
GLib.source_remove(timeout_source)
finally:
for subscription in subscriptions:
connection.signal_unsubscribe(subscription)
# Mirrors `_signal_outcome`: only one of these is ever set (every
# callback checks `_settled()` first), so the order here only decides
# between genuinely simultaneous dispatches.
if malformed:
raise PortalProtocolError(
method,
malformed["args"],
"the Request's Response signal is specified as "
"(uint response, results dict)",
)
if timed_out:
raise PortalTimeoutError(method, timeout)
return result["code"], result["results"]
def _call_for_fd(
connection: Any,
Gio: Any,
GLib: Any,
busname: str,
interface: str,
method: str,
session_handle: str,
timeout: float,
) -> int:
"""Call a method that returns a fd via a GUnixFDList index.
The fd that comes back is *owned* -- `g_unix_fd_list_get()` dups it --
so whoever receives it has to close it. See
:meth:`RemoteDesktopSession.close`.
``ConnectToEIS`` returns no `Request`, so there is no ``Response`` to
wait on and nothing here beyond the call itself -- but it is a call to
the same portal that just made the caller wait on a consent dialog, so
it is bounded by the same ``timeout`` rather than by GIO's default.
The reply carries only an *index* into a separate out fd list, and both
halves have to be checked before the index is used, because
`g_unix_fd_list_get()` will not check them for us:
* The out fd list is **nullable** -- ``call_with_unix_fd_list_sync()``
is specified to hand back ``NULL`` for it, so a well-formed ``(h)``
reply with no fds attached arrives here as ``None``. Dereferencing
that raised ``AttributeError`` at the caller, outside every
``except PortalError``.
* A bad index is a **programmer error**, not a runtime failure:
``g_unix_fd_list_get()`` asserts ``index >= 0 && index < nfd``,
logs ``GLib-GIO-CRITICAL`` and **returns -1 without raising and
without setting a GError** (measured on GLib 2.90.1). So an
out-of-range index cannot be caught by an ``except GLib.Error``; the
-1 just flows out as the EIS fd. Gio-2.0.gir says as much and names
the two fixes: ``lookup()``, which is GLib 2.90+ only, or a bounds
check against ``get_length()`` -- the portable one, used below.
The one real ``GLib.Error`` from ``get()`` is the dup itself failing on
an fd the list does hold, i.e. EMFILE/ENFILE.
"""
try:
reply, fd_list = connection.call_with_unix_fd_list_sync(
busname,
_OBJECT_PATH,
interface,
method,
GLib.Variant("(oa{sv})", (session_handle, {})),
GLib.VariantType.new("(h)"),
Gio.DBusCallFlags.NONE,
int(timeout * 1000),
None,
None,
)
except _glib_error(GLib) as exc:
if _is_reply_timeout(Gio, exc):
raise PortalTimeoutError(method, timeout) from exc
raise PortalError(f"{method} failed on the D-Bus: {exc}") from exc
(handle_index,) = reply.unpack()
# Each of the three checks below turns something that used to escape a
# caller's `except PortalError` -- an AttributeError, a silent -1, a raw
# GLib.Error -- into the same typed protocol error _request() raises for a
# malformed Response. See this function's docstring for the GLib contract
# they are reading.
if fd_list is None:
raise PortalProtocolError(
method,
handle_index,
"it returned an fd index but attached no fd list to the reply",
)
length = fd_list.get_length()
if handle_index < 0 or handle_index >= length:
raise PortalProtocolError(
method,
handle_index,
"the fd index it returned is out of range for the reply's fd list "
f"(index {handle_index}, {length} fd(s) attached)",
)
try:
fd = fd_list.get(handle_index)
except _glib_error(GLib) as exc:
# The index is in range, so this is not a lookup failure: the only
# thing left for g_unix_fd_list_get() to fail at is the dup() it does
# to hand back an owned fd.
raise PortalProtocolError(
method,
handle_index,
"duplicating the fd it returned failed -- this process is out of "
f"file descriptors ({exc})",
) from exc
if fd < 0:
# Unreachable via the bounds check above, which is the only documented
# way to get the -1 sentinel; kept so a future GLib that returns it for
# some other reason surfaces as a typed error rather than as a negative
# fd handed to ei.Sender.create_for_fd(), which does not check for one.
raise PortalProtocolError(
method,
handle_index,
f"its fd list returned no usable fd for index {handle_index} (got {fd})",
)
return fd
def _portal_version(reply: Any, interface: str) -> int:
"""The ``version`` property out of a `Properties.Get` reply, as an int.
`_call_sync` is given no ``reply_type``, here as everywhere else in this
module, so GDBus validates nothing about the shape of what comes back --
which is why every other reply-consuming site checks the unpacked value
before trusting it. These two did not: a reply that unpacked to anything
but a one-element tuple raised `ValueError`, and a ``version`` that was
not a number raised `TypeError`, both bare built-ins escaping the
`except PortalError` that `docs/troubleshooting.md` promises covers the
negotiation.
"""
unpacked = reply.unpack()
try:
(version,) = unpacked
except (ValueError, TypeError) as exc:
raise PortalProtocolError(
"Get",
unpacked,
f"{interface}'s version property is specified as a single "
f"value, and this reply is not that shape",
) from exc
# bool before int, because bool *is* an int: a True would otherwise read
# as version 1 and be refused as "too old", blaming the portal's version
# for a reply that was nonsense.
if isinstance(version, bool) or not isinstance(version, int):
raise PortalProtocolError(
"Get",
unpacked,
f"{interface} reported a non-numeric version {version!r}",
)
return version
def _remote_desktop_version(
connection: Any, Gio: Any, GLib: Any, busname: str, timeout: float
) -> int:
"""Read the RemoteDesktop portal's ``version`` property."""
reply = _call_sync(
connection,
Gio,
GLib,
busname,
_OBJECT_PATH,
"org.freedesktop.DBus.Properties",
"Get",
GLib.Variant("(ss)", (_REMOTE_DESKTOP, "version")),
None,
int(timeout * 1000),
)
return _portal_version(reply, _REMOTE_DESKTOP)
class RemoteDesktopSession:
"""A negotiated ``org.freedesktop.portal.RemoteDesktop`` session.
Two things here need releasing, and neither happens on its own when
this object is dropped:
* **The portal session.** It lives in xdg-desktop-portal, not in this
process, and persists until ``Session.Close()`` is called or the D-Bus
connection that created it drops. That connection is *not* owned here
-- ``Gio.bus_get_sync()`` hands back GLib's shared session-bus
singleton, which outlives any one session -- so a long-running process
that negotiates repeatedly accumulates live portal sessions until it
exits. :meth:`close` is what ends one.
* **The EIS fd**, which arrives dup'd and owned. Reading :attr:`eis_fd`
hands that ownership on (typically straight to
:meth:`libei.ei.Sender.create_for_fd`, which closes it itself); if it
is never read, :meth:`close` closes it rather than leaking it.
Use it as a context manager, or call :meth:`close` when done.
"""
def __init__(
self,
connection: Any,
eis_fd: int,
restore_token: str | None,
session_handle: str | None = None,
busname: str = _BUS_NAME,
) -> None:
"""Hold a negotiated session's handle, connection and EIS fd.
Not for direct use -- built by :meth:`negotiate` once ``Start`` and
``ConnectToEIS`` have both already succeeded.
"""
self._connection = connection
self._eis_fd: int | None = eis_fd
self._session_handle = session_handle
# Whichever bus name negotiate() used, not the default: a session
# created on an alternate portal name has to be closed on that same
# name, or Session.Close() goes to a portal that never heard of it.
self._busname = busname
# Mirrors libei.oeffis.Oeffis's ownership rule: reading `eis_fd`
# hands the fd to the caller, so close() must not also close it once
# that has happened -- but nothing else will ever close it if the
# session dies before anyone reads it, so close() must in that case.
self._eis_fd_claimed = False
self._closed = False
self.restore_token = restore_token
"""The token to pass as ``restore_token=`` on the next call to
avoid re-prompting, or ``None`` if the portal issued none -- either
because no ``persist_mode`` was requested, or the portal declined
to grant persistence.
Save whatever comes back on *every* run rather than only the first:
the portal is free to hand back a different token each time, and a
caller that keeps only the original would eventually present a stale
one. (Observed 2026-09-01 on GNOME: the same token comes back on
each restore. That is this portal's behaviour, not a guarantee --
the interface permits a new one.)
Nothing is written to disk here: a token is a standing grant of
input injection, so storing it is the caller's decision."""
@property
def eis_fd(self) -> int:
"""The fd to pass to :meth:`libei.ei.Sender.create_for_fd`.
Reading this transfers ownership of the fd to the caller -- after
that, closing it is the caller's job (or, far more usually, the
`Sender`'s, which takes ownership and closes it itself).
"""
if self._eis_fd is None:
raise PortalError("the session is closed; its EIS fd is gone")
self._eis_fd_claimed = True
return self._eis_fd
def close(self) -> None:
"""End the portal session, and close the EIS fd if unclaimed.
Idempotent. ``Session.Close()`` failures are logged and swallowed:
the session may already be gone (the portal restarted, the user
revoked the grant), and there is nothing a caller could usefully do
about it during cleanup either way.
Note that this does *not* disturb an `ei.Sender` already built on
the fd -- closing the portal session is what tears the EIS
connection down, so do it when finished injecting, not before.
"""
if self._closed:
return
self._closed = True
if self._eis_fd is not None and not self._eis_fd_claimed:
try:
os.close(self._eis_fd)
except OSError as exc:
# Nothing a caller could do about a failed close during
# cleanup, and raising here would mask whatever exception
# was already unwinding through a `with` block.
logger.debug("closing the EIS fd failed: %s", exc)
self._eis_fd = None
if self._session_handle is None or self._connection is None:
return
gio_modules = _gio()
if gio_modules is None: # pragma: no cover - unreachable once negotiated
return
Gio, GLib = gio_modules
try:
_close_session(
self._connection,
Gio,
GLib,
self._busname,
self._session_handle,
)
finally:
self._session_handle = None
self._connection = None
def __enter__(self) -> RemoteDesktopSession:
"""Return self: entering performs no action of its own."""
return self
def __exit__(self, *_exc: Any) -> None:
"""Close the session on the way out, whatever happened."""
self.close()
def __del__(self) -> None:
"""Close the fd only: __del__ can run during interpreter shutdown.
A synchronous D-Bus round trip there may hang or fail with nothing
left able to report it, so the D-Bus half of close() is deliberately
not attempted.
"""
# Deliberately only the fd, not the D-Bus half of close(): __del__
# can run during interpreter shutdown, where a synchronous D-Bus
# round trip may hang or fail in ways nothing can report. Closing an
# unclaimed fd is the part that is always safe and always necessary
# -- nothing else will ever close it. getattr() with defaults
# because __init__ can raise before these exist, and a bare
# attribute access would then raise AttributeError inside __del__,
# which Python only prints to stderr.
if getattr(self, "_eis_fd_claimed", True):
return
eis_fd = getattr(self, "_eis_fd", None)
if eis_fd is not None:
# an exception here is only printed to stderr anyway
with contextlib.suppress(OSError):
os.close(eis_fd)
@classmethod
def negotiate(
cls,
*,
connection: Any = None,
devices: DeviceType = DeviceType.ALL_DEVICES,
persist_mode: PersistMode = PersistMode.NONE,
restore_token: str | None = None,
busname: str = _BUS_NAME,
timeout: float = _DEFAULT_TIMEOUT,
) -> RemoteDesktopSession:
"""Negotiate a RemoteDesktop portal session and connect it to EIS.
Blocks until the whole ``CreateSession`` -> ``SelectDevices`` ->
``Start`` -> ``ConnectToEIS`` sequence resolves, prompting the user
for consent along the way unless ``restore_token`` lets the portal
skip that. Raises :class:`PortalVersionError` if the compositor's
RemoteDesktop portal is too old for ``ConnectToEIS`` (needs v2+),
:class:`PortalDeniedError` if any step is declined, and
:class:`PortalTimeoutError` if any one round trip exceeds
``timeout`` seconds (60 by default -- generous, since ``Start``
waits on a human answering a dialog). Any of those raised after
``CreateSession`` has succeeded closes the session it created on
the way out; nothing else could, since no `RemoteDesktopSession`
exists yet to own it and the portal would keep it alive for the
life of the bus connection.
``devices`` selects what to ask for. ``DeviceType.ALL_DEVICES`` is
liboeffis's sentinel for "everything" and is literally ``0``, which
the portal would read as *nothing*; it is translated here to every
type the portal defines.