-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathchrome-remote-desktop-setup.sh
1840 lines (1569 loc) · 69 KB
/
chrome-remote-desktop-setup.sh
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
#!/bin/bash
wget https://dl.google.com/linux/direct/chrome-remote-desktop_current_amd64.deb
sudo dpkg -i chrome-remote-desktop_current_amd64.deb
sudo apt-get install -f -y
rm chrome-remote-desktop_current_amd64.deb
cat <<EOF > ~/.chrome-remote-desktop-session
exec /etc/X11/Xsession 'env GNOME_SHELL_SESSION_MODE=ubuntu /usr/bin/gnome-session --systemd --session=ubuntu'
EOF
sudo usermod -a -G chrome-remote-desktop $USER
sudo systemctl disable chrome-remote-desktop
mkdir -p ~/.config/chrome-remote-desktop
cat <<EOF > ~/.config/autostart/chrome-remote-desktop.desktop
[Desktop Entry]
Type=Application
Exec=/opt/google/chrome-remote-desktop/chrome-remote-desktop --start
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[en_US]=Chrome Remote Desktop
Name=Chrome Remote Desktop
Comment[en_US]=Autostart Chrome Remote Desktop After Login to prevent service from preventing login
Comment=Autostart Chrome Remote Desktop After Login to prevent service from preventing login
EOF
sudo cat <<EOF > /opt/google/chrome-remote-desktop/chrome-remote-desktop
#!/usr/bin/python3
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# 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] < 3:
print("This script requires Python version 3.3")
sys.exit(1)
import argparse
import atexit
import errno
import fcntl
import getpass
import grp
import hashlib
import json
import logging
import os
import pipes
import platform
import psutil
import pwd
import re
import signal
import socket
import subprocess
import syslog
import tempfile
import threading
import time
import uuid
# 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 Xvfb as the virtual X display. When this
# environment variable is set, the script will instead launch an instance of
# Xorg using the dummy display driver and void input device. In order for this
# to work, both the dummy display driver and void input device need to be
# installed:
#
# sudo apt-get install xserver-xorg-video-dummy
# sudo apt-get install xserver-xorg-input-void
#
# TODO(rkjnsn): Add xserver-xorg-video-dummy and xserver-xorg-input-void as
# package dependencies at the same time we switch the default to Xorg
USE_XORG_ENV_VAR = "CHROME_REMOTE_DESKTOP_USE_XORG"
# 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"
# Xorg's dummy driver only supports switching between preconfigured sizes. To
# make resize-to-fit somewhat useful, include several common resolutions by
# default.
DEFAULT_SIZES_XORG = ("1600x1200,1600x900,1440x900,1366x768,1360x768,1280x1024,"
"1280x800,1280x768,1280x720,1152x864,1024x768,1024x600,"
"800x600,1680x1050,1920x1080,1920x1200,2560x1440,"
"2560x1600,3840x2160,3840x2560")
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")
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"
DEBIAN_XSESSION_PATH = "/etc/X11/Xsession"
X_LOCK_FILE_TEMPLATE = "/tmp/.X%d-lock"
FIRST_X_DISPLAY_NUMBER = 20
# 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
# 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 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"
# 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.
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
# Globals needed by the atexit cleanup() handler.
g_desktop = None
g_host_hash = hashlib.md5(socket.gethostname().encode()).hexdigest()
def gen_xorg_config(sizes):
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'
' 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'
# The horizontal sync rate was calculated from the vertical refresh rate
# and the modline template:
# (33000 (vert total) * 0.1 Hz = 3.3 kHz)
' HorizSync 3.3\n' # kHz
# The vertical refresh rate was chosen both to be low enough to have an
# acceptable dot clock at high resolutions, and then bumped down a little
# more so that in the unlikely event that a low refresh rate would break
# something, it would break obviously.
' VertRefresh 0.1\n' # Hz
'{modelines}'
'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'
' Modes {modes}\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(
# This Modeline template allows resolutions up to the dummy driver's
# max supported resolution of 32767x32767 without additional
# calculation while meeting the driver's dot clock requirements. Note
# that VP8 (and thus the amount of video RAM chosen) only support a
# maximum resolution of 16384x16384.
# 32767x32767 should be possible if we switch fully to VP9 and
# increase the video RAM to 4GiB.
# The dot clock was calculated to match the VirtRefresh chosen above.
# (33000 * 33000 * 0.1 Hz = 108.9 MHz)
# Changes this line require matching changes to HorizSync and
# VertRefresh.
modelines="".join(
' Modeline "{0}x{1}" 108.9 {0} 32998 32999 33000 '
'{1} 32998 32999 33000\n'.format(w, h) for w, h in sizes),
modes=" ".join('"{0}x{1}"'.format(w, h) for w, h in sizes),
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);
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 for amount of time
defined by SESSION_OUTPUT_TIME_LIMIT_SECONDS."""
def __init__(self, stream):
threading.Thread.__init__(self)
self.stream = stream
self.daemon = True
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 time.time() - started_time >= SESSION_OUTPUT_TIME_LIMIT_SECONDS:
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(
"Session output: ".encode(sys.stdout.encoding) + line);
sys.stdout.flush()
class Desktop:
"""Manage a single virtual desktop"""
def __init__(self, sizes):
self.x_proc = None
self.session_proc = None
self.host_proc = None
self.child_env = None
self.sizes = sizes
self.xorg_conf = None
self.pulseaudio_pipe = None
self.server_supports_exact_resize = False
self.server_supports_randr = False
self.randr_add_sizes = False
self.host_ready = False
self.ssh_auth_sockname = None
global g_desktop
assert(g_desktop is None)
g_desktop = self
@staticmethod
def get_unused_display_number():
"""Return a candidate display number for which there is currently no
X Server lock file"""
display = FIRST_X_DISPLAY_NUMBER
while os.path.exists(X_LOCK_FILE_TEMPLATE % display):
display += 1
return display
def _init_child_env(self):
self.child_env = dict(os.environ)
# Force GDK to use the X11 backend, as otherwise parts of the host that use
# GTK can end up connecting to an active Wayland display instead of the
# CRD X11 session.
self.child_env["GDK_BACKEND"] = "x11"
# 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_pulseaudio(self):
self.pulseaudio_pipe = None
# pulseaudio uses UNIX sockets for communication. Length of UNIX socket
# name is limited to 108 characters, so audio will not work properly if
# the path is too long. To workaround this problem we use only first 10
# symbols of the host hash.
pulse_path = os.path.join(CONFIG_DIR,
"pulseaudio#%s" % g_host_hash[0:10])
if len(pulse_path) + len("/native") >= 108:
logging.error("Audio will not be enabled because pulseaudio UNIX " +
"socket path is too long.")
return False
sink_name = "chrome_remote_desktop_session"
pipe_name = os.path.join(pulse_path, "fifo_output")
try:
if not os.path.exists(pulse_path):
os.mkdir(pulse_path)
except IOError as e:
logging.error("Failed to create pulseaudio pipe: " + str(e))
return False
try:
pulse_config = open(os.path.join(pulse_path, "daemon.conf"), "w")
pulse_config.write("default-sample-format = s16le\n")
pulse_config.write("default-sample-rate = 48000\n")
pulse_config.write("default-sample-channels = 2\n")
pulse_config.close()
pulse_script = open(os.path.join(pulse_path, "default.pa"), "w")
pulse_script.write("load-module module-native-protocol-unix\n")
pulse_script.write(
("load-module module-pipe-sink sink_name=%s file=\"%s\" " +
"rate=48000 channels=2 format=s16le\n") %
(sink_name, pipe_name))
pulse_script.close()
except IOError as e:
logging.error("Failed to write pulseaudio config: " + str(e))
return False
self.child_env["PULSE_CONFIG_PATH"] = pulse_path
self.child_env["PULSE_RUNTIME_PATH"] = pulse_path
self.child_env["PULSE_STATE_PATH"] = pulse_path
self.child_env["PULSE_SINK"] = sink_name
self.pulseaudio_pipe = pipe_name
return True
def _setup_gnubby(self):
self.ssh_auth_sockname = ("/tmp/chromoting.%s.ssh_auth_sock" %
os.environ["USER"])
# Returns child environment not containing TMPDIR.
# Certain values of TMPDIR can break the X server (crbug.com/672684), so we
# want to make sure it isn't set in the envirionment we use to start the
# server.
def _x_env(self):
if "TMPDIR" not in self.child_env:
return self.child_env
else:
env_copy = dict(self.child_env)
del env_copy["TMPDIR"]
return env_copy
def check_x_responding(self):
"""Checks if the X server is responding to connections."""
with open(os.devnull, "r+") as devnull:
exit_code = subprocess.call("xdpyinfo", env=self.child_env,
stdout=devnull)
return exit_code == 0
def _wait_for_x(self):
# Wait for X to be active.
for _test in range(20):
if self.check_x_responding():
logging.info("X server is active.")
return
time.sleep(0.5)
raise Exception("Could not connect to X server.")
def _launch_xvfb(self, display, x_auth_file, extra_x_args):
max_width = max([width for width, height in self.sizes])
max_height = max([height for width, height in self.sizes])
logging.info("Starting Xvfb on display :%d" % display)
screen_option = "%dx%dx24" % (max_width, max_height)
self.x_proc = subprocess.Popen(
["Xvfb", ":%d" % display,
"-auth", x_auth_file,
"-nolisten", "tcp",
"-noreset",
"-screen", "0", screen_option
] + extra_x_args, env=self._x_env())
if not self.x_proc.pid:
raise Exception("Could not start Xvfb.")
self._wait_for_x()
with open(os.devnull, "r+") as devnull:
exit_code = subprocess.call("xrandr", env=self.child_env,
stdout=devnull, stderr=devnull)
if exit_code == 0:
# RandR is supported
self.server_supports_exact_resize = True
self.server_supports_randr = True
self.randr_add_sizes = True
def _launch_xorg(self, display, x_auth_file, extra_x_args):
with tempfile.NamedTemporaryFile(
prefix="chrome_remote_desktop_",
suffix=".conf", delete=False) as config_file:
config_file.write(gen_xorg_config(self.sizes).encode())
# We can't support exact resize with the current Xorg dummy driver.
self.server_supports_exact_resize = False
# But dummy does support RandR 1.0.
self.server_supports_randr = True
self.xorg_conf = config_file.name
logging.info("Starting Xorg on display :%d" % display)
# We use the child environment so the Xorg server picks up the Mesa libGL
# instead of any proprietary versions that may be installed, thanks to
# LD_LIBRARY_PATH.
# Note: This prevents any environment variable the user has set from
# affecting the Xorg server.
self.x_proc = subprocess.Popen(
["Xorg", ":%d" % display,
"-auth", x_auth_file,
"-nolisten", "tcp",
"-noreset",
# Disable logging to a file and instead bump up the stderr verbosity
# so the equivalent information gets logged in our main log file.
"-logfile", "/dev/null",
"-verbose", "3",
"-config", config_file.name
] + extra_x_args, env=self._x_env())
if not self.x_proc.pid:
raise Exception("Could not start Xorg.")
self._wait_for_x()
def _launch_x_server(self, extra_x_args):
x_auth_file = os.path.expanduser("~/.Xauthority")
self.child_env["XAUTHORITY"] = x_auth_file
display = self.get_unused_display_number()
# Run "xauth add" with |child_env| so that it modifies the same XAUTHORITY
# file which will be used for the X session.
exit_code = subprocess.call("xauth add :%d . `mcookie`" % display,
env=self.child_env, shell=True)
if exit_code != 0:
raise Exception("xauth failed with code %d" % exit_code)
# Disable the Composite extension iff the X session is the default
# Unity-2D, since it uses Metacity which fails to generate DAMAGE
# notifications correctly. See crbug.com/166468.
x_session = choose_x_session()
if (len(x_session) == 2 and
x_session[1] == "/usr/bin/gnome-session --session=ubuntu-2d"):
extra_x_args.extend(["-extension", "Composite"])
self.child_env["DISPLAY"] = ":%d" % display
self.child_env["CHROME_REMOTE_DESKTOP_SESSION"] = "1"
# Use a separate profile for any instances of Chrome that are started in
# the virtual session. Chrome doesn't support sharing a profile between
# multiple DISPLAYs, but Chrome Sync allows for a reasonable compromise.
#
# 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
else:
self.child_env["CHROME_CONFIG_HOME"] = chrome_config_home
# Set SSH_AUTH_SOCK to the file name to listen on.
if self.ssh_auth_sockname:
self.child_env["SSH_AUTH_SOCK"] = self.ssh_auth_sockname
if USE_XORG_ENV_VAR in os.environ:
self._launch_xorg(display, x_auth_file, extra_x_args)
else:
self._launch_xvfb(display, x_auth_file, extra_x_args)
# The remoting host expects the server to use "evdev" keycodes, but Xvfb
# starts configured to use the "base" ruleset, resulting in XKB configuring
# for "xfree86" keycodes, and screwing up some keys. See crbug.com/119013.
# Reconfigure the X server to use "evdev" keymap rules. The X server must
# be started with -noreset otherwise it'll reset as soon as the command
# completes, since there are no other X clients running yet.
exit_code = subprocess.call(["setxkbmap", "-rules", "evdev"],
env=self.child_env)
if exit_code != 0:
logging.error("Failed to set XKB to 'evdev'")
if not self.server_supports_randr:
return
with open(os.devnull, "r+") as devnull:
# Register the screen sizes with RandR, if needed. Errors here are
# non-fatal; the X server will continue to run with the dimensions from
# the "-screen" option.
if self.randr_add_sizes:
for width, height in self.sizes:
label = "%dx%d" % (width, height)
args = ["xrandr", "--newmode", label, "0", str(width), "0", "0", "0",
str(height), "0", "0", "0"]
subprocess.call(args, env=self.child_env, stdout=devnull,
stderr=devnull)
args = ["xrandr", "--addmode", "screen", label]
subprocess.call(args, env=self.child_env, stdout=devnull,
stderr=devnull)
# Set the initial mode to the first size specified, otherwise the X server
# would default to (max_width, max_height), which might not even be in the
# list.
initial_size = self.sizes[0]
label = "%dx%d" % initial_size
args = ["xrandr", "-s", label]
subprocess.call(args, env=self.child_env, stdout=devnull, stderr=devnull)
# Set the physical size of the display so that the initial mode is running
# at approximately 96 DPI, since some desktops require the DPI to be set
# to something realistic.
args = ["xrandr", "--dpi", "96"]
subprocess.call(args, env=self.child_env, stdout=devnull, stderr=devnull)
# Monitor for any automatic resolution changes from the desktop
# environment.
args = [SCRIPT_PATH, "--watch-resolution", str(initial_size[0]),
str(initial_size[1])]
# It is not necessary to wait() on the process here, as this script's main
# loop will reap the exit-codes of all child processes.
subprocess.Popen(args, env=self.child_env, stdout=devnull, stderr=devnull)
def _launch_x_session(self):
# Start desktop session.
# The /dev/null input redirection is necessary to prevent the X session
# reading from stdin. If this code runs as a shell background job in a
# terminal, any reading from stdin causes the job to be suspended.
# Daemonization would solve this problem by separating the process from the
# controlling terminal.
xsession_command = choose_x_session()
if xsession_command is None:
raise Exception("Unable to choose suitable X session command.")
logging.info("Launching X session: %s" % xsession_command)
self.session_proc = subprocess.Popen(xsession_command,
stdin=open(os.devnull, "r"),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=HOME_DIR,
env=self.child_env)
output_filter_thread = SessionOutputFilterThread(self.session_proc.stdout)
output_filter_thread.start()
if not self.session_proc.pid:
raise Exception("Could not start X session")
def launch_session(self, x_args):
self._init_child_env()
self._setup_pulseaudio()
self._setup_gnubby()
self._launch_x_server(x_args)
self._launch_x_session()
def launch_host(self, host_config, extra_start_host_args):
# Start remoting host
args = [HOST_BINARY_PATH, "--host-config=-"]
if self.pulseaudio_pipe:
args.append("--audio-pipe-name=%s" % self.pulseaudio_pipe)
if self.server_supports_exact_resize:
args.append("--server-supports-exact-resize")
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()
def shutdown_all_procs(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.x_proc, "X server"),
(self.session_proc, "session"),
(self.host_proc, "host")]:
if proc is not None:
logging.info("Terminating " + name)
try:
psutil_proc = psutil.Process(proc.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")
self.x_proc = None
self.session_proc = None
self.host_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 parse_config_arg(args):
"""Parses only the --config option from a given command-line.
Returns:
A two-tuple. The first element is the value of the --config option (or None
if it is not specified), and the second is a list containing the remaining
arguments
"""
# By default, argparse will exit the program on error. We would like it not to
# do that.
class ArgumentParserError(Exception):
pass
class ThrowingArgumentParser(argparse.ArgumentParser):
def error(self, message):
raise ArgumentParserError(message)
parser = ThrowingArgumentParser()
parser.add_argument("--config", nargs='?', action="store")
try:
result = parser.parse_known_args(args)
return (result[0].config, result[1])
except ArgumentParserError:
return (None, list(args))
def get_daemon_proc(config_file, require_child_process=False):
"""Checks if there is already an instance of this script running against
|config_file|, and returns a psutil.Process instance for it. If
|require_child_process| is true, only check for an instance with the
--child-process flag specified.
If a process is found without --config in the command line, get_daemon_proc
will fall back to the old behavior of checking whether the script path matches
the current script. This is to facilitate upgrades from previous versions.
Returns:
A Process instance for the existing daemon process, or None if the daemon
is not running.
"""
# Note: When making changes to how instances are detected, it is imperative
# that this function retains the ability to find older versions. Otherwise,
# upgrades can leave the user with two running sessions, with confusing
# results.
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 process for this instance.
if process.pid == this_pid:
continue
# |cmdline| will be [python-interpreter, script-file, other arguments...]
cmdline = psget(process.cmdline)
if len(cmdline) < 2:
continue
if (os.path.basename(cmdline[0]).startswith('python') and
os.path.basename(cmdline[1]) == os.path.basename(sys.argv[0]) and
"--start" in cmdline):
process_config = parse_config_arg(cmdline[2:])[0]
# Fall back to old behavior if there is no --config argument
# TODO(rkjnsn): Consider removing this fallback once sufficient time
# has passed.
if process_config == config_file or (process_config is None and
cmdline[1] == sys.argv[0]):
if "--child-process" in cmdline:
return process
else:
non_child_process = process
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
return non_child_process if not require_child_process else None
def choose_x_session():
"""Chooses the most appropriate X session command for this system.
Returns:
A string containing the command to run, or a list of strings containing
the executable program and its arguments, which is suitable for passing as
the first parameter of subprocess.Popen(). If a suitable session cannot
be found, returns None.
"""
XSESSION_FILES = [
SESSION_FILE_PATH,
SYSTEM_SESSION_FILE_PATH ]
for startup_file in XSESSION_FILES:
startup_file = os.path.expanduser(startup_file)
if os.path.exists(startup_file):
if os.access(startup_file, os.X_OK):
# "/bin/sh -c" is smart about how to execute the session script and
# works in cases where plain exec() fails (for example, if the file is
# marked executable, but is a plain script with no shebang line).
return ["/bin/sh", "-c", pipes.quote(startup_file)]
else:
# If this is a system-wide session script, it should be run using the
# system shell, ignoring any login shell that might be set for the
# current user.
return ["/bin/sh", startup_file]
# If there's no configuration, show the user a session chooser.
return [HOST_BINARY_PATH, "--type=xsession_chooser"]
class ParentProcessLogger(object):
"""Redirects logs to the parent process, until the host is ready or quits.
This class creates a pipe to allow logging from the daemon process to be
copied to the parent process. The daemon process adds a log-handler that
directs logging output to the pipe. The parent process reads from this pipe
and writes the content to stderr. When the pipe is no longer needed (for
example, the host signals successful launch or permanent failure), the daemon
removes the log-handler and closes the pipe, causing the the parent process
to reach end-of-file while reading the pipe and exit.
The file descriptor for the pipe to the parent process should be passed to
the constructor. The (grand-)child process should call start_logging() when
it starts, and then use logging.* to issue log statements, as usual. When the
child has either succesfully started the host or terminated, it must call
release_parent() to allow the parent to exit.