-
Notifications
You must be signed in to change notification settings - Fork 369
/
x11docker
executable file
·6992 lines (6379 loc) · 313 KB
/
x11docker
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 bash
# x11docker
# Run GUI applications and desktop environments in docker
#
# - Runs additional X servers to circumvents common X security leaks.
# - Restricts container capabilities to improve container security.
# - Container user is same as host user to avoid root in container.
# - Features e.g. sound, hardware acceleration and data storage.
#
# Type 'x11docker --help' or scroll down to read usage information.
# More documentation at: https://github.com/mviereck/x11docker
Version="5.4.1"
usage() { # --help: show usage information
echo "
x11docker: Run GUI applications and desktop environments in docker.
Usage:
To run a docker image with new X server:
x11docker [OPTIONS] IMAGE [COMMAND]
x11docker [OPTIONS] -- IMAGE [COMMAND [ARG1 ARG2 ...]]
x11docker [OPTIONS] -- DOCKER_RUN_OPTIONS -- IMAGE [COMMAND [ARG1 ARG2 ...]]
To run a host application on a new X server:
x11docker [OPTIONS] --exe COMMAND
x11docker [OPTIONS] --exe -- COMMAND [ARG1 ARG2 ...]
To run only a new empty X server:
x11docker [OPTIONS]
Optional features:
* Hardware acceleration for OpenGL
* Pulseaudio and ALSA sound
* Clipboard sharing
* Printer access
* Webcam access
* Persistent home folders
* Wayland support
* Language locale creation
* Init system in container (systemd, SysVinit, OpenRC, runit, tini)
* DBus in container
Focus on security:
* Avoids X security leaks using additional X servers.
* Container user is same as host user to avoid root in container.
* Restricts container capabilities to bare minimum.
Note that some applications might behave different than with a regular
docker run command due to security restrictions set by x11docker.
Unrestricted container setup is possible with: --user=root --cap-default
Dependencies on host:
Depending on chosen options, x11docker needs some packages to be installed.
It will check for them on startup and show messages if some are missing.
List of possibly needed packages:
* most recommended to allow security and convenience:
X servers: Xephyr xpra nxagent (on Windows: VcXsrv or Xwin)
X tools: xauth xrandr xhost xinit
* advanced GPU support:
Desktop mode: weston Xwayland
Seamless mode: weston Xwayland xpra xdotool
* less important:
xclip xdpyinfo xdg-utils pulseaudio
* least important:
unzip wget xfishtank kwin_wayland Xvfb
xserver-xorg-legacy xserver-xorg-video-dummy
Dependencies in image:
Doesn't have dependencies inside of docker images, except for options:
--gpu: OpenGL packages, often already installed as package dependencies.
--pulseaudio: sound with pulseaudio needs pulseaudio on host and in image.
--lang: localedef to create missing language locales.
--dbus, --dbus-system, --hostdbus: needs dbus in image.
--systemd, --runit,--openrc, --sysvinit: init systems need to be installed.
Options:
--help display this message and exit.
-e, --exe execute host application on new X server (no docker).
--xonly only create empty X server.
Basic settings: (especially influencing auto choosing X server)
-d, --desktop Indicate desktop environment in image.
-g, --gpu Hardware accelerated OpenGL rendering. Shares files in
/dev/dri. Works best with open source drivers installed
on host and OpenGL/Mesa in image.
For closed source nvidia drivers regard terminal output.
Degrades container isolation. Container access to GPU.
-w, --wm COMMAND Host window manager to use for single applications in
nested X server options like --xephyr.
To autodetect a host wm, use --wm=auto or short: -wm
To set default autodetected window manager:
update-alternatives --config x-window-manager
Shared folders:
-m, --home Share a host folder ~/.local/share/x11docker/imagename
as home folder in container to store persistent data.
~/.local/share/x11docker has a softlink to ~/x11docker
--homedir DIR Specify custom host folder DIR for option --home.
--homebasedir DIR Custom base folder for option --home.
(Compare --cachebasedir below).
--sharedir DIR Share host folder (or file) DIR. DIR:ro sets read-only.
Clipboard, sound, printer, language:
-c, --clipboard Share clipboard between X servers (works best with xpra.
Most other X servers need xclip to be installed).
-p, --pulseaudio [=MODE] Sound with pulseaudio. Degrades isolation.
Needs 'pulseaudio' on host and in image.
Optional arg MODE can be 'socket' (default) or 'tcp'.
--alsa Sound with ALSA. Shares devices in /dev/snd. You can
define desired sound card with: --env ALSA_CARD=cardname
Degrades isolation. Container access to sound hardware.
--lang LOCALE Language setting: search for utf8 LOCALE in image and
create it if missing. Needs package 'locale' im image.
LOCALE can be e.g. ru, en, de, zh_CN, cz, fr, fr_BE.
Same as host: --lang=\$LANG.
--printer Share host printers through CUPS server.
--webcam Share host webcam device files.
Special options:
--env VAR=value Set custom environment variable VAR=value
Special use case for user shell: '--env SHELL=/bin/sh'
-i, --interactive Run with an interactive tty to allow shell commands.
--name NAME Specify container name NAME.
--no-internet Disable internet access for container.
--no-entrypoint Disable ENTRYPOINT in image to allow other commands, too
--pull [=ask|yes|no|always] Behaviour if image is missing on host.
ask: Ask in terminal, timeout after 60s (default).
yes: Allow docker pull (default for --pull).
no: Do not run 'docker pull'
always: Always run 'docker pull'. Download only if
newer image is available. Allows sort of auto-update.
--pw FRONTEND Choose frontend for password prompt. Possible FRONTEND:
su sudo gksu gksudo lxsu lxsudo kdesu kdesudo
pkexec beesu none
--runfromhost CMD Run host command CMD on new X server (you may need & ).
--runasroot CMD Run command CMD as root in container on startup.
--sharessh Share SSH agent authentication socket from host.
--showenv Echo new \$DISPLAY, \$XAUTHORITY and \$WAYLAND_DISPLAY.
For custom access to new X server. Get environment with:
read xenv < <(x11docker --showenv [...])
--showid Echo container ID on stdout.
--showpid1 Echo host PID of container PID 1 on stdout.
--stdin Forward stdin of x11docker to image command.
--workdir DIR Set working directory DIR.
X server options:
--auto Auto choose X server (default).
(Regards options --desktop, --gpu, --wayland and --wm).
-a, --xpra Nested X server supporting seamless and --desktop mode.
Needs 'xpra' on host. For faster startup see --nxagent.
-y, --xephyr Nested X server for --desktop mode. Without --desktop,
a host window manager will be provided (option --wm).
(Needs 'Xephyr' or 'Xnest').
-n, --nxagent Nested X server supporting seamless and --desktop mode.
Faster than --xpra and more flexible than --xephyr, but
some compositing applications have issues.
(Needs 'nxagent', best since nxagent version 3.5.99).
-A, --xpra-xwayland Like --xpra, but supports option --gpu.
(Needs 'xpra', 'Xwayland', 'weston' and 'xdotool').
-Y, --weston-xwayland Desktop mode like --xephyr, but supports option --gpu.
Runs from console, within X and within Wayland.
(Needs 'weston' and 'Xwayland'.)
-h, --hostdisplay Share host display :0. Quite bad container isolation!
Least overhead of all X server options.
Some apps may fail due to restricted untrusted cookies.
Remove restrictions by the way with option --clipboard.
-x, --xorg Core Xorg server. Runs ootb from console.
Switch tty with <CTRL><ALT><F1>....<F12>.
To run from within X, edit '/etc/X11/Xwrapper.conf' and
replace line: allowed_users=console
with lines allowed_users=anybody
needs_root_rights=yes
Debian 9 and Ubuntu 16.04: Install xserver-xorg-legacy.
Special X server options:
-t, --tty TTY only. Do not provide any X or Wayland server.
--kwin-xwayland Like --weston-xwayland, but using kwin_wayland
(Needs 'kwin_wayland' and 'Xwayland').
-X, --xwayland Blanc Xwayland, needs a running Wayland compositor.
(Needs 'Xwayland' to be installed.)
--xdummy Invisible X server. (Needs Xorg's dummy video driver)
--xvfb Invisible X server. (Needs 'Xvfb')
--xdummy and --xvfb can be used for custom VNC access.
Output of environment variables on stdout. (--showenv)
Along with option --gpu an invisible setup with Weston,
Xwayland and xdotool is used (instead of Xdummy or Xvfb).
--xwin X server for Windows to run with Cygwin/X.
--vcxsrv X server for Windows to run with MSYS2, Cygwin or WSL.
Wayland without X:
-W, --wayland Automatically set up a Wayland environment.
Chooses one of following options and regards --desktop.
Sets some Wayland environment variables and runs
DBus system daemon (--dbus-system) in container.
-T, --weston Weston without X for pure Wayland applications.
Runs in X or from console. (Needs package weston.)
-K, --kwin KWin without X for pure Wayland applications.
Runs in X or from console. (Needs kwin_wayland.)
-H, --hostwayland Share host Wayland without X for pure Wayland apps.
(Needs already running Wayland compositor like Gnome 3.)
(Can be combined with --hostdisplay.)
X and Wayland appearance options:
--border[=COLOR] Draw a colored border in windows from --xpra[-xwayland].
Optional COLOR can be e.g. 'orange' or '#F00'. Thickness
can be specified, too, e.g. 'red,3'. Default: 'blue,1'
-f, --fullscreen Run Xephyr, nxagent or Weston in fullscreen mode.
--size XxY Screen size of new X server (e.g. 800x600).
--scale N Scale/zoom factor N for xpra, Xorg or Weston.
Allowed for --xpra, --xorg --xpra-xwayland: 0.25...8.0.
Allowed for --weston and --weston-xwayland: 1...9.
(Mismatching font sizes can be adjusted with --dpi).
--rotate N Rotate display (--xorg, --weston and --weston-xwayland)
Allowed values: 0, 90, 180, 270, flipped, flipped-90,
flipped-180, flipped-270. (flipped = mirrored)
--dpi N dpi value (dots per inch) to submit to clients.
Influences font size of some applications.
--output-count N Multiple outputs for Weston, KWin or Xephyr.
--xfishtank Show fish tank on new X server (needs 'xfishtank').
X and Wayland configuration:
--xhost STR Set \"xhost STR\" on new X server (see 'man xhost').
(Use with care. '--xhost +' allows access for everyone).
-o, --no-xhost Disable any access to host X server granted by xhost.
--no-auth Allow access to X for everyone. Security risk!
--display N Use display number N for new X server.
--vt N Use vt / tty N (affects --xorg, --xdummy, --xpra).
--keymap LAYOUT Set keyboard layout for new X server, e.g. de, us, ru.
For possible LAYOUT look at /usr/share/X11/xkb/symbols.
--westonini FILE Custom weston.ini for --weston and --weston-xwayland.
User settings:
--sudouser Allow su and sudo for container user. Use with care,
severe reduction of default x11docker security!
Password: x11docker
--user N Create container user N (N=name or N=uid). Default:
same as host user. N can also be an unknown user id.
You can specify a group id with N being 'user:gid'.
Special case: --user=RETAIN keeps image user settings.
--hostuser USER Run X (and container user) as user USER. Default is
result of \$(logname). (x11docker must run as root).
--group-add GROUP Additional group GROUP for container user.
Init system and DBus daemon:
--tini Default: init system tini (built-in of docker).
--no-init No init system in container. Image command is PID 1.
--runit Init system runit. Degrades container isolation.
Needs 'runit' installed in image. 'dbus' is recommended.
--openrc Init system OpenRC. Degrades container isolation a bit,
but needs less capabilities than --runit and --systemd.
Needs 'openrc' installed in image. 'dbus' recommended.
--sysvinit Init system SysVinit. Degrades container isolation a bit,
but needs less capabilities than others.
Needs 'sysvinit' installed in image. 'dbus' recommended.
--systemd Init system systemd. Degrades container isolation.
For faster startup mask services that fail in container.
Needs 'systemd' installed in image.
Old systemd versions in image need --sys-admin, too.
--sharecgroup Share /sys/fs/cgroup. Allows elogind in container if
used with --dbus-system or init options.
-b, --dbus Run DBus user session daemon for image command.
--dbus-system Run DBus system daemon in container (includes --dbus).
Default for --wayland and for init options except --tini.
--hostdbus Connect to DBus session from host.
Container capabilities:
Custom capabilities can be added with --cap-add=CAP after --
--cap-default Allow default docker container capabilities and
disable container security hardening of x11docker.
--hostipc Sets docker option --ipc=host, disables IPC namespacing.
Severe reduction of container isolation! Shares
host interprocess communication and shared memory.
Allows MIT-SHM extension of X servers.
--hostnet Set docker run option --net=host, disables network
namespacing. Severe reduction of container isolation!
Shares host network stack.
--limit[=FACTOR] Limit CPU and RAM usage of container to
currently free RAM x FACTOR and available CPUs x FACTOR.
Allowed range is 0 < FACTOR <= 1.
Default without argument FACTOR is 0.5
--sys-admin Add capability SYS_ADMIN. Please avoid that.
Miscellaneous:
--launcher Create application launcher on desktop and exit.
You can move the created .desktop file to
~/.local/share/applications to get a menu entry.
--cachebasedir DIR Custom base folder for cache files.
--license Show license of x11docker (MIT) and exit.
--ps Preserve container and cache files on exit.
--cleanup Clean up orphaned containers and cache files.
Verbosity options:
-v, --verbose [=c] Be verbose. Output of logfile on stderr.
Optional argument '=c' generates colored output.
-D, --debug Debug mode: Show some debug output,
-q, --quiet Suppress x11docker terminal messages.
Installation options (need root permissions):
--install Install x11docker and x11docker-gui from current folder.
--update Download and install latest release from github.
--update-master Download and install latest master version from github.
--remove Remove x11docker from your system.
x11docker version: $Version
Please report issues and get help at: https://github.com/mviereck/x11docker
"
}
license() { # --license: show license (MIT)
echo 'MIT License
Copyright (c) 2015, 2016, 2017, 2018 Martin Viereck
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.'
}
#### messages
alertbox() { # X alert box with title $1 and message $2
local Title= Message=
Title=${1:-}
Message=${2:-}
Message="$(echo "$Message" | LANG=C sed "s/[\x80-\xFF]//g" | fold -w120 )" # remove UTF-8 special chars; line folding at 120 chars
# try some tools to show alert message. If all tools fail, return 1
command -v xmessage >/dev/null && [ -n "${DISPLAY:-}" ] && {
echo "$Title
$Message" | xmessage -file - -default okay ||:
} || {
command -v gxmessage >/dev/null && [ -n "${DISPLAY:-}" ] && {
echo "$Title
$Message" | gxmessage -file - -default okay ||:
}
} || {
command -v zenity >/dev/null && [ -n "${DISPLAY:-}" ] && {
zenity --error --no-markup --ellipsize --title="$Title" --text="$Message" 2>/dev/null ||:
}
} || {
command -v yad >/dev/null && [ -n "${DISPLAY:-}" ] && {
yad --image "dialog-error" --title "$Title" --button=gtk-ok:0 --text "$(echo "$Message" | sed 's/\\/\\\\/g')" --fixed 2>/dev/null ||:
}
} || {
command -v kaptain >/dev/null && [ -n "${DISPLAY:-}" ] && {
echo 'start "'$Title'" -> message @close=" cancel" ;
message "'$(echo "$Message" | sed 's/\\/\\\\\\/g' | sed 's/"/\\"/g' | sed -E ':a;N;$!ba;s/\r{0,1}\n/\\n/g' )'" -> @fill ;' | kaptain ||:
}
} || {
command -v kdialog >/dev/null && [ -n "${DISPLAY:-}" ] && {
kdialog --title "$Title" --error "$(echo "$Message" | sed 's/\\/\\\\/g' )" 2>/dev/null ||:
}
} || {
command -v xterm >/dev/null && [ -n "${DISPLAY:-}" ] && {
xterm -title "$Title" -e "echo '$(echo "$Message" | sed "s/'/\"/g")' ; read -n1" ||:
}
} || {
[ -n "$Passwordterminal" ] && [ -e "$Cachefolder" ] && [ "$Xserver" != "--tty" ] && {
mkfile $Cachefolder/message
echo "#! /usr/bin/env bash
echo '$Title
$Message
(Press any key to close window)'
read -n1
" >> $Cachefolder/message
$Passwordterminal /usr/bin/env bash $Cachefolder/message
:
}
} || {
notify-send "$Title:
$Message" 2>/dev/null
} || return 1
return 0
}
traperror() { # trap ERR: --debug: Output for 'set -o errtrace'
debugnote "Command at Line ${2:-} returned with error code ${1:-}:
${4:-}
${3:-} - ${5:-}"
}
error() { # show error message and exit
local Message=
Message="$*
Type 'x11docker --help' for usage information
Debug options: '--verbose' (full log) or '--debug' (log excerpt).
Logfile will be: $Logbackup
Please report issues at https://github.com/mviereck/x11docker"
Message="$(rmcr <<< "$Message")"
# output to terminal
[ "$Verbose" = "no" ] && echo -e "
${Colredbg}x11docker ERROR:${Colnorm} $Message
" >&2
# output to logfile
logentry "x11docker ERROR: $Message
"
[ -e "$Cachefolder/error" ] && waitfortheend # Avoid double alert boxes
[ -d "$Cachefolder" ] && mkfile "$Cachefolder/error" # also regarded by finish() for exit code
# output to X dialogbox if not running in terminal
[ "$Runsinterminal" = "no" ] && [ "$Silent" = "no" ] && export ${Terminalxenv:-DISPLAY} && alertbox "x11docker ERROR" "$Message" &
finish 1
}
warning() { # show warning messages
[ "$Verbose" = "no" ] && echo "${Colyellow}x11docker WARNING:${Colnorm} $*
" >&3
logentry "x11docker WARNING: $*
"
}
note() { # show notice messages
[ "$Verbose" = "no" ] && echo "${Colgreen}x11docker note:${Colnorm} $*
" >&3
logentry "x11docker note: $*
"
}
verbose() { # show verbose messages
# only logfile notes here, terminal output is done with tail in part:verbose
# if $1 = -d then show debug note, too
[ "$1" = "-d" ] && shift && debugnote "$*"
logentry "x11docker[$(date +%s.%2N | cut -c8-)]: $*
"
}
debugnote() { # show debug output $*
[ "$Debugmode" = "yes" ] && {
logentry "DEBUGNOTE[$(date +%s.%2N | cut -c8-)]: $*"
[ "$Verbose" = "no" ] && echo "${Colblue}DEBUGNOTE[$(date +%s.%2N | cut -c8-)]:${Colnorm} $*" >&3
} ||:
}
logentry() { # write into logfile
[ "$Logfile" ] && {
[ "$Logmessages" ] && echo "$Logmessages" >>$Messagelogfile && Logmessages=""
echo "$*" >>$Messagelogfile ||:
} || Logmessages="$Logmessages
$*"
}
setup_verbosity() { # options --verbose, --stdout, --stderr
# create summary logfile
tail --pid=$$ --retry -n +1 -F $Messagelogfile $Containerlogfile \
$Cmdstdoutlogfile $Cmdstderrlogfile ${Journallogfile:-} \
$Xpraserverlogfile $Xpraclientlogfile \
$Xinitlogfile $Compositorlogfile 2>/dev/null >>$Logfile &
# option --verbose
[ "$Verbose" = "yes" ] && {
case $Verbosecolors in
no) tail --pid=$$ --retry -n +1 -F $Logfile 2>/dev/null >&3 & ;;
yes) tail --pid=$$ --retry -n +1 -F $Logfile 2>/dev/null | sed "
/\(Failed to add fd to store\|Failed to set invocation ID\|Failed to reset devices.list\)/d;
s/\(ERROR\|Error\|error\|FAILURE\|FATAL\|Fatal\|fatal\)/${Colredbg}\1${Colnorm}/g;
s/\(Failed\|failed\|Failure\|failure\)/${Colred}\1${Colnorm}/g;
s/\(WARNING\|Warning\|warning\)/${Colyellow}\1${Colnorm}/g;
s/\(DEBUGNOTE\)/${Colblue}\1${Colnorm}/g;
s/^==>.*/${Coluline}\0${Colnorm}/;
s/\(Starting\)/${Colgreen}\0${Colnorm}/;
s/\(Started\|Reached target\)/${Colgreenbg}\0${Colnorm}/;
s/^\(+\|++\|+++\)/${Colgreenbg}\0${Colnorm}/ ;
s/^x11docker/${Colgreen}\0${Colnorm}/ " >&3 &
[ "$Initsystem" = "systemd" ] && note "x11docker deletes some systemd error messages
that are harmless but numerous to get a better readable output.
It deletes all lines with: 'Failed to add fd to store',
'Failed to set invocation ID' and 'Failed to reset devices.list'."
;;
esac
}
# options --stdout, --stderr
[ "$Showstdout" = "yes" ] && {
{ waitforfilecontent $Containerpid1pidfile infinity
tail --pid=$$ --retry -n +1 -F $Cmdstdoutlogfile 2>/dev/null
} & storepid $! tailstdout
}
[ "$Showstderr" = "yes" ] && {
{ tail --pid=$$ --retry -n +1 -F $Cmdstderrlogfile >&4 2>/dev/null
} & storepid $! tailstderr
}
return 0
}
#### exit
finish_sigint() { # trap SIGINT to activate debug mode on finish()
Debugmode="yes"
debugnote "Received SIGINT"
finish
}
finish() { # trap EXIT routine to clean up background processes and cache
local Pid= Name= Zeit= Catlogfilepid= Exitcode= Pid1pid=
trap - EXIT
verbose -d "Terminating x11docker."
debugnote "List of stored background processes:
$(cat $Bgpidfile 2>/dev/null)"
[ "$$" = "$BASHPID" ] || saygoodbye finish-subshell
[ "$Sudo" ] && Sudo="sudo -n" # no password prompt here, rather fail
# check for background processes stored in $Bgpidfile
[ -s "$Bgpidfile" ] && {
while read -r Line ; do
Pid=$(echo $Line | awk '{print $1}')
Name=$(echo $Line | awk '{print $2}')
debugnote "Checking: $Pid ($Name): $(pspid $Pid ||:)"
checkpid $Pid && {
case $Name in
xinit) killpid $Pid $Name xinit ;;
Xserver) killpid $Pid $Name 'Xorg|Xephyr|Xvfb|Xwayland|nxagent|vcxsrv.exe|Xwin' ;;
containershell) killpid $Pid $Name x11docker ;;
windowmanager) killpid $Pid $Name ;;
xpraserver|xpraclient) killpid $Pid $Name xpra ;;
compositor) killpid $Pid $Name 'weston|kwin_wayland' ;;
waitfortheend|xpraloop|watchpidlist)
killpid $Pid $Name x11docker ;;
watchmessagefifo) [ "$$" = "$BASHPID" ] && killpid $Pid $Name x11docker || Pid= ;;
tailstdout|tailstderr) Pid= ;; # tail terminates itself after exit of $$
catstdin) killpid $Pid $Name ;;
hostexe|shareclipboard) killpid $Pid $Name bash ;;
xfishtank) killpid $Pid $Name xfishtank ;;
containerpid1)
Pid1pid=$Pid
Pid=
# Send TERM to PID1 of container
checkpid $Pid1pid 2>&1 && {
verbose -d "Sending TERM to PID 1 of container: $(pspid $Pid1pid)"
killpid $Pid1pid containerPID1 2>/dev/null || note "Could not terminate PID 1 of container: $(pspid $Pid1pid)"
# Give container a bit time for graceful shutdown
case $Initsystem in
systemd) ;;
*)
for Count in 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0; do
checkpid $Pid1pid || break
sleep $( awk "BEGIN { print $Count * 0.1 }")
debugnote "Waiting for container PID 1: $Pid1pid to terminate"
done
;;
esac
}
# Try 'docker stop' if TERM failed
checkpid $Pid1pid && {
verbose -d "Container still running. Executing 'docker stop'."
$Sudo $Dockerexe stop $Containername >>$Containerlogfile 2>&1 || verbose -d "docker stop failed"
}
;;
*) # should never happen (tm)
note "Found remaining background process $Line ($Pid)
$(pspid $Pid)"
killpid $Pid $Name
;;
esac
checkpid $Pid && {
sleep 1
checkpid $Pid && verbose -d "Issue terminating $Line: $(pspid $Pid)" && kill -s KILL $Pid
}
}
done < <(tac $Bgpidfile)
}
# Possibly stored Windows pids to terminate. Currently only VcXsrv in WSL.
[ "$Winpidlist" ] && for Line in $Winpidlist ; do verbose -d "Terminating Windows PID $Line: $(taskkill.exe /F /PID $Line 2>&1 | rmcr)" ; done
saygoodbye "finish"
# Check if container is still running.
# if kill of PID 1 failed in loop above, most times terminating X server will already have stopped GUI applications.
checkpid $Pid1pid && {
$Sudo $Dockerexe stop $Containername >>$Containerlogfile 2>&1 || {
note "Found remaining container process. Most probably the X session was
interrupted. Can not stop container because x11docker does not run as root.
Will wait up to 10 seconds for docker to finish."
Zeit=$(date +%s)
while checkpid $Pid1pid ; do
note "Waiting for container to terminate ..."
sleep 1
[ 10 -lt $(($(date +%s) - $Zeit)) ] && break
done
if checkpid $Pid1pid ; then
note "Container did not terminate as it should.
Will not clean cache to avoid file permission issues.
You can remove the new container with command:
docker rm -f $Containername
Afterwards, remove cache files with:
rm -R $Cachefolder
or let x11docker do the cleanup work for you:
x11docker --cleanup"
Preservecachefiles="yes"
else
note "Container terminated successfully"
fi
}
}
# different stop behaviour on Windows because $Pid1pid is not in ps.
[ "$Winsubsystem" ] && [ "$Containername" ] && {
$Dockerexe ps -a | grep -q $Containername && {
verbose -d "Container still running. Executing 'docker stop'."
$Dockerexe stop $Containername >>$Containerlogfile 2>&1 || {
warning "Failed to stop container $Containername.
Will not clean cache to avoid file permission issues."
Preservecachefiles="yes"
}
}
}
# check for possible error
Exitcode=${1:-0}
[ -e "$Cachefolder/error" ] && Exitcode=1
verbose -d "Exitcode $Exitcode"
# backup of logfile in $Cachebasedir
[ -e "$Logfile" ] && {
[ "$Verbose" = "yes" ] && sleep 1
rmcr $Logfile
$Mksu "cp '$Logfile' '$Logbackup'"
}
# close additional file descriptors
for i in 3 4 6 7 8 9; do
{ >&$i ;} 2>/dev/null && exec >&$i-
done
# remove cache files
[ "$Preservecachefiles" = "no" ] && grep -q cache <<<$Cachefolder && grep -q x11docker <<<$Cachefolder && [ "x11docker" != "$(basename "$Cachefolder")" ] && $Mksu "rm -f -R '$Cachefolder'"
exit $Exitcode
}
saygoodbye() { # create file signaling watching processes to terminate
verbose -d "time to say goodbye ($*)"
[ -e "$Sharefolder" ] && {
echo timetosaygoodbye >> $Timetosaygoodbye
echo timetosaygoodbye >> $Timetosaygoodbyefifo
}
}
#### watching processes and messages
rocknroll() { # check whether x11docker session is still running
[ -s "$Timetosaygoodbye" ] && return 1
[ -e "$Timetosaygoodbye" ] || return 1
return 0
}
waitfortheend() { # wait for end of x11docker session
# signal is byte in $Timetosaygoodbyefifo
# decent read to wait for signal to terminate
case $Winsubsystem in
"")
while rocknroll; do
bash -c "read -n1 -t1 <&8" && saygoodbye timetosaygoodbyefifo
done
;;
*) # Reading from fifo fails on Windows, workaround
while rocknroll; do
sleep 2
done
;;
esac
}
watchpidlist() { # watch list of important pids
# terminate x11docker if a PID in $Watchpidlist terminates
# serves mainly watching X server, Wayland compositor, container and hostexe
# echo PIDs to watch into >&9 (setonwatchpidlist())
local Pid= Containername= Line= Watchpidlist=
while rocknroll ; do
read -t1 Pid <&9 ||:
[ "$Pid" ] && {
[ "${Pid:0:9}" = "CONTAINER" ] && {
Containername=${Pid#CONTAINER}
verbose -d "Watching Container: $Containername"
} || {
Watchpidlist="$Watchpidlist $Pid"
verbose -d "Watching pids:
$(for Line in $Watchpidlist; do pspid $Line ; done)"
}
}
for Pid in $Watchpidlist; do
[ -e /proc/$Pid ] || {
debugnote "watchpidlist: PID $Pid has terminated"
saygoodbye "watchpidlist $Pid"
}
done
[ "$Containername" ] && {
# Container PID not watchable in MSYS2/Cygwin/WSL.
$Dockerexe inspect $Containername >/dev/null 2>&1 || {
debugnote "watchpidlist: Container $Containername has terminated"
saygoodbye "watchpidlist $Containername"
}
}
[ "$Winsubsystem" ] && sleep 2
done
saygoodbye "watchpidlist"
}
setonwatchpidlist() { # add PID $1 to watchpidlist()
#echo ${1:-} >&9
debugnote "Set pid ${1:-} on watchlist: ${2:-}"
echo "${1:-}" >>$Watchpidfifo
}
watchmessagefifo() { # watch for messages out of container or dockerrc
# message in fifo must end with :$Messagetype
local Line= Message= Messagetype=
while rocknroll ; do
IFS= read -r Line <&6 ||:
[ "$Line" ] || sleep 2 # sleep for MSYS2/CYGWIN workaround
[ "$Line" ] && Message="$Message
$Line"
grep -q -E ":WARNING|:NOTE|:DEBUGNOTE|:VERBOSE|:ERROR|:STDOUT" <<< "$Line" && {
Messagetype=":$(echo $Line | rev | cut -d: -f1 | rev)"
Message="${Message%$Messagetype}"
Message="$(tail -n +2 <<< "$Message")" # remove leading newline
case "$Messagetype" in
:WARNING) warning "$Message" ;;
:NOTE) note "$Message" ;;
:DEBUGNOTE) debugnote "$Message" ;;
:ERROR) error "$Message" ;;
:VERBOSE) [ "-d " = "$(cut -c1-3 <<<"$Message" | head -n1)" ] && verbose -d "$(tail -c +4 <<< "$Message")" || verbose "$Message" ;;
:STDOUT) echo "$Message" ;;
esac
Message=
Messagetype=
}
done
}
storepid () { # store pid $1 and name $2 of background process in file $Bgpidfile.
# store Pid and process name of background processes in file
# for use on exit / with trap to clean up with background processes
# this subroutine has a twin in xinitrc
echo ${1:-} ${2:-} >> $Bgpidfile
verbose -d "Stored background pid ${1:-} of ${2:-}"
disown ${1:-} 2>/dev/null ||:
}
mywatch() { # repeat $1 untils its output changes
local Watchoutput=
Watchoutput="$(sh -c "${1:-}" 2>&1)"
verbose -d "Watching output of: sh -c \"'${1:-}'\" 2>&1
Current output:
$Watchoutput"
while rocknroll; do
[ "$Watchoutput" = "$(sh -c "${1:-}" 2>&1)" ] || break
sleep 1
done
verbose -d "Stopped watching output of: sh -c \"'${1:-}'\" 2>&1
Current output:
$(sh -c "${1:-}" 2>&1)"
}
checkpid() { # check if PID $1 is active
#ps -p ${1:-} >/dev/null 2>&1
[ -e "/proc/${1:-NONSENSE}" ]
}
pspid() { # ps -p $1 --no-headers
# On some systems ps does not have option --no-headers.
# On some systems (busybox) ps -p is not supported
ps -p ${1:-} 2>/dev/null || echo "ps -p not supported" | tail -n+2
}
killpid() { # kill PID $1 with codename $2 [and process name $3]
verbose -d "Terminating ${1:-} (${2:-}) ${3:-}: $(pspid ${1:-})"
# ps -p ${1:-} >/dev/null && kill ${1:-} 2>/dev/null
checkpid "${1:-}" && kill ${1:-} 2>/dev/null
}
#### more or less general routines
verlte() { # version number check $1 less than or equal $2
[ "${1:-}" = "$(echo -e "${1:-}\n${2:-}" | sort -V | head -n1)" ] && return 0 || return 1
}
verlt() { # version number check $1 less than $2
[ "${1:-}" = "${2:-}" ] && return 1 || { verlte "${1:-}" "${2:-}" && return 0 || return 1 ; }
}
check_parent_sshd() { # check whether pid $1 runs in SSH session
local Wanted_pid="${1:-}" Process_line
ps -p 1 >/dev/null 2>&1 || {
note "Failed to check for sshd. ps -p not supported."
return 1
}
while [ $Wanted_pid -ne 1 ] ; do
Process_line="$(ps -f -p "$Wanted_pid"| tail -n1)"
Wanted_pid="$(echo $Process_line| awk '{print $3}')"
[[ $Process_line =~ sshd ]] && return 0
done
return 1
}
getrandomnumber() { # get random number
# chosen by fair dice roll
# guaranteed to be random
echo "4"
}
isnum() { # check if $1 is a number
[ "1" = "$(awk -v a="${1:-}" 'BEGIN {print (a == a + 0)}')" ]
}
escapestring() { # escape special chars of $1
# escape all characters except those described in [^a-zA-Z0-9,._+@=:/-]
echo "${1:-}" | LC_ALL=C sed -e 's/[^a-zA-Z0-9,._+@=:/-]/\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'
}
rmcr() { # remove carriage return to translate DOS/Windows newlines into UNIX newlines
# convert stdin if $1 is empty. Otherwise convert file $1.
case "${1:-}" in
"") sed "s/$(printf "\r")//g" ;;
*) sed -i "s/$(printf "\r")//g" "${1:-}"
esac
}
download() { # download file at URL $1 and store it in file $2
# Uses wget or curl. If both are missing, returns 1. Follows redirects.
# With no arguments it checks for curl/wget only.
local Downloader=
command -v wget >/dev/null && Downloader="wget"
command -v curl >/dev/null && Downloader="curl"
[ "$Downloader" ] || return 1
[ "${1:-}" ] || return 0
case $Downloader in
wget) wget "${1:-}" -O "${2:-}" ;;
curl) curl -L "${1:-}" --output "${2:-}" ;;
esac
}
#### file routines
waitforfilecreation() { # similar to inotify-wait: wait up to 15s for file $1 to be created
# $1 file to wait for
# $2 time to wait (optional). default: 15s. possible: infinity
local Zeit= Warten= Dauer= Count=
Zeit=$(date +%s)
verbose -d "Waiting for file creation of ${1:-}"
case ${2:-} in
"") Warten=15 ;;
infinity|inf) Warten=32000 ;; # nearly infinity in fast-moving today ...
*) Warten=${2:-} ;;
esac
while [ ! "$(find "${1:-}" 2>/dev/null)" ] ; do
Count=$(( Count + 1 ))
Dauer=$(( $(date +%s) - $Zeit ))
sleep $(awk "BEGIN { print $Count * 0.1 }")
[ $Warten -lt $Dauer ] && {
warning "Failed to wait for file creation of
${1:-}"
return 1
}
verbose "Waiting since ${Dauer}s for ${1:-} to be created, will wait up to $Warten seconds."
rocknroll || {
verbose -d "Stopped waiting for ${1:-} due to terminating signal."
return 1
}
done
verbose "Found new created file $(ls ${1:-})"
return 0
}
waitforfilecontent() { # wait for file $1 to be not empty
# $1 file to look at
local Zeit= Warten= Dauer= Count=
Zeit=$(date +%s)
case "${2:-}" in
infinity) Warten=32000 ;;
"") Warten=15 ;;
*) Warten="${2:-}" ;;
esac
verbose -d "Waiting for file content in ${1:-}"
while [ ! -s "${1:-}" ] ; do
Count=$(( Count + 1 ))
Dauer=$(( $(date +%s) - $Zeit ))
sleep $(awk "BEGIN { print $Count * 0.1 }")
[ $Warten -lt $Dauer ] && return 1
verbose "Waiting since ${Dauer}s for ${1:-} to have content, will wait up to $Warten seconds."
rocknroll || {
verbose -d "Stopped waiting for file content of ${1:-} due to terminating signal."
return 1
} done
verbose "Found file content in ${1:-}"
return 0
}
waitforlogentry() { # wait for entry $3 in logfile $2 of application $1
# $1 is the application we are waiting for to be ready
# $2 points to logfile
# $3 keyword to wait for
local Zeit= Warten= Dauer= Count=
Zeit=$(date +%s)
Warten=60
while ! grep -q "${3:-}" <"${2:-}" ; do
# grep -i -q -E 'error|Failed to process Wayland|failed to create display|] fatal:' <"${2:-}" && {
grep -i -q -E 'Failed to process Wayland|failed to create display|] fatal:' <"${2:-}" && {
warning "Found error message for ${1:-} in logfile
${2:-}
$(grep -i -E 'error|failed|fatal' <"${2:-}")"
return 1
}
Count=$(( Count + 1 ))
Dauer=$(( $(date +%s) - $Zeit ))
verbose "Waiting since ${Dauer}s for ${1:-} to be ready."
sleep $(awk "BEGIN { print $Count * 0.1 }")
[ $Warten -lt $Dauer ] && return 1
rocknroll || {
verbose -d "Stopped waiting for logentry in ${2:-} of ${1:-} due to terminating signal."
return 1
}
done
verbose "${1:-} is ready."
return 0
}
mkfile() { # create file $1 owned by $Hostuser
:> "${1:-}" || return 1
chown $Hostuser "${1:-}" || return 1
chgrp $Hostusergid "${1:-}" || return 1
[ -n "${2:-}" ] && { chmod ${2:-} "${1:-}" || return 1 ; }
return 0
}
writeaccess() { # check if useruid $1 has write access to folder $2
local dirVals= gMember= IFS=
IFS=$'\t' read -a dirVals < <(stat -Lc "%U %G %A" "${2:-}")
[ "$(id -u $dirVals)" == "${1:-}" ] && [ "${dirVals[2]:2:1}" == "w" ] && return 0
[ "${dirVals[2]:8:1}" == "w" ] && return 0
[ "${dirVals[2]:5:1}" == "w" ] && {
gMember="$(groups ${1:-} 2>/dev/null)"
[[ "${gMember[*]:2}" =~ ^(.* |)${dirVals[1]}( .*|)$ ]] && return 0
}
[ "w" = "$(getfacl -pn "${2:-}" | grep user:${1:-}: | rev | cut -c2)" ] && return 0 || return 1
}
convertpath() { # convert unix and windows pathes
# $1: Mode:
# --windows echo windows path - result: C:/path
# --unix echo unix path - result: /c/path
# --subsystem echo path within subsystem - result: /cygdrive/c/path or /path
# --volume echo --volume compatible syntax - result: 'unixpath':'containerpath':rw (or ":ro")
# $2: Path to convert. Arbitrary syntax, can be C:/path, /c/path, /cygdrive/c/path, /path
# Can have suffix :rw or :ro. If none is given, return with :rw
# $3: Optional for --volume: containerpath
local Mode= Path= Drive= Readwritemode=
Mode="${1:-}"
Path="${2:-}"
# check path for suffix :rw or :ro
Readwritemode="$(echo "$Path" | rev | cut -c1-3 | rev)"
[ "$(cut -c1 <<< "$Readwritemode")" = ":" ] && {
Path="$(echo "$Path" | rev | cut -c4- | rev)"
} || Readwritemode=":rw"
# not on Windows
[ -z "$Winsubsystem" ] && {
case $Mode in
--volume) echo "'$Path':'${3:-$Path}'$Readwritemode" ;;
--unix|--subsystem) echo "$Path" ;;
--windows) warning "Nonsense path conversion $Mode: $Path" ; return 1 ;;
esac
return 0
}
# replace \ with /
Path="$(tr '\\' '/' <<< "$Path")"
# remove possible already given mountpoint
Path="${Path#$Winsubmount}"
# Given format is /c/
[ "$(cut -c1,3 <<< "$Path")" = "//" ] && {
Drive="$(cut -c2 <<< "$Path")"
Path="$(cut -c3- <<< "$Path")"
}
# Given format is C:/
[ "$(cut -c2 <<< "$Path")" = ":" ] && {
Drive="$(cut -c1 <<< "$Path")"
Path="$(cut -c3- <<< "$Path")"
}
# change C to c
Drive="${Drive,}"
[ "$Winsubsystem" = "WSL" ] && [ -z "$Drive" ] && case $Mode in
--windows|--unix|--volume)
warning "Request of Windows path to path within WSL:
$Path
Write access from Windows host to WSL files can damage WSL.
Read-only access is ok."
;;
esac
case $Drive in
"") # Path points into subsystem
Path="${Path#"$Winsubpath"}"
Drive="$(cut -c2 <<<"$Winsubpath")"
case $Mode in
--windows) echo "${Drive^}:$(cut -c3- <<<$Winsubpath)$Path" ;;