-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathchrome-remote-desktop
2005 lines (1692 loc) · 80.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
"""
Forceful server controls for chrome remote desktop.
@ https://github.com/Jesssullivan/chrome-remote-desktop-budgie
@ https://transscendsurvival.org/
"""
import sys
import shutil
import argparse
import atexit
import errno
import fcntl
import grp
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 hashlib
import getpass
class Remote(object):
# if verbose=False, remote class will not print to console,
# leaving only the existing google chrome remote logs
verbose = True
# this is where chrome puts the chrome-remote-desktop scripts:
goog_path = '/opt/google/chrome-remote-desktop/'
crd_path = '/opt/google/chrome-remote-desktop/chrome-remote-desktop'
verbatim_crd_path = '/opt/google/chrome-remote-desktop/chrome-remote-desktop.verbatim'
crd_url = 'https://dl.google.com/linux/direct/chrome-remote-desktop_current_amd64.deb'
this_path = os.path.abspath('chrome-remote-desktop')
# a persistent version of this script lives here,
# so if you want systemctl can check for updates-
# both google overwriting previous changes in /opt
# or remote updates available on github-
# by comparing the checksums of the copies from
# gitub <--> /opt/ <--> /usr/local/bin
bin_path = '/usr/local/bin/'
binscript = bin_path + 'chrome-remote-desktop'
release = bin_path + 'chrome-remote-desktop.github'
# we fetch the latest crd binary here, should it need to be (re)installed
# we also copy the current distributed version for easy override
tmp_path = '/tmp/crd/'
if not os.path.exists(tmp_path):
subprocess.Popen('mkdir ' + tmp_path, shell=True).wait()
deb = tmp_path + '.crd.deb'
# note, 'xbase-clients' must already be installed
apt_depends = ['xbase-clients',
'xvfb',
'xserver-xorg-video-dummy',
'xserver-xorg-input-void']
@staticmethod
def _vprint(text):
if Remote.verbose:
print(text)
@staticmethod
def _execute(cmd):
Remote._vprint(text='executing ``` ' + cmd + ' ```')
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
stdout = proc.stdout.read()
proc.wait()
return stdout
@classmethod
def _is_installed(cls, cmd):
cls._vprint(text='checking if ' + cmd + ' is present...')
if not shutil.which(cmd):
cls._vprint(text="didn't find " + cmd + '...')
return False
else:
return True
@classmethod
def serve_install(cls, apt=True, do_install=True):
# serve_install both checks apt depends as well as
# reinstall the chrome-remote-desktop software w/ dpkg.
if apt:
for depend in cls.apt_depends:
if not cls._is_installed(cmd=depend):
subprocess.Popen('sudo apt-get install ' + depend + ' -y', shell=True).wait()
if not os.path.exists(cls.crd_path) and do_install:
cls._vprint(text='fetching deb package...')
wget = str('wget -O ' + cls.deb + ' ' + cls.crd_url)
cls._execute(wget)
cls._vprint(text='checking ' + cls.deb + ' w/ dpkg...')
cmds = [
'sudo dpkg -i ' + cls.deb,
'sudo usermod -a -G chrome-remote-desktop $USER',
'sudo chmod +s /opt/google/chrome-remote-desktop/user-session'
]
for cmd in cmds:
cls._execute(cmd)
time.sleep(.1)
cls._vprint(text='done with dpkg, you may need to reboot for usermod changes to take effect')
# makes a backup of the chrome-remote-desktop script as distributed,
# prior to making any further changes:
copy_cmd = str('sudo cp -R ' + __file__ + ' ' + cls.verbatim_crd_path)
cls._execute(copy_cmd)
@classmethod
def sync_scripts(cls):
# sync_scripts lets us make sure the script version chrome is using to manage
# chrome-remote-desktop threads is the one we want, e.g. this one :)
# this way when google pushes automatic updates the rest of the software-
# overriding this one- the persistent version called by systemctl version
# in /bin/ will notice and add itself back to /opt/.
script_versions = [cls.this_path, cls.crd_path, cls.binscript, cls.release]
cls._vprint(text='checking scripts....')
for script in script_versions:
if script != cls.this_path:
cmd = str('sudo cp -R ' + cls.this_path + ' ' + script)
cls._execute(cmd)
# we all check the current github release here only to notify the user if there is
# a new script version. the new script is not automatically used, but is available in /bin/
# (__file__.new) alongside the existing script.
cls._vprint(text='fetching latest script release...')
subprocess.Popen(str(
'sudo wget -O ' + cls.release + ' ' +
'https://raw.githubusercontent.com/Jesssullivan/chrome-remote-desktop-budgie/master/chrome-remote-desktop'),
shell=True).wait()
cls._vprint(text='comparing script checksums...')
time.sleep(.1)
hashes = {}
for script in script_versions:
hashmd = hashlib.md5()
hash_crd = open(script, "rb")
content = hash_crd.read()
hashmd.update(content)
hashes[script] = hashmd.hexdigest()
cls._vprint(text='syncing scripts....')
time.sleep(.1)
cls._vprint(text=' __file__ hash: ' + hashes[cls.this_path] +
'\n github release hash: ' + hashes[cls.release] +
'\n local /bin/ script hash: ' + hashes[cls.binscript] +
'\n /opt/ script hash: ' + hashes[cls.crd_path])
# remote.this_path will usually by the same as remote.binscript-
# systemctl should only be calling remote.binscript.
if hashes[cls.this_path] != hashes[cls.binscript]:
# in this scenario, $USER is likely running __file__ to set everything up
cmd = str('sudo cp -R ' + __file__ + ' ' + cls.binscript)
cls._execute(cmd)
if hashes[cls.binscript] != hashes[cls.crd_path]:
# in this scenario, google may have updated chrome-remote-desktop, and reset changes
cmd = str('sudo cp -R ' + cls.binscript + ' ' + cls.crd_path)
cls._execute(cmd)
if hashes[cls.release] != hashes[cls.binscript]:
cls._vprint(text='Hey! your chrome-remote-desktop is out of sync with new changes on github,' +
' check the changes or consider contributing @ ' +
'https://github.com/Jesssullivan/chrome-remote-desktop-budgie \n')
@classmethod
def get_display(cls):
try:
proc = subprocess.Popen('echo $DISPLAY', stdout=subprocess.PIPE, shell=True)
result = proc.stdout.read().__str__()
display_num = result.split(':')[1].split('\\')[0]
cls._vprint(text='$DISPLAY value read @ ' + display_num)
return display_num
except:
display_num = 0
cls._vprint(text='$DISPLAY value set @ 0')
return display_num
@staticmethod
def passed_crd(*passed_arg):
cmd = str(Remote.crd_path + str(*passed_arg))
try:
passed = Remote._execute(cmd)
if 'denied' in passed.__str__():
raise ChildProcessError
except ChildProcessError:
print('A command was denied, please reboot')
except:
print('noting error, continuing....')
time.sleep(.5)
pass
remote_sizes = ("1600x1200,1600x900,1440x900,1366x768,1360x768,1280x1024,"
"1280x800,1280x768,1280x720,1152x864,1024x768,1024x600,"
"800x600,1680x1050,1920x1080,1920x1200,2560x1440,"
"2560x1600,3840x2160,3840x2560")
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 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
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.
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 = Remote.remote_sizes
DEFAULT_SIZES_XORG = Remote.remote_sizes
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 = Remote.get_display()
# 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)
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"]
def run_command_with_group(command, group):
"""Run a command with a different primary group."""
# This is implemented using sg, which is an odd character and will try to
# prompt for a password if it can't verify the user is a member of the given
# group, along with in a few other corner cases. (It will prompt in the
# non-member case even if the group doesn't have a password set.)
#
# To prevent sg from prompting the user for a password that doesn't exist,
# redirect stdin and detach sg from the TTY. It will still print something
# like "Password: crypt: Invalid argument", so redirect stdout and stderr, as
# well. Finally, have the shell unredirect them when executing user-session.
#
# It is also desirable to have some way to tell whether any errors are
# from sg or the command, which is done using a pipe.
def pre_exec(read_fd, write_fd):
os.close(read_fd)
# /bin/sh may be dash, which only allows redirecting file descriptors 0-9,
# the minimum required by POSIX. Since there may be files open elsewhere,
# move the relevant file descriptors to specific numbers under that limit.
# Because this runs in the child process, it doesn't matter if existing file
# descriptors are closed in the process. After, stdio will be redirected to
# /dev/null, write_fd will be moved to 6, and the old stdio will be moved
# to 7, 8, and 9.
if (write_fd != 6):
os.dup2(write_fd, 6)
os.close(write_fd)
os.dup2(0, 7)
os.dup2(1, 8)
os.dup2(2, 9)
devnull = os.open(os.devnull, os.O_RDWR)
os.dup2(devnull, 0)
os.dup2(devnull, 1)
os.dup2(devnull, 2)
os.close(devnull)
# os.setsid will detach subprocess from the TTY
os.setsid()
# Pipe to check whether sg successfully ran our command.
read_fd, write_fd = os.pipe()
try:
# sg invokes the provided argument using /bin/sh. In that shell, first write
# "success\n" to the pipe, which is checked later to determine whether sg
# itself succeeded, and then restore stdio, close the extra file
# descriptors, and exec the provided command.
process = subprocess.Popen(
["sg", group,
"echo success >&6; exec {command} "
# Restore original stdio
"0<&7 1>&8 2>&9 "
# Close no-longer-needed file descriptors
"6>&- 7<&- 8>&- 9>&-"
.format(command=" ".join(map(pipes.quote, command)))],
# It'd be nice to use pass_fds instead close_fds=False. Unfortunately,
# pass_fds doesn't seem usable with remapping. It runs after preexec_fn,
# which does the remapping, but complains if the specified fds don't
# exist ahead of time.
close_fds=False, preexec_fn=lambda: pre_exec(read_fd, write_fd))
result = process.wait()
except OSError as e:
logging.error("Failed to execute sg: {}".format(e.strerror))
if e.errno == errno.ENOENT:
result = COMMAND_NOT_FOUND_EXIT_CODE
else:
result = COMMAND_NOT_EXECUTABLE_EXIT_CODE
# Skip pipe check, since sg was never executed.
os.close(read_fd)
return result
except KeyboardInterrupt:
# Because sg is in its own session, it won't have gotten the interrupt.
try:
os.killpg(os.getpgid(process.pid), signal.SIGINT)
result = process.wait()
except OSError:
logging.warning("Command may still be running")
result = 1
finally:
os.close(write_fd)
with os.fdopen(read_fd) as read_file:
contents = read_file.read()
if contents != "success\n":
# No success message means sg didn't execute the command. (Maybe the user
# is not a member of the group?)
logging.error("Failed to access {} group. Is the user a member?"
.format(group))
result = COMMAND_NOT_EXECUTABLE_EXIT_CODE
return result
def start_via_user_session(foreground):
# We need to invoke user-session
global process
command = [USER_SESSION_PATH, "start"]
if foreground:
command += ["--foreground"]
command += ["--"] + sys.argv[1:]
try:
process = subprocess.Popen(command)
result = process.wait()
except OSError as e:
if e.errno == errno.EACCES:
# User may have just been added to the CRD group, in which case they
# won't be able to execute user-session directly until they log out and
# back in. In the mean time, we can try to switch to the CRD group and
# execute user-session.
result = run_command_with_group(command, CHROME_REMOTING_GROUP_NAME)
else:
logging.error("Could not execute {}: {}"
.format(USER_SESSION_PATH, e.strerror))
if e.errno == errno.ENOENT:
result = COMMAND_NOT_FOUND_EXIT_CODE
else:
result = COMMAND_NOT_EXECUTABLE_EXIT_CODE
except KeyboardInterrupt:
# Child will have also gotten the interrupt. Wait for it to exit.
result = process.wait()
return result
def cleanup():
logging.info("Cleanup.")
global g_desktop
if g_desktop is not None:
g_desktop.shutdown_all_procs()
if g_desktop.xorg_conf is not None:
os.remove(g_desktop.xorg_conf)
g_desktop = None
ParentProcessLogger.release_parent_if_connected(False)
def relaunch_self():
"""Relaunches the session to pick up any changes to the session logic in case
Chrome Remote Desktop has been upgraded. We return a special exit code to
inform user-session that it should relaunch.
"""
# cleanup run via atexit
sys.exit(RELAUNCH_EXIT_CODE)
def waitpid_with_timeout(pid, deadline):
"""Wrapper around os.waitpid() which waits until either a child process dies
or the deadline elapses.
Args:
pid: Process ID to wait for, or -1 to wait for any child process.
deadline: Waiting stops when time.time() exceeds this value.
Returns:
(pid, status): Same as for os.waitpid(), except that |pid| is 0 if no child
changed state within the timeout.
Raises:
Same as for os.waitpid().
"""
while time.time() < deadline:
pid, status = os.waitpid(pid, os.WNOHANG)
if pid != 0:
return pid, status
time.sleep(1)
return 0, 0
def waitpid_handle_exceptions(pid, deadline):
"""Wrapper around os.waitpid()/waitpid_with_timeout(), which waits until
either a child process exits or the deadline elapses, and retries if certain
exceptions occur.
Args:
pid: Process ID to wait for, or -1 to wait for any child process.
deadline: If non-zero, waiting stops when time.time() exceeds this value.
If zero, waiting stops when a child process exits.
Returns:
(pid, status): Same as for waitpid_with_timeout(). |pid| is non-zero if and
only if a child exited during the wait.
Raises:
Same as for os.waitpid(), except:
OSError with errno==EINTR causes the wait to be retried (this can happen,
for example, if this parent process receives SIGHUP).
OSError with errno==ECHILD means there are no child processes, and so
this function sleeps until |deadline|. If |deadline| is zero, this is an
error and the OSError exception is raised in this case.
"""
while True:
try:
if deadline == 0:
pid_result, status = os.waitpid(pid, 0)
else:
pid_result, status = waitpid_with_timeout(pid, deadline)
return pid_result, status
except OSError as e:
if e.errno == errno.EINTR:
continue
elif e.errno == errno.ECHILD:
now = time.time()
if deadline == 0:
# No time-limit and no child processes. This is treated as an error
# (see docstring).
raise
elif deadline > now:
time.sleep(deadline - now)
return 0, 0
else:
# Anything else is an unexpected error.
raise
def watch_for_resolution_changes(initial_size):
"""Watches for any resolution-changes which set the maximum screen resolution,
and resets the initial size if this happens.
The Ubuntu desktop has a component (the 'xrandr' plugin of
unity-settings-daemon) which often changes the screen resolution to the
first listed mode. This is the built-in mode for the maximum screen size,
which can trigger excessive CPU usage in some situations. So this is a hack
which waits for any such events, and undoes the change if it occurs.
Sometimes, the user might legitimately want to use the maximum available
resolution, so this monitoring is limited to a short time-period.
"""
for _ in range(30):
time.sleep(1)
xrandr_output = subprocess.Popen(["xrandr"],
stdout=subprocess.PIPE).communicate()[0]
matches = re.search(br'current (\d+) x (\d+), maximum (\d+) x (\d+)',
xrandr_output)
# No need to handle ValueError. If xrandr fails to give valid output,
# there's no point in continuing to monitor.
current_size = (int(matches.group(1)), int(matches.group(2)))
maximum_size = (int(matches.group(3)), int(matches.group(4)))
if current_size != initial_size:
# Resolution change detected.
if current_size == maximum_size:
# This was probably an automated change from unity-settings-daemon, so
# undo it.
label = "%dx%d" % initial_size
args = ["xrandr", "-s", label]
subprocess.call(args)
args = ["xrandr", "--dpi", "96"]
subprocess.call(args)
# Stop monitoring after any change was detected.
break
def main():
EPILOG = ''
parser = argparse.ArgumentParser(
usage="Usage: %(prog)s [options] [ -- [ X server options ] ]",
epilog=EPILOG)
parser.add_argument("-s", "--size", dest="size", action="append",
help="Dimensions of virtual desktop. This can be "
"specified multiple times to make multiple screen "
"resolutions available (if the X server supports this).")
parser.add_argument("-f", "--foreground", dest="foreground", default=False,
action="store_true",
help="Don't run as a background daemon.")
parser.add_argument("--start", dest="start", default=False,
action="store_true",
help="Start the host.")
parser.add_argument("-k", "--stop", dest="stop", default=False,
action="store_true",
help="Stop the daemon currently running.")
parser.add_argument("--get-status", dest="get_status", default=False,
action="store_true",
help="Prints host status")
parser.add_argument("--check-running", dest="check_running",
default=False, action="store_true",
help="Return 0 if the daemon is running, or 1 otherwise.")
parser.add_argument("--config", dest="config", action="store",
help="Use the specified configuration file.")
parser.add_argument("--reload", dest="reload", default=False,
action="store_true",
help="Signal currently running host to reload the "
"config.")
parser.add_argument("--add-user", dest="add_user", default=False,
action="store_true",
help="Add current user to the chrome-remote-desktop "
"group.")
parser.add_argument("--add-user-as-root", dest="add_user_as_root",
action="store", metavar="USER",
help="Adds the specified user to the "
"chrome-remote-desktop group (must be run as root).")
# The script is being run as a child process under the user-session binary.
# Don't daemonize and use the inherited environment.
parser.add_argument("--child-process", dest="child_process", default=False,
action="store_true",
help=argparse.SUPPRESS)
parser.add_argument("--watch-resolution", dest="watch_resolution",
type=int, nargs=2, default=False, action="store",
help=argparse.SUPPRESS)
parser.add_argument(dest="args", nargs="*", help=argparse.SUPPRESS)
options = parser.parse_args()
# Determine the filename of the host configuration.
if options.config:
config_file = options.config
else:
config_file = os.path.join(CONFIG_DIR, "host#%s.json" % g_host_hash)
config_file = os.path.realpath(config_file)
# Check for a modal command-line option (start, stop, etc.)
if options.get_status:
proc = get_daemon_proc(config_file)
if proc is not None:
print("STARTED")
elif is_supported_platform():
print("STOPPED")
else:
print("NOT_IMPLEMENTED")
return 0
if options.check_running:
proc = get_daemon_proc(config_file)
return 1 if proc is None else 0
if options.stop:
proc = get_daemon_proc(config_file)
if proc is None:
print("The daemon is not currently running")
else:
print("Killing process %s" % proc.pid)
proc.terminate()
try:
proc.wait(timeout=30)
except psutil.TimeoutExpired:
print("Timed out trying to kill daemon process")
return 1
return 0