-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchrome-remote-desktop
executable file
·2596 lines (2216 loc) · 99.1 KB
/
chrome-remote-desktop
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
#!/usr/bin/python3
# Copyright 2012 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Virtual Me2Me implementation. This script runs and manages the processes
# required for a Virtual Me2Me desktop, which are: X server, X desktop
# session, and Host process.
# This script is intended to run continuously as a background daemon
# process, running under an ordinary (non-root) user account.
import sys
if sys.version_info[0] != 3 or sys.version_info[1] < 5:
print("This script requires Python version 3.5")
sys.exit(1)
import abc
import argparse
import atexit
import base64
import errno
import fcntl
import getpass
import grp
import hashlib
import json
import logging
import os
import platform
import pwd
import re
import shlex
import shutil
import signal
import socket
import string
import struct
import subprocess
import syslog
import tempfile
import threading
import time
import uuid
import psutil
import xdg
from packaging import version
# If this env var is defined, extra host params will be loaded from this env var
# as a list of strings separated by space (\s+). Note that param that contains
# space is currently NOT supported and will be broken down into two params at
# the space character.
HOST_EXTRA_PARAMS_ENV_VAR = "CHROME_REMOTE_DESKTOP_HOST_EXTRA_PARAMS"
# This script has a sensible default for the initial and maximum desktop size,
# which can be overridden either on the command-line, or via a comma-separated
# list of sizes in this environment variable.
DEFAULT_SIZES_ENV_VAR = "CHROME_REMOTE_DESKTOP_DEFAULT_DESKTOP_SIZES"
# By default, this script launches Xorg as the virtual X display, using the
# dummy display driver and void input device, unless Xorg+Dummy is deemed
# unsupported. When this environment variable is set, the script will instead
# launch Xvfb.
USE_XVFB_ENV_VAR = "CHROME_REMOTE_DESKTOP_USE_XVFB"
# The amount of video RAM the dummy driver should claim to have, which limits
# the maximum possible resolution.
# 1048576 KiB = 1 GiB, which is the amount of video RAM needed to have a
# 16384x16384 pixel frame buffer (the maximum size supported by VP8) with 32
# bits per pixel.
XORG_DUMMY_VIDEO_RAM = 1048576 # KiB
# By default, provide a maximum size that is large enough to support clients
# with large or multiple monitors. This is a comma-separated list of
# resolutions that will be made available if the X server supports RANDR. These
# defaults can be overridden in ~/.profile.
DEFAULT_SIZES = "1600x1200,3840x2560"
# Decides number of monitors and their resolution that should be run for the
# wayland session.
WAYLAND_DESKTOP_SIZES_ENV = "CHROME_REMOTE_DESKTOP_WAYLAND_DESKTOP_SIZES"
# Default wayland monitor size if `CHROME_REMOTE_DESKTOP_DEFAULT_DESKTOP_SIZES`
# env variable is not set.
DEFAULT_WAYLAND_DESKTOP_SIZES = "1280x720"
SCRIPT_PATH = os.path.abspath(sys.argv[0])
SCRIPT_DIR = os.path.dirname(SCRIPT_PATH)
if (os.path.basename(sys.argv[0]) == 'linux_me2me_host.py'):
# Needed for swarming/isolate tests.
HOST_BINARY_PATH = os.path.join(SCRIPT_DIR,
"../../../out/Release/remoting_me2me_host")
else:
HOST_BINARY_PATH = os.path.join(SCRIPT_DIR, "chrome-remote-desktop-host")
USER_SESSION_PATH = os.path.join(SCRIPT_DIR, "user-session")
CRASH_UPLOADER_PATH = os.path.join(SCRIPT_DIR, "crash-uploader")
CHROME_REMOTING_GROUP_NAME = "chrome-remote-desktop"
HOME_DIR = os.environ["HOME"]
CONFIG_DIR = os.path.join(HOME_DIR, ".config/chrome-remote-desktop")
SESSION_FILE_PATH = os.path.join(HOME_DIR, ".chrome-remote-desktop-session")
SYSTEM_SESSION_FILE_PATH = "/etc/chrome-remote-desktop-session"
SYSTEM_PRE_SESSION_FILE_PATH = "/etc/chrome-remote-desktop-pre-session"
DEBIAN_XSESSION_PATH = "/etc/X11/Xsession"
X_LOCK_FILE_TEMPLATE = "/tmp/.X%d-lock"
FIRST_X_DISPLAY_NUMBER = 1
# Amount of time to wait between relaunching processes.
SHORT_BACKOFF_TIME = 5
LONG_BACKOFF_TIME = 60
# How long a process must run in order not to be counted against the restart
# thresholds.
MINIMUM_PROCESS_LIFETIME = 60
# Thresholds for switching from fast- to slow-restart and for giving up
# trying to restart entirely.
SHORT_BACKOFF_THRESHOLD = 5
MAX_LAUNCH_FAILURES = SHORT_BACKOFF_THRESHOLD + 10
# Number of seconds to save session output to the log.
SESSION_OUTPUT_TIME_LIMIT_SECONDS = 300
# Number of seconds to save the display server output to the log.
SERVER_OUTPUT_TIME_LIMIT_SECONDS = 300
# Host offline reason if the X server retry count is exceeded.
HOST_OFFLINE_REASON_X_SERVER_RETRIES_EXCEEDED = "X_SERVER_RETRIES_EXCEEDED"
# Host offline reason if the wayland server retry count is exceeded.
HOST_OFFLINE_REASON_WAYLAND_SERVER_RETRIES_EXCEEDED = (
"WAYLAND_SERVER_RETRIES_EXCEEDED")
# Host offline reason if the X session retry count is exceeded.
HOST_OFFLINE_REASON_SESSION_RETRIES_EXCEEDED = "SESSION_RETRIES_EXCEEDED"
# Host offline reason if the host retry count is exceeded. (Note: It may or may
# not be possible to send this, depending on why the host is failing.)
HOST_OFFLINE_REASON_HOST_RETRIES_EXCEEDED = "HOST_RETRIES_EXCEEDED"
# Host offline reason if the crash-uploader retry count is exceeded.
HOST_OFFLINE_REASON_CRASH_UPLOADER_RETRIES_EXCEEDED = (
"CRASH_UPLOADER_RETRIES_EXCEEDED")
# This is the file descriptor used to pass messages to the user_session binary
# during startup. It must be kept in sync with kMessageFd in
# remoting_user_session.cc.
USER_SESSION_MESSAGE_FD = 202
# This is the exit code used to signal to wrapper that it should restart instead
# of exiting. It must be kept in sync with kRelaunchExitCode in
# remoting_user_session.cc and RestartForceExitStatus in
RELAUNCH_EXIT_CODE = 41
# This exit code is returned when a needed binary such as user-session or sg
# cannot be found.
COMMAND_NOT_FOUND_EXIT_CODE = 127
# This exit code is returned when a needed binary exists but cannot be executed.
COMMAND_NOT_EXECUTABLE_EXIT_CODE = 126
# User runtime directory. This is where the wayland socket is created by the
# wayland compositor/server for clients to connect to.
# TODO(rkjnsn): Use xdg.BaseDirectory.get_runtime_dir instead
RUNTIME_DIR_TEMPLATE = "/run/user/%s"
# Binary name for `gnome-session`.
GNOME_SESSION = "gnome-session"
# Binary name for `gnome-session-quit`.
GNOME_SESSION_QUIT = "gnome-session-quit"
# Globals needed by the atexit cleanup() handler.
g_desktop = None
g_host_hash = hashlib.md5(socket.gethostname().encode()).hexdigest()
def gen_xorg_config():
return (
# This causes X to load the default GLX module, even if a proprietary one
# is installed in a different directory.
'Section "Files"\n'
' ModulePath "/usr/lib/xorg/modules"\n'
'EndSection\n'
'\n'
# Suppress device probing, which happens by default.
'Section "ServerFlags"\n'
' Option "AutoAddDevices" "false"\n'
' Option "AutoEnableDevices" "false"\n'
' Option "DontVTSwitch" "true"\n'
' Option "PciForceNone" "true"\n'
'EndSection\n'
'\n'
'Section "InputDevice"\n'
# The host looks for this name to check whether it's running in a virtual
# session
' Identifier "Chrome Remote Desktop Input"\n'
# While the xorg.conf man page specifies that both of these options are
# deprecated synonyms for `Option "Floating" "false"`, it turns out that
# if both aren't specified, the Xorg server will automatically attempt to
# add additional devices.
' Option "CoreKeyboard" "true"\n'
' Option "CorePointer" "true"\n'
# The "void" driver is no longer available since Debian 11, but having an
# InputDevice section with an invalid driver will still prevent the Xorg
# server from using a fallback InputDevice setting. However, "Chrome
# Remote Desktop Input" will not appear in the device list if the driver
# is not available.
' Driver "void"\n'
'EndSection\n'
'\n'
'Section "Device"\n'
' Identifier "Chrome Remote Desktop Videocard"\n'
' Driver "dummy"\n'
' VideoRam {video_ram}\n'
'EndSection\n'
'\n'
'Section "Monitor"\n'
' Identifier "Chrome Remote Desktop Monitor"\n'
'EndSection\n'
'\n'
'Section "Screen"\n'
' Identifier "Chrome Remote Desktop Screen"\n'
' Device "Chrome Remote Desktop Videocard"\n'
' Monitor "Chrome Remote Desktop Monitor"\n'
' DefaultDepth 24\n'
' SubSection "Display"\n'
' Viewport 0 0\n'
' Depth 24\n'
' EndSubSection\n'
'EndSection\n'
'\n'
'Section "ServerLayout"\n'
' Identifier "Chrome Remote Desktop Layout"\n'
' Screen "Chrome Remote Desktop Screen"\n'
' InputDevice "Chrome Remote Desktop Input"\n'
'EndSection\n'.format(
video_ram=XORG_DUMMY_VIDEO_RAM))
def display_manager_is_gdm():
try:
# Open as binary to avoid any encoding errors
with open('/etc/X11/default-display-manager', 'rb') as file:
if file.read().strip() in [b'/usr/sbin/gdm', b'/usr/sbin/gdm3']:
return True
# Fall through to process checking even if the file doesn't contain gdm.
except:
# If we can't read the file, move on to checking the process list.
pass
for process in psutil.process_iter():
if process.name() in ['gdm', 'gdm3']:
return True
return False
def is_supported_platform():
# Always assume that the system is supported if the config directory or
# session file exist.
if (os.path.isdir(CONFIG_DIR) or os.path.isfile(SESSION_FILE_PATH) or
os.path.isfile(SYSTEM_SESSION_FILE_PATH)):
return True
# There's a bug in recent versions of GDM that will prevent a user from
# logging in via GDM when there is already an x11 session running for that
# user (such as the one started by CRD). Since breaking local login is a
# pretty serious issue, we want to disallow host set up through the website.
# Unfortunately, there's no way to return a specific error to the website, so
# we just return False to indicate an unsupported platform. The user can still
# set up the host using the headless setup flow, where we can at least display
# a warning. See https://gitlab.gnome.org/GNOME/gdm/-/issues/580 for details
# of the bug and fix.
if display_manager_is_gdm():
return False;
# The session chooser expects a Debian-style Xsession script.
return os.path.isfile(DEBIAN_XSESSION_PATH);
def is_googler_owned(config):
try:
host_owner = config["host_owner"]
return host_owner.endswith("@google.com")
except KeyError:
return False
def get_pipewire_session_manager():
"""Returns the PipeWire session manager supported on this system (either
"wireplumber" or "pipewire-media-session"), or None if a supported PipeWire
installation is not found."""
if shutil.which("pipewire") is None:
logging.warning("PipeWire not found. Not enabling PipeWire audio support.")
return None
try:
version_output = subprocess.check_output(["pipewire", "--version"],
universal_newlines=True)
except subprocess.CalledProcessError as e:
logging.warning("Failed to execute pipewire. Not enabling PipeWire audio"
+ " support: " + str(e))
return None
match = re.search(r"pipewire (\S+)$", version_output, re.MULTILINE)
if not match:
logging.warning("Failed to determine pipewire version. Not enabling"
+ " PipeWire audio support.")
return None
try:
pipewire_version = version.parse(match[1])
except version.InvalidVersion as e:
logging.warning("Failed to parse pipewire version. Not enabling PipeWire"
+ " audio support: " + str(e))
return None
if pipewire_version < version.parse("0.3.53"):
logging.warning("Installed pipewire version is too old. Not enabling"
+ " PipeWire audio support.")
return None
session_manager = None
for binary in ["wireplumber", "pipewire-media-session"]:
if shutil.which(binary) is not None:
session_manager = binary
break
if session_manager is None:
logging.warning("No session manager found. Not enabling PipeWire audio"
+ " support.")
return None
return session_manager
def terminate_process(pid, name):
"""Terminates the process with the given |pid|. Initially sends SIGTERM, but
falls back to SIGKILL if the process fails to exit after 10 seconds. |name|
is used for logging. Throws psutil.NoSuchProcess if the pid doesn't exist."""
logging.info("Sending SIGTERM to %s proc (pid=%s)",
name, pid)
try:
psutil_proc = psutil.Process(pid)
psutil_proc.terminate()
# Use a short timeout, to avoid delaying service shutdown if the
# process refuses to die for some reason.
psutil_proc.wait(timeout=10)
except psutil.TimeoutExpired:
logging.error("Timed out - sending SIGKILL")
psutil_proc.kill()
except psutil.Error:
logging.error("Error terminating process")
def terminate_command_if_running(command_line):
"""Terminate any processes that match |command_line| (including all arguments)
exactly. Note: this does not attempt to resolve the actual path to the
executable. As such, arg0 much match exactly."""
uid = os.getuid()
this_pid = os.getpid()
# This function should return the process with the --child-process flag if it
# exists. If there's only a process without, it might be a legacy process.
non_child_process = None
# Support new & old psutil API. This is the right way to check, according to
# http://grodola.blogspot.com/2014/01/psutil-20-porting.html
if psutil.version_info >= (2, 0):
psget = lambda x: x()
else:
psget = lambda x: x
for process in psutil.process_iter():
# Skip any processes that raise an exception, as processes may terminate
# during iteration over the list.
try:
# Skip other users' processes.
if psget(process.uids).real != uid:
continue
# Skip the current process.
if process.pid == this_pid:
continue
# |cmdline| will be [python-interpreter, script-file, other arguments...]
if psget(process.cmdline) == command_line:
terminate_process(process.pid, command_line[0]);
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
class Config:
def __init__(self, path):
self.path = path
self.data = {}
self.changed = False
def load(self):
"""Loads the config from file.
Raises:
IOError: Error reading data
ValueError: Error parsing JSON
"""
settings_file = open(self.path, 'r')
self.data = json.load(settings_file)
self.changed = False
settings_file.close()
def save(self):
"""Saves the config to file.
Raises:
IOError: Error writing data
TypeError: Error serialising JSON
"""
if not self.changed:
return
old_umask = os.umask(0o066)
try:
settings_file = open(self.path, 'w')
settings_file.write(json.dumps(self.data, indent=2))
settings_file.close()
self.changed = False
finally:
os.umask(old_umask)
def save_and_log_errors(self):
"""Calls self.save(), trapping and logging any errors."""
try:
self.save()
except (IOError, TypeError) as e:
logging.error("Failed to save config: " + str(e))
def get(self, key):
return self.data.get(key)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.changed = True
def clear(self):
self.data = {}
self.changed = True
class Authentication:
"""Manage authentication tokens for Chromoting/xmpp"""
def __init__(self):
# Note: Initial values are never used.
self.login = None
self.oauth_refresh_token = None
def copy_from(self, config):
"""Loads the config and returns false if the config is invalid."""
try:
self.login = config["xmpp_login"]
self.oauth_refresh_token = config["oauth_refresh_token"]
except KeyError:
return False
return True
def copy_to(self, config):
config["xmpp_login"] = self.login
config["oauth_refresh_token"] = self.oauth_refresh_token
class Host:
"""This manages the configuration for a host."""
def __init__(self):
# Note: Initial values are never used.
self.host_id = None
self.host_name = None
self.host_secret_hash = None
self.private_key = None
def copy_from(self, config):
try:
self.host_id = config.get("host_id")
self.host_name = config["host_name"]
self.host_secret_hash = config.get("host_secret_hash")
self.private_key = config["private_key"]
except KeyError:
return False
return bool(self.host_id)
def copy_to(self, config):
if self.host_id:
config["host_id"] = self.host_id
config["host_name"] = self.host_name
config["host_secret_hash"] = self.host_secret_hash
config["private_key"] = self.private_key
class SessionOutputFilterThread(threading.Thread):
"""Reads session log from a pipe and logs the output with the provided prefix
for amount of time defined by time_limit, or indefinitely if time_limit is
None."""
def __init__(self, stream, prefix, time_limit):
threading.Thread.__init__(self)
self.stream = stream
self.daemon = True
self.prefix = prefix
self.time_limit = time_limit
def run(self):
started_time = time.time()
is_logging = True
while True:
try:
line = self.stream.readline();
except IOError as e:
print("IOError when reading session output: ", e)
return
if line == b"":
# EOF reached. Just stop the thread.
return
if not is_logging:
continue
if self.time_limit and time.time() - started_time >= self.time_limit:
is_logging = False
print("Suppressing rest of the session output.", flush=True)
else:
# Pass stream bytes through as is instead of decoding and encoding.
sys.stdout.buffer.write(self.prefix.encode(sys.stdout.encoding) + line);
sys.stdout.flush()
class Desktop(abc.ABC):
"""Manage a single virtual desktop"""
def __init__(self, sizes, server_inhibitor=None, pipewire_inhibitor=None,
session_inhibitor=None, host_inhibitor=None):
self.sizes = sizes
self.server_proc = None
self.pipewire_proc = None
self.pipewire_pulse_proc = None
self.pipewire_session_manager = None
self.pipewire_session_manager_proc = None
self.pre_session_proc = None
self.session_proc = None
self.host_proc = None
self.child_env = None
self.host_ready = False
self.server_inhibitor = server_inhibitor
self.pipewire_inhibitor = pipewire_inhibitor
self.session_inhibitor = session_inhibitor
self.host_inhibitor = host_inhibitor
self._init_child_env();
if self.server_inhibitor is None:
self.server_inhibitor = RelaunchInhibitor("Display server")
if self.pipewire_inhibitor is None:
self.pipewire_inhibitor = RelaunchInhibitor("PipeWire")
if self.session_inhibitor is None:
self.session_inhibitor = RelaunchInhibitor("session")
if self.host_inhibitor is None:
self.host_inhibitor = RelaunchInhibitor("host")
# Map of inhibitors to the corresponding host offline reason should that
# session component fail. None indicates that the session component isn't
# mandatory and its failure should not result in the host shutting down.
self.inhibitors = {
self.server_inhibitor: HOST_OFFLINE_REASON_X_SERVER_RETRIES_EXCEEDED,
self.pipewire_inhibitor: None,
self.session_inhibitor: HOST_OFFLINE_REASON_SESSION_RETRIES_EXCEEDED,
self.host_inhibitor: HOST_OFFLINE_REASON_HOST_RETRIES_EXCEEDED
}
# Crash reporting is disabled by default.
self.crash_reporting_enabled = False
self.crash_uploader_proc = None
self.crash_uploader_inhibitor = None
def _init_child_env(self):
self.child_env = dict(os.environ)
self.child_env["CHROME_REMOTE_DESKTOP_SESSION"] = "1"
# We used to create a separate profile/chrome config home for the virtual
# session since the virtual session was independent of the local session in
# curtain mode, and using the same Chrome profile between sessions would
# lead to cross talk issues. This is no longer the case given modern desktop
# environments don't support running two graphical sessions simultaneously.
# Therefore, we don't set the env var unless the directory already exists.
#
# M61 introduced CHROME_CONFIG_HOME, which allows specifying a different
# config base path while still using different user data directories for
# different channels (Stable, Beta, Dev). For existing users who only have
# chrome-profile, continue using CHROME_USER_DATA_DIR so they don't have to
# set up their profile again.
chrome_profile = os.path.join(CONFIG_DIR, "chrome-profile")
chrome_config_home = os.path.join(CONFIG_DIR, "chrome-config")
if (os.path.exists(chrome_profile)
and not os.path.exists(chrome_config_home)):
self.child_env["CHROME_USER_DATA_DIR"] = chrome_profile
elif os.path.exists(chrome_config_home):
self.child_env["CHROME_CONFIG_HOME"] = chrome_config_home
# Ensure that the software-rendering GL drivers are loaded by the desktop
# session, instead of any hardware GL drivers installed on the system.
library_path = (
"/usr/lib/mesa-diverted/%(arch)s-linux-gnu:"
"/usr/lib/%(arch)s-linux-gnu/mesa:"
"/usr/lib/%(arch)s-linux-gnu/dri:"
"/usr/lib/%(arch)s-linux-gnu/gallium-pipe" %
{ "arch": platform.machine() })
if "LD_LIBRARY_PATH" in self.child_env:
library_path += ":" + self.child_env["LD_LIBRARY_PATH"]
self.child_env["LD_LIBRARY_PATH"] = library_path
def _setup_gnubby(self):
self.ssh_auth_sockname = ("/tmp/chromoting.%s.ssh_auth_sock" %
os.environ["USER"])
self.child_env["SSH_AUTH_SOCK"] = self.ssh_auth_sockname
def _launch_pipewire(self, instance_name, runtime_path, sink_name):
self.pipewire_session_manager = get_pipewire_session_manager()
if self.pipewire_session_manager is None:
return False
try:
for config_file in ["pipewire.conf", "pipewire-pulse.conf",
self.pipewire_session_manager + ".conf"]:
with open(os.path.join(SCRIPT_DIR, config_file + ".template"),
"r") as infile, \
open(os.path.join(runtime_path, config_file), "w") as outfile:
template = string.Template(infile.read())
outfile.write(template.substitute({
"instance_name": instance_name,
"runtime_path": runtime_path,
"sink_name": sink_name}))
logging.info("Launching pipewire")
pipewire_cmd = ["pipewire", "-c",
os.path.join(runtime_path, "pipewire.conf")]
# PulseAudio protocol support is built into PipeWire for the versions we
# support. Invoking the pipewire binary directly instead of via the
# pipewire-pulse symlink allows this to work even if the pipewire-pulse
# package is not installed (e.g., if the user is still using PulseAudio
# for local sessions).
pipewire_pulse_cmd = ["pipewire", "-c",
os.path.join(runtime_path, "pipewire-pulse.conf")]
session_manager_cmd = [
self.pipewire_session_manager, "-c",
os.path.join(runtime_path, self.pipewire_session_manager + ".conf")]
# Terminate any stale processes before relaunching.
for command in [pipewire_cmd, pipewire_pulse_cmd, session_manager_cmd]:
terminate_command_if_running(command)
self.pipewire_proc = subprocess.Popen(pipewire_cmd, env=self.child_env)
self.pipewire_pulse_proc = subprocess.Popen(pipewire_pulse_cmd,
env=self.child_env)
# MEDIA_SESSION_CONFIG_DIR is needed to use an absolute path with
# pipewire-media-session.
self.pipewire_session_manager_proc = subprocess.Popen(session_manager_cmd,
env={**self.child_env, "MEDIA_SESSION_CONFIG_DIR": "/"})
# Directs native PipeWire clients to the correct instance
self.child_env["PIPEWIRE_REMOTE"] = instance_name
return True
except (IOError, OSError) as e:
logging.error("Failed to start PipeWire: " + str(e))
# Clean up any processes that did start
for proc, name in [(self.pipewire_proc, "pipewire"),
(self.pipewire_pulse_proc, "pipewire-pulse"),
(self.pipewire_session_manager_proc,
self.pipewire_session_manager)]:
if proc is not None:
terminate_process(proc.pid, name)
self.pipewire_proc = None
self.pipewire_pulse_proc = None
self.pipewire_session_manager_proc = None
return False
def _launch_pre_session(self):
# Launch the pre-session script, if it exists. Returns true if the script
# was launched, false if it didn't exist.
if os.path.exists(SYSTEM_PRE_SESSION_FILE_PATH):
pre_session_command = bash_invocation_for_script(
SYSTEM_PRE_SESSION_FILE_PATH)
logging.info("Launching pre-session: %s" % pre_session_command)
self.pre_session_proc = subprocess.Popen(pre_session_command,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=HOME_DIR,
env=self.child_env)
if not self.pre_session_proc.pid:
raise Exception("Could not start pre-session")
output_filter_thread = SessionOutputFilterThread(
self.pre_session_proc.stdout, "Pre-session output: ", None)
output_filter_thread.start()
return True
return False
def launch_session(self, server_args, backoff_time):
"""Launches process required for session and records the backoff time
for inhibitors so that process restarts are not attempted again until
that time has passed."""
logging.info("Setting up and launching session")
self._setup_gnubby()
display = self.get_unused_display_number()
self.child_env["DISPLAY"] = ":%d" % display
self.server_inhibitor.record_started(MINIMUM_PROCESS_LIFETIME,
backoff_time)
self.session_inhibitor.record_started(MINIMUM_PROCESS_LIFETIME,
backoff_time)
def _wait_for_setup_before_host_launch(self):
"""
If a virtual desktop needs to do some setup before launching the host
process, it can override this method and ensure that the required setup is
done before returning from this process.
"""
pass
def launch_host(self, host_config, extra_start_host_args, backoff_time):
self._wait_for_setup_before_host_launch()
logging.info("Launching host process")
# Start remoting host
args = [HOST_BINARY_PATH, "--host-config=-"]
if self.audio_pipe:
args.append("--audio-pipe-name=%s" % self.audio_pipe)
if self.ssh_auth_sockname:
args.append("--ssh-auth-sockname=%s" % self.ssh_auth_sockname)
args.extend(extra_start_host_args)
# Have the host process use SIGUSR1 to signal a successful start.
def sigusr1_handler(signum, frame):
_ = signum, frame
logging.info("Host ready to receive connections.")
self.host_ready = True
ParentProcessLogger.release_parent_if_connected(True)
signal.signal(signal.SIGUSR1, sigusr1_handler)
args.append("--signal-parent")
logging.info(args)
self.host_proc = subprocess.Popen(args, env=self.child_env,
stdin=subprocess.PIPE)
if not self.host_proc.pid:
raise Exception("Could not start Chrome Remote Desktop host")
try:
self.host_proc.stdin.write(json.dumps(host_config.data).encode('UTF-8'))
self.host_proc.stdin.flush()
except IOError as e:
# This can occur in rare situations, for example, if the machine is
# heavily loaded and the host process dies quickly (maybe if the X
# connection failed), the host process might be gone before this code
# writes to the host's stdin. Catch and log the exception, allowing
# the process to be retried instead of exiting the script completely.
logging.error("Failed writing to host's stdin: " + str(e))
finally:
self.host_proc.stdin.close()
self.host_inhibitor.record_started(MINIMUM_PROCESS_LIFETIME, backoff_time)
def enable_crash_reporting(self):
logging.info("Configuring crash reporting")
self.crash_reporting_enabled = True
self.crash_uploader_inhibitor = RelaunchInhibitor("Crash uploader")
self.inhibitors[self.crash_uploader_inhibitor] = (
HOST_OFFLINE_REASON_CRASH_UPLOADER_RETRIES_EXCEEDED
)
def launch_crash_uploader(self, backoff_time):
if not self.crash_reporting_enabled:
return
logging.info("Launching crash uploader")
args = [CRASH_UPLOADER_PATH]
self.crash_uploader_proc = subprocess.Popen(args, env=self.child_env)
if not self.crash_uploader_proc.pid:
raise Exception("Could not start crash-uploader")
self.crash_uploader_inhibitor.record_started(MINIMUM_PROCESS_LIFETIME,
backoff_time)
def cleanup(self):
"""Send SIGTERM to all procs and wait for them to exit. Will fallback to
SIGKILL if a process doesn't exit within 10 seconds.
"""
for proc, name in [(self.host_proc, "host"),
(self.crash_uploader_proc, "crash-uploader"),
(self.session_proc, "session"),
(self.pre_session_proc, "pre-session"),
(self.pipewire_proc, "pipewire"),
(self.pipewire_pulse_proc, "pipewire-pulse"),
(self.pipewire_session_manager_proc,
self.pipewire_session_manager),
(self.server_proc, "display server")]:
if proc is not None:
terminate_process(proc.pid, name)
self.server_proc = None
self.pipewire_proc = None
self.pipewire_pulse_proc = None
self.pipewire_session_manager_proc = None
self.pre_session_proc = None
self.session_proc = None
self.host_proc = None
self.crash_uploader_proc = None
def report_offline_reason(self, host_config, reason):
"""Attempt to report the specified offline reason to the registry. This
is best effort, and requires a valid host config.
"""
logging.info("Attempting to report offline reason: " + reason)
args = [HOST_BINARY_PATH, "--host-config=-",
"--report-offline-reason=" + reason]
proc = subprocess.Popen(args, env=self.child_env, stdin=subprocess.PIPE)
proc.communicate(json.dumps(host_config.data).encode('UTF-8'))
def on_process_exit(self, pid, status):
"""Checks for which process has exited and whether or not the exit was
expected. Returns a boolean indicating whether or not tear down of the
processes is needed."""
tear_down = False
pipewire_process = False
if self.server_proc is not None and pid == self.server_proc.pid:
logging.info("Display server process terminated")
self.server_proc = None
self.server_inhibitor.record_stopped(expected=False)
tear_down = True
if (self.pre_session_proc is not None and
pid == self.pre_session_proc.pid):
self.pre_session_proc = None
if status == 0:
logging.info("Pre-session terminated successfully. Starting session.")
self.launch_desktop_session()
else:
logging.info("Pre-session failed. Tearing down.")
# The pre-session may have exited on its own or been brought down by
# the display server dying. Check if the display server is still running
# so we know whom to penalize.
if self.check_server_responding():
# Pre-session and session use the same inhibitor.
self.session_inhibitor.record_stopped(expected=False)
else:
self.server_inhibitor.record_stopped(expected=False)
# Either way, we want to tear down the session.
tear_down = True
if self.pipewire_proc is not None and pid == self.pipewire_proc.pid:
logging.info("PipeWire process terminated")
self.pipewire_proc = None
pipewire_process = True
if (self.pipewire_pulse_proc is not None
and pid == self.pipewire_pulse_proc.pid):
logging.info("PipeWire-Pulse process terminated")
self.pipewire_pulse_proc = None
pipewire_process = True
if (self.pipewire_session_manager_proc is not None
and pid == self.pipewire_session_manager_proc.pid):
logging.info(self.pipewire_session_manager + " process terminated")
self.pipewire_session_manager_proc = None
pipewire_process = True
if pipewire_process:
self.pipewire_inhibitor.record_stopped(expected=False)
# Terminate other PipeWire-related processes to start fresh.
for proc, name in [(self.pipewire_proc, "pipewire"),
(self.pipewire_pulse_proc, "pipewire-pulse"),
(self.pipewire_session_manager_proc,
self.pipewire_session_manager)]:
if proc is not None:
terminate_process(proc.pid, name)
self.pipewire_proc = None
self.pipewire_pulse_proc = None
self.pipewire_session_manager_proc = None
if self.session_proc is not None and pid == self.session_proc.pid:
logging.info("Session process terminated")
self.session_proc = None
# The session may have exited on its own or been brought down by the
# display server dying. Check if the display server is still running so we
# know whom to penalize.
if self.check_server_responding():
self.session_inhibitor.record_stopped(expected=False)
else:
self.server_inhibitor.record_stopped(expected=False)
# Either way, we want to tear down the session.
tear_down = True
if self.host_proc is not None and pid == self.host_proc.pid:
logging.info("Host process terminated")
self.host_proc = None
self.host_ready = False
# These exit-codes must match the ones used by the host.
# See remoting/host/base/host_exit_codes.h.
# Delete the host or auth configuration depending on the returned error
# code, so the next time this script is run, a new configuration
# will be created and registered.
if os.WIFEXITED(status):
if os.WEXITSTATUS(status) == 100:
logging.info("Host configuration is invalid - exiting.")
return 0
elif os.WEXITSTATUS(status) == 101:
logging.info("Host ID has been deleted - exiting.")
host_config.clear()
host_config.save_and_log_errors()
return 0
elif os.WEXITSTATUS(status) == 102:
logging.info("OAuth credentials are invalid - exiting.")
return 0
elif os.WEXITSTATUS(status) == 103:
logging.info("Host domain is blocked by policy - exiting.")
return 0
# Nothing to do for Mac-only status 104 (login screen unsupported)
elif os.WEXITSTATUS(status) == 105:
logging.info("Username is blocked by policy - exiting.")
return 0
elif os.WEXITSTATUS(status) == 106:
logging.info("Host has been deleted - exiting.")
return 0
elif os.WEXITSTATUS(status) == 107:
logging.info("Remote access is disallowed by policy - exiting.")
return 0
elif os.WEXITSTATUS(status) == 108:
logging.info("This CPU is not supported - exiting.")
return 0
else:
logging.info("Host exited with status %s." % os.WEXITSTATUS(status))
elif os.WIFSIGNALED(status):
logging.info("Host terminated by signal %s." % os.WTERMSIG(status))
# The host may have exited on it's own or been brought down by the display
# server dying. Check if the display server is still running so we know
# whom to penalize.
if self.check_server_responding():
self.host_inhibitor.record_stopped(expected=False)
else:
self.server_inhibitor.record_stopped(expected=False)
# Only tear down if the display server isn't responding.
tear_down = True
if (self.crash_uploader_proc is not None and
pid == self.crash_uploader_proc.pid):
logging.info("Crash uploader process terminated")
self.crash_uploader_proc = None
self.crash_uploader_inhibitor.record_stopped(expected=False)
# Don't tear down the host if the uploader is killed or crashes.
tear_down = False
return tear_down
def aggregate_failure_count(self):
failure_count = 0
for inhibitor, offline_reason in self.inhibitors.items():
if inhibitor.running:
inhibitor.record_stopped(True)
# Only count mandatory processes
if offline_reason is not None:
failure_count += inhibitor.failures
return failure_count
def setup_audio(self, host_id, backoff_time):
"""Launches a CRD-specific instance of PipeWire for audio forwarding within
the session and sets up the restart inhibitor for it, if supported on this
system. Otherwise, falls back to writing a legacy PulseAudio
configuration."""
self.audio_pipe = None