-
-
Notifications
You must be signed in to change notification settings - Fork 142
/
parsing.py
executable file
·1975 lines (1882 loc) · 101 KB
/
parsing.py
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/env python3
# This file is part of Xpra.
# Copyright (C) 2011 Serviware (Arthur Huillet, <ahuillet@serviware.com>)
# Copyright (C) 2010-2021 Antoine Martin <antoine@xpra.org>
# Copyright (C) 2008 Nathaniel Smith <njs@pobox.com>
# Xpra is released under the terms of the GNU GPL v2, or, at your option, any
# later version. See the file COPYING for details.
import sys
import shlex
import os.path
import optparse
from xpra.version_util import full_version_str
from xpra.platform.features import LOCAL_SERVERS_SUPPORTED, SHADOW_SUPPORTED, CAN_DAEMONIZE
from xpra.util import envbool, csv, parse_simple_dict, DEFAULT_PORT, DEFAULT_PORTS
from xpra.os_util import getuid, WIN32, OSX, POSIX
from xpra.scripts.config import (
OPTION_TYPES, FALSE_OPTIONS,
InitException, InitInfo, InitExit,
fixup_debug_option, fixup_options,
make_defaults_struct, parse_bool, print_number,
validate_config, has_sound_support, name_to_field,
)
def enabled_str(v, true_str="yes", false_str="no") -> str:
if v:
return true_str
return false_str
def enabled_or_auto(v):
return bool_or(v, None, true_str="yes", false_str="no", other_str="auto")
def bool_or(v, other_value, true_str, false_str, other_str):
vs = str(v).lower()
if vs==str(other_value).lower():
return other_str
bv = parse_bool("", v)
return enabled_str(bv, true_str, false_str)
def sound_option(v):
vl = v.lower()
#ensures we return only: "on", "off" or "disabled" given any value
if vl=="no":
vl = "disabled"
return bool_or(vl, "disabled", "on", "off", "disabled")
def _stderr_write(msg):
#use this function to print warnings
#we must write to stderr to prevent
#the output from interfering when running as proxy over ssh
#(which uses stdin / stdout as communication channel)
try:
sys.stderr.write(msg+"\n")
sys.stderr.flush()
return True
except OSError:
return False
def info(msg):
if not _stderr_write(msg) and POSIX:
import syslog
syslog.syslog(syslog.LOG_INFO, msg)
def warn(msg):
if not _stderr_write(msg) and POSIX:
import syslog
syslog.syslog(syslog.LOG_WARNING, msg)
def error(msg):
if not _stderr_write(msg) and POSIX:
import syslog
syslog.syslog(syslog.LOG_ERR, msg)
supports_proxy = True
supports_shadow = SHADOW_SUPPORTED
supports_server = LOCAL_SERVERS_SUPPORTED
if supports_server:
try:
from xpra.x11.bindings.wait_for_x_server import wait_for_x_server #@UnresolvedImport @UnusedImport
except ImportError:
supports_server = False
try:
from xpra.net import mdns
supports_mdns = bool(mdns)
except ImportError:
supports_mdns = False
#this parse doesn't exit when it encounters an error,
#allowing us to deal with it better and show a UI message if needed.
class ModifiedOptionParser(optparse.OptionParser):
def error(self, msg):
raise InitException(msg)
def exit(self, status=0, msg=None):
raise InitExit(status, msg)
def fixup_defaults(defaults):
for k in ("debug", "encoding", "sound-source", "microphone-codec", "speaker-codec"):
fn = k.replace("-", "_")
v = getattr(defaults, fn)
if "help" in v:
if not envbool("XPRA_SKIP_UI", False):
#skip-ui: we're running in subprocess, don't bother spamming stderr
warn(("Warning: invalid 'help' option found in '%s' configuration\n" % k) +
" this should only be used as a command line argument\n")
if k in ("encoding", "debug", "sound-source"):
setattr(defaults, fn, "")
else:
v.remove("help")
def do_replace_option(cmdline, oldoption, newoption):
for i, x in enumerate(cmdline):
if x==oldoption:
cmdline[i] = newoption
elif newoption.find("=")<0 and x.startswith("%s=" % oldoption):
cmdline[i] = "%s=%s" % (newoption, x.split("=", 1)[1])
def do_legacy_bool_parse(cmdline, optionname, newoptionname=None):
#find --no-XYZ or --XYZ
#and replace it with --XYZ=yes|no
no = "--no-%s" % optionname
yes = "--%s" % optionname
if newoptionname is None:
newoptionname = optionname
do_replace_option(cmdline, no, "--%s=no" % optionname)
do_replace_option(cmdline, yes, "--%s=yes" % optionname)
def ignore_options(args, options):
for x in options:
o = "--%s" % x #ie: --use-display
while o in args:
args.remove(o)
o = "--%s=" % x #ie: --bind-tcp=....
remove = []
#find all command line arguments starting with this option:
for v in args:
if v.startswith(o):
remove.append(v)
#and remove them all:
for r in remove:
while r in args:
args.remove(r)
def parse_env(env) -> dict:
d = {}
for ev in env:
try:
if ev.startswith("#"):
continue
v = ev.split("=", 1)
if len(v)!=2:
warn("Warning: invalid environment option '%s'" % ev)
continue
d[v[0]] = os.path.expandvars(v[1])
except Exception as e:
warn("Warning: cannot parse environment option '%s':" % ev)
warn(" %s" % e)
return d
def parse_URL(url):
from urllib.parse import urlparse, parse_qs
up = urlparse(url)
address = up.netloc
qpos = url.find("?")
options = {}
if qpos>0:
params_str = url[qpos+1:]
params = parse_qs(params_str, keep_blank_values=True)
f_params = {}
for k,v in params.items():
t = OPTION_TYPES.get(k)
if t is not None and t!=list:
v = v[0]
f_params[k] = v
options = validate_config(f_params)
scheme = up.scheme
if scheme.startswith("xpra+"):
scheme = scheme[len("xpra+"):]
if scheme in ("tcp", "ssl", "ssh", "ws", "wss"):
address = "%s://%s" % (scheme, address)
return address, options
def _sep_pos(display_name):
#split the display name on ":" or "/"
scpos = display_name.find(":")
slpos = display_name.find("/")
if scpos<0:
return slpos
if slpos<0:
return scpos
return min(scpos, slpos)
def parse_proxy_attributes(display_name):
import re
# Notes:
# (1) this regex permits a "?" in the password or username (because not just splitting at "?").
# It doesn't look for the next "?" until after the "@", where a "?" really indicates
# another field.
# (2) all characters including "@"s go to "userpass" until the *last* "@" after which it all goes
# to "hostport"
reout = re.search("\\?proxy=(?P<p>((?P<userpass>.+)@)?(?P<hostport>[^?]+))", display_name)
if not reout:
return display_name, {}
try:
desc_tmp = {}
# This one should *always* return a host, and should end with an optional numeric port
hostport = reout.group("hostport")
hostport_match = re.match(r"(?P<host>[^:]+)($|:(?P<port>\d+)$)", hostport)
if not hostport_match:
raise RuntimeError("bad format for 'hostport': '%s'" % hostport)
host = hostport_match.group("host")
if not host:
raise RuntimeError("bad format: missing host in '%s'" % hostport)
desc_tmp["proxy_host"] = host
if hostport_match.group("port"):
port_str = hostport_match.group("port")
try:
desc_tmp["proxy_port"] = int(port_str)
except ValueError:
raise RuntimeError("bad format: proxy port '%s' is not a number" % port_str) from None
userpass = reout.group("userpass")
if userpass:
# The username ends at the first colon. This decision was not unique: I could have
# allowed one colon in username if there were two in the string.
userpass_match = re.match("(?P<username>[^:]+)(:(?P<password>.+))?", userpass)
if not userpass_match:
raise RuntimeError("bad format for 'userpass': '%s'" % userpass)
# If there is a "userpass" part, then it *must* have a username
username = userpass_match.group("username")
if not username:
raise RuntimeError("bad format: missing username in '%s'" % userpass)
desc_tmp["proxy_username"] = username
password = userpass_match.group("password")
if password:
desc_tmp["proxy_password"] = password
except RuntimeError:
from xpra.log import Logger
sshlog = Logger("ssh")
sshlog.error("bad proxy argument: " + reout.group(0))
return display_name, {}
else:
# rip out the part we've processed
display_name = display_name[:reout.start()] + display_name[reout.end():]
return display_name, desc_tmp
def parse_remote_display(s):
if not s:
return {}
qpos = s.find("?")
cpos = s.find(",")
display = None
options_str = None
if qpos>=0 and (qpos<cpos or cpos<0):
#query string format, ie: "DISPLAY?key1=value1&key2=value2#extra_stuff
attr_sep = "&"
parts = s.split("?", 1)
s = parts[0].split("#")[0]
options_str = parts[1]
elif cpos>0 and (cpos<qpos or qpos<0):
#csv string format,
# ie: DISPLAY,key1=value1,key2=value2
# or: key1=value1,key2=value2
attr_sep = ","
parts = s.split(",", 1)
if parts[0].find("=")>0:
#if the first part is a key=value,
#assume it is part of the parameters
parts = ["", s]
display = ""
if len(parts)==2:
options_str = parts[1]
elif s.find("=")>0:
#ie: just one key=value
#(so this is not a display)
display = ""
attr_sep = ","
parts = ["", s]
options_str = parts[1]
else:
parts = []
if display is None:
try:
assert [int(x) for x in s.split(".")] #ie: ":10.0" -> [10, 0]
display = ":" + s #ie: ":10.0"
except ValueError:
display = s #ie: "tcp://somehost:10000/"
desc = {
"display" : display,
"display_as_args" : [display],
}
if options_str:
#parse extra attributes
d = parse_simple_dict(options_str, attr_sep)
for k,v in d.items():
if k in desc:
warn("Warning: cannot override '%s' with URI" % k)
else:
desc[k] = v
return desc
def parse_username_and_password(s):
ppos = s.find(":")
if ppos>=0:
password = s[ppos+1:]
username = s[:ppos]
else:
username = s
password = ""
#fugly: we override the command line option after parsing the string:
desc = {}
if username:
desc["username"] = username
if password:
desc["password"] = password
return desc
def parse_host_string(host, default_port=DEFAULT_PORT):
"""
Parses [username[:password]@]host[:port]
and returns username, password, host, port
missing arguments will be empty (username and password) or 0 (port)
"""
upos = host.rfind("@")
if upos>=0:
#HOST=username@host
desc = parse_username_and_password(host[:upos])
host = host[upos+1:]
else:
desc = {}
port_str = None
if host.count(":")>=2:
#more than 2 ":", assume this is IPv6:
if host.startswith("["):
#if we have brackets, we can support: "[HOST]:SSHPORT"
epos = host.find("]")
if epos<0:
raise ValueError("invalid host format, expected IPv6 [..]")
port_str = host[epos+1:] #ie: ":22"
if port_str.startswith(":"):
port_str = port_str[1:] #ie: "22"
host = host[1:epos] #ie: "[HOST]"
else:
#ie: fe80::c1:ac45:7351:ea69%eth1:14500 -> ["fe80::c1:ac45:7351:ea69", "eth1:14500"]
devsep = host.split("%")
if len(devsep)==2:
parts = devsep[1].split(":", 1) #ie: "eth1:14500" -> ["eth1", "14500"]
if len(parts)==2:
host = "%s%%%s" % (devsep[0], parts[0])
port_str = parts[1] #ie: "14500"
else:
parts = host.split(":")
if len(parts[-1])>4:
port_str = parts[-1]
host = ":".join(parts[:-1])
else:
#otherwise, we have to assume they are all part of IPv6
#we could count them at split at 8, but that would be just too fugly
pass
elif host.find(":")>0:
host, port_str = host.split(":", 1)
if port_str:
try:
port = int(port_str)
except ValueError:
raise ValueError("invalid port number specified: %s" % port_str) from None
else:
port = default_port
if port<=0 or port>=2**16:
raise ValueError("invalid port number: %s" % port)
desc.update({
"host" : host or "127.0.0.1",
"port" : port,
"local" : is_local(host),
})
return desc
def load_password_file(password_file):
if not password_file:
return None
if not os.path.exists(password_file):
warn("Error: password file '%s' does not exist:\n" % password_file)
return None
try:
with open(password_file, "rb") as f:
return f.read()
except Exception as e:
warn("Error: failed to read the password file '%s':\n" % password_file)
warn(" %s\n" % e)
return None
def parse_display_name(error_cb, opts, display_name, find_session_by_name=False):
if WIN32:
from xpra.platform.win32.dotxpra import PIPE_PREFIX # pragma: no cover
else:
PIPE_PREFIX = None
if display_name.startswith("/") and POSIX:
display_name = "socket://"+display_name
desc = {"display_name" : display_name}
display_name, proxy_attrs = parse_proxy_attributes(display_name)
desc.update(proxy_attrs)
pos = _sep_pos(display_name)
if pos<0 or (display_name and display_name[0] in "0123456789"):
match = None
if POSIX:
#maybe this is just the display number without the ":" prefix?
try:
if pos>0:
display_name = ":%i" % int(display_name[:pos])
else:
display_name = ":%i" % int(display_name)
match = True
except ValueError:
pass
elif WIN32: # pragma: no cover
display_name = "named-pipe://%s%s" % (PIPE_PREFIX, display_name)
match = True
if find_session_by_name and not match:
#try to find a session whose "session-name" matches:
match = find_session_by_name(opts, display_name)
if match:
display_name = match
#display_name may have been updated, re-parse it:
pos = _sep_pos(display_name)
if pos<0:
error_cb("unknown format for display name: %s" % display_name)
protocol = display_name[:pos]
#the separator between the protocol and the rest can be ":", "/" or "://"
#but the separator value we use thereafter can only be ":" or "/"
#because we want strings like ssl://host:port/DISPLAY to be parsed into ["ssl", "host:port", "DISPLAY"]
psep = ""
if display_name[pos]==":":
psep += ":"
pos += 1
scount = 0
while display_name[pos]=="/" and scount<2:
psep += "/"
pos += 1
scount += 1
if protocol=="socket":
#socket paths may start with a slash!
#so socket:/path means that the slash is part of the path
if psep==":/":
psep = psep[:-1]
pos -= 1
elif protocol=="rfb":
protocol = "vnc"
if psep not in (":", "/", "://"):
error_cb("unknown format for protocol separator '%s' in display name: %s" % (psep, display_name))
afterproto = display_name[pos:] #ie: "host:port/DISPLAY"
separator = psep[-1] #ie: "/"
parts = afterproto.split(separator, 1) #ie: "host:port", "DISPLAY"
def _set_password():
password = desc.get("password")
if password is None:
password = load_password_file(opts.password_file)
if password:
desc["password"] = password
if password:
opts.password = password
def _parse_username_and_password(s):
d = parse_username_and_password(s)
desc.update(d)
opts.username = d.get("username", opts.username)
_set_password()
def _parse_host_string(host, default_port=DEFAULT_PORT):
d = parse_host_string(host, default_port)
desc.update(d)
_set_password()
def _parse_remote_display(s):
d = parse_remote_display(s)
desc.update(d)
opts.display = desc.get("display")
if protocol in ("ssh", "vnc+ssh"):
desc.update({
"type" : protocol,
"proxy_command" : ["_proxy"],
"exit_ssh" : opts.exit_ssh,
"display" : None,
"display_as_args" : [],
})
#desc["proxy_command"] = ["_proxy" if protocol=="ssh" else "_proxy_vnc"]
host = parts[0]
if len(parts)>1:
_parse_remote_display(parts[1])
if protocol=="vnc+ssh":
#use a vnc display string with the proxy command
#and specify the vnc port if we know the display number:
vnc_uri = "vnc://localhost"
if opts.display:
try:
vnc_port = 5900+int(opts.display.lstrip(":"))
desc["remote_port"] = vnc_port
except ValueError:
vnc_uri += "/"
else:
vnc_uri += ":%i/" % vnc_port
desc["display_as_args"] = [vnc_uri]
#ie: ssh=["/usr/bin/ssh", "-v"]
ssh = parse_ssh_string(opts.ssh)
full_ssh = ssh[:]
#maybe restrict to win32 only?
ssh_cmd = ssh[0].lower()
is_putty = ssh_cmd.endswith("plink") or ssh_cmd.endswith("plink.exe")
is_paramiko = ssh_cmd.split(":")[0]=="paramiko"
if is_paramiko:
ssh[0] = "paramiko"
desc["is_paramiko"] = is_paramiko
if opts.ssh.find(":")>0:
desc["paramiko-config"] = parse_simple_dict(opts.ssh.split(":", 1)[1])
if is_putty:
desc["is_putty"] = True
_parse_host_string(host, 22)
ssh_port = desc.pop("port", 22)
if ssh_port!=22:
desc["ssh-port"] = ssh_port
username = desc.get("username")
password = desc.get("password")
host = desc.get("host")
key = desc.get("key", None)
full_ssh += add_ssh_args(username, password, host, ssh_port, key, is_putty, is_paramiko)
if "proxy_host" in desc:
proxy_username = desc.get("proxy_username", "")
proxy_password = desc.get("proxy_password", "")
proxy_host = desc["proxy_host"]
proxy_port = desc.get("proxy_port", 22)
proxy_key = desc.get("proxy_key", "")
full_ssh += add_ssh_proxy_args(proxy_username, proxy_password, proxy_host, proxy_port,
proxy_key, ssh, is_putty, is_paramiko)
desc.update({
"host" : host,
"full_ssh" : full_ssh,
"remote_xpra" : opts.remote_xpra,
})
if opts.socket_dir:
desc["socket_dir"] = opts.socket_dir
return desc
if protocol=="socket":
assert not WIN32, "unix-domain sockets are not supported on MS Windows"
#use the socketfile specified:
slash = afterproto.find("/")
if 0<afterproto.find(":")<slash:
#ie: username:password/run/user/1000/xpra/hostname-number
#remove username and password prefix:
_parse_username_and_password(afterproto[:slash])
sockfile = afterproto[slash:]
elif afterproto.find("@")>=0:
#ie: username:password@/run/user/1000/xpra/hostname-number
parts = afterproto.split("@")
_parse_username_and_password("@".join(parts[:-1]))
sockfile = parts[-1]
else:
sockfile = afterproto
desc.update({
"type" : "unix-domain",
"local" : True,
"socket_dir" : os.path.basename(sockfile),
"socket_dirs" : opts.socket_dirs,
"socket_path" : sockfile,
})
opts.display = None
return desc
if display_name.startswith(":"):
assert not WIN32, "X11 display names are not supported on MS Windows"
desc.update({
"type" : "unix-domain",
"local" : True,
"display" : display_name,
"socket_dirs" : opts.socket_dirs})
opts.display = display_name
if opts.socket_dir:
desc["socket_dir"] = opts.socket_dir
return desc
if protocol in ("tcp", "ssl", "ws", "wss", "vnc"):
desc["type"] = protocol
if len(parts) not in (1, 2, 3):
error_cb("invalid %s connection string,\n" % protocol
+" use %s://[username[:password]@]host[:port][/display]\n" % protocol)
#display (optional):
if separator=="/" and len(parts)==2:
_parse_remote_display(parts[-1])
parts = parts[:-1]
host = ":".join(parts)
default_port = DEFAULT_PORTS.get(protocol, DEFAULT_PORT)
_parse_host_string(host, default_port)
return desc
if protocol=="vsock":
#use the vsock specified:
cid, iport = parse_vsock(parts[0])
desc.update({
"type" : "vsock",
"local" : False,
"display" : display_name,
"vsock" : (cid, iport),
})
opts.display = display_name
return desc
if WIN32 or display_name.startswith("named-pipe:"): # pragma: no cover
if afterproto.find("@")>=0:
parts = afterproto.split("@")
_parse_username_and_password("@".join(parts[:-1]))
pipe_name = parts[-1]
else:
pipe_name = afterproto
if not pipe_name.startswith(PIPE_PREFIX):
pipe_name = "%s%s" % (PIPE_PREFIX, pipe_name)
desc.update({
"type" : "named-pipe",
"local" : True,
"display" : "DISPLAY",
"named-pipe" : pipe_name,
})
opts.display = display_name
return desc
error_cb("unknown format for display name: %s" % display_name)
def parse_ssh_string(ssh_setting):
ssh_cmd = shlex.split(ssh_setting, posix=not WIN32)
if ssh_cmd[0]=="auto":
#try paramiko:
try:
from xpra.log import is_debug_enabled, Logger
from xpra.net.ssh import nogssapi_context
with nogssapi_context():
import paramiko
assert paramiko
ssh_cmd = ["paramiko"]
if is_debug_enabled("ssh"):
Logger("ssh").info("using paramiko ssh backend")
except ImportError as e:
if is_debug_enabled("ssh"):
Logger("ssh").info("no paramiko: %s" % e)
from xpra.platform.features import DEFAULT_SSH_COMMAND
ssh_cmd = shlex.split(DEFAULT_SSH_COMMAND)
return ssh_cmd
def add_ssh_args(username, password, host, ssh_port, key, is_putty=False, is_paramiko=False):
args = []
if password and is_putty:
args += ["-pw", password]
if username and not is_paramiko:
args += ["-l", username]
if ssh_port and ssh_port!=22:
#grr why bother doing it different?
if is_putty:
args += ["-P", str(ssh_port)]
elif not is_paramiko:
args += ["-p", str(ssh_port)]
if not is_paramiko:
args += ["-T", host]
if key:
key_path = os.path.abspath(key)
if WIN32 and is_putty:
# tortoise plink works with either slash, backslash needs too much escaping
# because of the weird way it's passed through as a ProxyCommand
key_path = "\"" + key.replace("\\", "/") + "\"" # pragma: no cover
args += ["-i", key_path]
return args
def add_ssh_proxy_args(username, password, host, ssh_port, pkey, ssh, is_putty=False, is_paramiko=False):
args = []
proxyline = ssh
if is_putty:
proxyline += ["-nc", "%host:%port"]
elif not is_paramiko:
proxyline += ["-W", "%h:%p"]
# the double quotes are in case the password has something like "&"
proxyline += add_ssh_args(username, password, host, ssh_port, pkey, is_putty, is_paramiko)
if is_putty:
args += ["-proxycmd", " ".join(proxyline)]
elif not is_paramiko:
args += ["-o", "ProxyCommand " + " ".join(proxyline)]
return args
def get_server_modes():
server_modes = []
if supports_server:
server_modes.append("start")
server_modes.append("start-desktop")
server_modes.append("upgrade")
if supports_shadow:
server_modes.append("shadow")
return server_modes
def get_subcommands():
return tuple(x.split(" ")[0] for x in get_usage())
def get_usage():
command_options = [""]
if supports_server:
command_options += ["start [DISPLAY]",
"start-desktop [DISPLAY]",
"upgrade [DISPLAY]",
"upgrade-desktop [DISPLAY]",
"recover [DISPLAY]",
]
if supports_shadow:
command_options.append("shadow [DISPLAY]")
command_options += [
"attach [DISPLAY]",
"detach [DISPLAY]",
"info [DISPLAY]",
"id [DISPLAY]",
"version [DISPLAY]",
"stop [DISPLAY]",
"exit [DISPLAY]",
"clean [DISPLAY1] [DISPLAY2]..",
"clean-sockets [DISPLAY]",
"clean-displays [DISPLAY]",
"screenshot filename [DISPLAY]",
"control DISPLAY command [arg1] [arg2]..",
"print DISPLAY filename",
"shell [DISPLAY]",
"showconfig",
"list",
"list-sessions",
"list-windows",
"sessions",
"launcher",
"gui",
"start-gui",
"bug-report",
"toolbox",
"displays",
"clean-displays",
"docs",
"html5",
"autostart",
"encoding",
"path-info",
]
if supports_mdns:
command_options.append("list-mdns")
command_options.append("mdns-gui")
return command_options
def parse_cmdline(cmdline):
defaults = make_defaults_struct()
return do_parse_cmdline(cmdline, defaults)
def do_parse_cmdline(cmdline, defaults):
#################################################################
## NOTE NOTE NOTE
##
## If you modify anything here, then remember to update the man page
## (xpra.1) as well!
##
## NOTE NOTE NOTE
#################################################################
version = "xpra v%s" % full_version_str()
usage_strs = ["\t%%prog %s\n" % x for x in get_usage()]
if not supports_server:
usage_strs = ["(this xpra installation does not support starting local servers)\n"]+usage_strs
parser = ModifiedOptionParser(version=version, usage="\n" + "".join(usage_strs))
hidden_options = {
"display" : defaults.display,
"wm-name" : defaults.wm_name,
"download-path" : defaults.download_path,
}
def replace_option(oldoption, newoption):
do_replace_option(cmdline, oldoption, newoption)
def legacy_bool_parse(optionname, newoptionname=None):
do_legacy_bool_parse(cmdline, optionname, newoptionname)
def ignore(defaults):
ignore_options(cmdline, defaults.keys())
for k,v in defaults.items():
hidden_options[k.replace("-", "_")] = v
group = optparse.OptionGroup(parser, "Server Options",
"These options are only relevant on the server when using the %s mode." %
" or ".join(["'%s'" % x for x in get_server_modes()]))
parser.add_option_group(group)
#we support remote start, so we need those even if we don't have server support:
def dcsv(v):
return csv(v or ["none"])
group.add_option("--start", action="append",
dest="start", metavar="CMD", default=list(defaults.start or []),
help="program to spawn in server (may be repeated). Default: %s." % dcsv(defaults.start))
group.add_option("--start-late", action="append",
dest="start_late", metavar="CMD", default=list(defaults.start_late or []),
help="program to spawn in server once initialization is complete (may be repeated). Default: %s." % dcsv(defaults.start_late))
group.add_option("--start-child", action="append",
dest="start_child", metavar="CMD", default=list(defaults.start_child or []),
help="program to spawn in server,"
+" taken into account by the exit-with-children option"
+" (may be repeated to run multiple commands)."
+" Default: %s." % dcsv(defaults.start_child))
group.add_option("--start-child-late", action="append",
dest="start_child_late", metavar="CMD", default=list(defaults.start_child_late or []),
help="program to spawn in server once initialization is complete"
+" taken into account by the exit-with-children option"
+" (may be repeated to run multiple commands)."
+" Default: %s." % dcsv(defaults.start_child_late))
group.add_option("--start-after-connect", action="append",
dest="start_after_connect", default=defaults.start_after_connect,
help="program to spawn in server after the first client has connected (may be repeated)."
+" Default: %s." % dcsv(defaults.start_after_connect))
group.add_option("--start-child-after-connect", action="append",
dest="start_child_after_connect", default=defaults.start_child_after_connect,
help="program to spawn in server after the first client has connected,"
+" taken into account by the exit-with-children option"
+" (may be repeated to run multiple commands)."
+" Default: %s." % dcsv(defaults.start_child_after_connect))
group.add_option("--start-on-connect", action="append",
dest="start_on_connect", default=defaults.start_on_connect,
help="program to spawn in server every time a client connects (may be repeated)."
+" Default: %s." % dcsv(defaults.start_on_connect))
group.add_option("--start-child-on-connect", action="append",
dest="start_child_on_connect", default=defaults.start_child_on_connect,
help="program to spawn in server every time a client connects,"
+" taken into account by the exit-with-children option (may be repeated)."
+" Default: %s." % dcsv(defaults.start_child_on_connect))
group.add_option("--start-on-last-client-exit", action="append",
dest="start_on_last_client_exit", default=defaults.start_on_last_client_exit,
help="program to spawn in server every time a client disconnects"
+" and there are no other clients left (may be repeated)."
+" Default: %s." % dcsv(defaults.start_on_last_client_exit))
group.add_option("--start-child-on-last-client-exit", action="append",
dest="start_child_on_last_client_exit", default=defaults.start_child_on_last_client_exit,
help="program to spawn in server every time a client disconnects"
+" and there are no other clients left,"
+" taken into account by the exit-with-children option (may be repeated)."
+" Default: %s." % dcsv(defaults.start_child_on_last_client_exit))
group.add_option("--exec-wrapper", action="store",
dest="exec_wrapper", metavar="CMD", default=defaults.exec_wrapper,
help="Wrapper for executing commands. Default: %default.")
legacy_bool_parse("terminate-children")
group.add_option("--terminate-children", action="store", metavar="yes|no",
dest="terminate_children", default=defaults.terminate_children,
help="Terminate all the child commands on server stop. Default: %default")
legacy_bool_parse("exit-with-children")
group.add_option("--exit-with-children", action="store", metavar="yes|no",
dest="exit_with_children", default=defaults.exit_with_children,
help="Terminate the server when the last --start-child command(s) exit")
legacy_bool_parse("start-new-commands")
group.add_option("--start-new-commands", action="store", metavar="yes|no",
dest="start_new_commands", default=defaults.start_new_commands,
help="Allows clients to execute new commands on the server."
+" Default: %s." % enabled_str(defaults.start_new_commands))
legacy_bool_parse("start-via-proxy")
group.add_option("--start-via-proxy", action="store", metavar="yes|no|auto",
dest="start_via_proxy", default=defaults.start_via_proxy,
help="Start servers via the system proxy server. Default: %default.")
legacy_bool_parse("proxy-start-sessions")
group.add_option("--proxy-start-sessions", action="store", metavar="yes|no",
dest="proxy_start_sessions", default=defaults.proxy_start_sessions,
help="Allows proxy servers to start new sessions on demand."
+" Default: %s." % enabled_str(defaults.proxy_start_sessions))
group.add_option("--dbus-launch", action="store",
dest="dbus_launch", metavar="CMD", default=defaults.dbus_launch,
help="Start the session within a dbus-launch context,"
+" leave empty to turn off. Default: %default.")
group.add_option("--source", action="append",
dest="source", default=list(defaults.source or []),
help="Script to source into the server environment. Default: %s." % csv(
("'%s'" % x) for x in (defaults.source or []) if not x.startswith("#")))
group.add_option("--source-start", action="append",
dest="source_start", default=list(defaults.source_start or []),
help="Script to source into the environment used for starting commands. Default: %s." % csv(
("'%s'" % x) for x in (defaults.source_start or []) if not x.startswith("#")))
group.add_option("--start-env", action="append",
dest="start_env", default=list(defaults.start_env or []),
help="Define environment variables used with 'start-child' and 'start',"
+" can be specified multiple times. Default: %s." % csv(
("'%s'" % x) for x in (defaults.start_env or []) if not x.startswith("#")))
if POSIX:
legacy_bool_parse("systemd-run")
group.add_option("--systemd-run", action="store", metavar="yes|no|auto",
dest="systemd_run", default=defaults.systemd_run,
help="Wrap server start commands with systemd-run. Default: %default.")
group.add_option("--systemd-run-args", action="store", metavar="ARGS",
dest="systemd_run_args", default=defaults.systemd_run_args,
help="Command line arguments passed to systemd-run. Default: '%default'.")
else:
ignore({"systemd_run" : defaults.systemd_run,
"systemd_run_args" : defaults.systemd_run_args})
legacy_bool_parse("html")
if supports_server or supports_shadow:
group.add_option("--tcp-proxy", action="store",
dest="tcp_proxy", default=defaults.tcp_proxy,
metavar="HOST:PORT",
help="The address to which non-xpra packets will be forwarded. Default: '%default'.")
group.add_option("--html", action="store",
dest="html", default=defaults.html,
metavar="on|off|[HOST:]PORT",
help="Enable the web server and the html5 client. Default: '%default'.")
group.add_option("--http-scripts", action="store",
dest="http_scripts", default=defaults.http_scripts,
metavar="off|all|SCRIPTS",
help="Enable the builtin web server scripts. Default: '%default'.")
else:
ignore({"tcp_proxy" : "",
"html" : ""})
legacy_bool_parse("daemon")
legacy_bool_parse("attach")
if POSIX and getuid()==0:
group.add_option("--uid", action="store",
dest="uid", default=defaults.uid,
help="The user id to change to when the server is started by root."
+" Default: %s." % defaults.uid)
group.add_option("--gid", action="store",
dest="gid", default=defaults.gid,
help="The group id to change to when the server is started by root."
+" Default: %s." % defaults.gid)
else:
ignore({
"uid" : defaults.uid,
"gid" : defaults.gid,
})
if (supports_server or supports_shadow) and CAN_DAEMONIZE:
group.add_option("--daemon", action="store", metavar="yes|no",
dest="daemon", default=defaults.daemon,
help="Daemonize when running as a server (default: %s)" % enabled_str(defaults.daemon))
group.add_option("--chdir", action="store", metavar="DIR",
dest="chdir", default=defaults.chdir,
help="Change to this directory (default: %s)" % enabled_str(defaults.chdir))
group.add_option("--pidfile", action="store",
dest="pidfile", default=defaults.pidfile,
help="Write the process id to this file (default: '%default')")
group.add_option("--log-dir", action="store",
dest="log_dir", default=defaults.log_dir,
help="The directory where log files are placed"
)
group.add_option("--log-file", action="store",
dest="log_file", default=defaults.log_file,
help="When daemonizing, this is where the log messages will go. Default: '%default'."
+ " If a relative filename is specified the it is relative to --log-dir,"
+ " the value of '$DISPLAY' will be substituted with the actual display used"
)
else:
ignore({
"daemon" : defaults.daemon,
"pidfile" : defaults.pidfile,
"log_file" : defaults.log_file,
"log_dir" : defaults.log_dir,
"chdir" : defaults.chdir,
})
group.add_option("--attach", action="store", metavar="yes|no|auto",
dest="attach", default=defaults.attach,
help="Attach a client as soon as the server has started"
+" (default: %s)" % enabled_or_auto(defaults.attach))
legacy_bool_parse("printing")
legacy_bool_parse("file-transfer")
legacy_bool_parse("open-files")
legacy_bool_parse("open-url")
group.add_option("--file-transfer", action="store", metavar="yes|no|ask",
dest="file_transfer", default=defaults.file_transfer,
help="Support file transfers. Default: %s." % enabled_str(defaults.file_transfer))
group.add_option("--open-files", action="store", metavar="yes|no|ask",
dest="open_files", default=defaults.open_files,
help="Automatically open uploaded files (potentially dangerous). Default: '%default'.")
group.add_option("--open-url", action="store", metavar="yes|no|ask",
dest="open_url", default=defaults.open_url,
help="Automatically open URL (potentially dangerous). Default: '%default'.")
group.add_option("--printing", action="store", metavar="yes|no|ask",
dest="printing", default=defaults.printing,
help="Support printing. Default: %s." % enabled_str(defaults.printing))
group.add_option("--file-size-limit", action="store", metavar="SIZE",
dest="file_size_limit", default=defaults.file_size_limit,
help="Maximum size of file transfers. Default: %s." % defaults.file_size_limit)
if supports_server:
group.add_option("--lpadmin", action="store",
dest="lpadmin", default=defaults.lpadmin,
metavar="COMMAND",
help="Specify the lpadmin command to use. Default: '%default'.")
group.add_option("--lpinfo", action="store",
dest="lpinfo", default=defaults.lpinfo,
metavar="COMMAND",
help="Specify the lpinfo command to use. Default: '%default'.")