-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
x11docker
9061 lines (8309 loc) · 385 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 containers.
#
# - Runs additional X servers to circumvent common X security leaks.
# - Restricts container capabilities to enhance container security.
# - Container user is same as host user to avoid root in container.
# - Features e.g. sound, hardware acceleration and data storage.
#
# Run 'x11docker --help' or scroll down to read usage information.
# More documentation at: https://github.com/mviereck/x11docker
Version="6.8.0"
# --enforce-i: Enforce running in interactive mode to allow commands tty and weston-launch in special setups.
grep -q -- "--enforce-i" <<< "$*" && case $- in
*i*) set +H ;;
*) exec bash --noprofile --norc --noediting -i -- "$0" "$@" ;;
esac
usage() { # --help: show usage information
echo "
x11docker: Run GUI applications and desktop environments in Docker containers.
Usage:
To run a Docker container on a new X server:
x11docker IMAGE
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 an empty new X server:
x11docker [OPTIONS] --xonly
x11docker always runs a fresh container from image and discards it afterwards.
Runs on Linux and (with some restrictions) on MS Windows. Not adapted for macOS.
Optional features:
* GPU hardware acceleration
* Sound with pulseaudio or ALSA
* Clipboard sharing
* Printer access
* Webcam access
* Persistent home folder
* Wayland support
* Language locale creation
* Several init systems and DBus in container
* Support of several container runtimes
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.
x11docker sets up an unprivileged container user with password 'x11docker'
and restricts container capabilities. Some applications might behave different
than with a regular 'docker run' command due to these security restrictions.
Achieve a less restricted setup with --cap-default, --sudouser or --user=root.
Dependencies on host:
For core functionality x11docker only needs bash, docker and an X server.
Depending on chosen options x11docker might need some additional tools.
It checks for them on startup and shows messages if some are missing.
Core list of recommended tools:
* Recommended to allow security and convenience:
X servers: xpra Xephyr nxagent
X tools: xauth xclip xrandr xhost xinit
* Advanced GPU support: weston Xwayland xpra xdotool
See also: https://github.com/mviereck/x11docker/wiki/Dependencies
Dependencies in image:
No dependencies in image except for a few feature options. Most important:
--gpu: OpenGL/MESA packages, collected often in 'mesa-utils' package.
--pulseaudio: Needs pulseaudio on host and pulseaudio client libs in image.
--printer: Needs cups on host and cups client libs in image.
See also: https://github.com/mviereck/x11docker/wiki/Dependencies
Options: (short options do not accept arguments)
--help Display this message and exit.
-e, --exe Execute host application instead of docker container.
--xonly Only create empty X server.
Basic settings:
-d, --desktop Indicate a desktop environment in image.
In that case important for automatical X server choice.
-i, --interactive Run with an interactive tty to allow shell commands.
Useful with commands like bash.
Host integration:
--alsa [=ALSA_CARD] Sound with ALSA. You can define a desired sound card
with ALSA_CARD. List of available sound cards: aplay -l
-c, --clipboard Share clipboard. Graphical clips with --xpra only.
-g, --gpu GPU access for hardware accelerated OpenGL rendering.
Works best with open source drivers on host and in image.
For closed source nvidia drivers regard terminal output.
-I, --network [=NET] Allow internet access. (Currently enabled by default,
will change in future.)
For optional argument NET see Docker documentation
of docker run option --network.
--network=none disables internet access. (future default)
-l, --lang [=LOCALE] Set language variable LANG=LOCALE in container.
Without arg LOCALE host variable --lang=\$LANG is used.
If LOCALE is missing in image, x11docker generates it
with 'localedef' in container (needs 'locales' package).
Examples for LOCALE: ru, en, de, zh_CN, cz, fr, fr_BE.
-P, --printer [=MODE] Share host printers through CUPS server.
Optional MODE can be 'socket' or 'tcp'. Default: socket
-p, --pulseaudio [=MODE] Sound with pulseaudio. Needs 'pulseaudio' on host
and in image. Optional arg MODE can be 'socket' or 'tcp'.
--webcam Share host webcam device files.
Shared host folders or Docker volumes:
-m, --home [=ARG] Create a persistant HOME folder for data storage.
Default: Uses ~/.local/share/x11docker/IMAGENAME.
ARG can be another host folder or a Docker volume.
(~/.local/share/x11docker has a softlink to ~/x11docker.)
(Use --homebasedir to change this base storage folder.)
--share ARG Share host file or folder ARG. Read-only with ARG:ro
Device files in /dev can be shared, too.
ARG can also be a Docker volume instead of a host folder.
X server options:
--auto Automatically choose X server (default). Influenced
noteable by options --desktop, --gpu, --wayland, --wm.
-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 with option --clipboard.
-n, --nxagent Nested X server supporting seamless and --desktop mode.
Faster than --xpra, but can have compositing issues.
-Y, --weston-xwayland Desktop mode like --xephyr, but supports option --gpu.
Runs from console, within X and within Wayland.
-y, --xephyr Nested X server for --desktop mode. Without --desktop
a host window manager will be provided (option --wm).
-x, --xorg Core Xorg server. Runs ootb from console.
Switch tty with <CTRL><ALT><F1>....<F12>. Always switch
to a black tty before switching to X to avoid crashes.
-a, --xpra Nested X server supporting seamless and --desktop mode.
-A, --xpra-xwayland Like --xpra, but supports option --gpu.
Special X server options:
--kwin-xwayland Like --weston-xwayland, but using kwin_wayland
-t, --tty Terminal only mode. Does not run an X or Wayland server.
--xdummy Invisible X server using dummy video driver.
--xvfb Invisible X server using 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).
-X, --xwayland Blanc Xwayland, needs a running Wayland compositor.
--xwin X server to run in Cygwin/X on MS Windows.
Wayland instead of X:
-W, --wayland Automatically set up a Wayland environment.
Chooses one of following options and regards --desktop.
-T, --weston Weston without X for pure Wayland applications.
Runs in X, in Wayland or from console.
-K, --kwin KWin without X for pure Wayland applications.
Runs in X, in Wayland or from console.
-H, --hostwayland Share host Wayland without X for pure Wayland apps.
X and Wayland appearance options:
--border [=COLOR] Draw a colored border in windows of --xpra[-xwayland].
Argument COLOR can be e.g. 'orange' or '#F00'. Thickness
can be specified, too, e.g. 'red,3'. Default: 'blue,1'
--dpi N dpi value (dots per inch) to submit to X clients.
Influences font size of some applications.
-f, --fullscreen Run in fullscreen mode.
--output-count N Multiple virtual monitors for Weston, KWin or Xephyr.
--rotate N Rotate display (--xorg, --weston and --weston-xwayland)
Allowed values: 0, 90, 180, 270, flipped, flipped-90,
flipped-180, flipped-270. (flipped means mirrored)
--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).
Odd resolutions with --xorg might need --scale=1.
--size WxH Screen size of new X server (e.g. 800x600).
-w, --wm [=ARG] Provide a window manager to container applications.
If available, image x11docker/openbox will be used.
Otherwise x11docker looks for a host window manager.
Possible ARG:
host: Enforce autodetection of a host window manager.
COMMAND: COMMAND can be a desired host window manager.
IMAGE: IMAGE can be a local docker image with a WM.
none: Run without a window manager. Same as --desktop.
-F, --xfishtank Show fish tank on new X server.
X and Wayland special configuration:
--clean-xhost Disable xhost access policies on host display.
--display N Use display number N for new X server.
--iglx Use indirect rendering for OpenGL. (Currently works with
closed source nvidia driver only, bug in MESA libgl.)
--keymap LAYOUT Set keyboard layout for new X server, e.g. de, us, ru.
For possible LAYOUT look at /usr/share/X11/xkb/symbols.
--no-auth Allow access to X for everyone. Security risk!
--vt N Use vt / tty N (regarded by --xorg only).
--westonini FILE Custom weston.ini for --weston and --weston-xwayland.
--xhost STR Set \"xhost STR\" on new X server (see 'man xhost').
(Use with care. '--xhost +' allows access for everyone).
--xoverip Connect to X over TCP network. For special setups only.
Only supported by a subset of X server options.
--xtest [=yes|no] Enable or disable X extension XTEST. Default is yes for
--xpra, --xvfb and --xdummy, no for other X servers.
Needed to allow custom access with xpra.
Container user settings:
--group-add GROUP Add container user to group GROUP.
--hostuser USER Run X (and container user) as user USER. Default is
result of \$(logname). (x11docker must run as root).
--password [=WORD] Change container user password and exit.
Interactive input if argument WORD is not provided.
Stored encrypted in ~/.config/x11docker/passwd.
--sudouser [=nopasswd] Allow su and sudo for container user. Use with care,
severe reduction of default x11docker security!
Optionally passwordless sudo with argument nopasswd.
Default password is '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.
Container capabilities:
In most setups x11docker sets --cap-drop=ALL --security-opt=no-new-privileges
and shows warnings if doing otherwise.
Custom capabilities can be added with --cap-add=CAP after --
--cap-default Allow default docker container capabilities.
Includes --newprivileges=yes.
--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.
--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 for --limit without argument FACTOR: 0.5
--newprivileges [=yes|no|auto] Set or unset docker run option
--security-opt=no-new-privileges. Default with no
argument is 'yes'. Default for most cases is 'no'.
Container init system, elogind and DBus daemon:
--dbus [=system] Run DBus user session daemon for container command.
With argument 'system' also run a DBus system daemon.
(To run a DBus system daemon rather use one of
--init=systemd|openrc|runit|sysvinit )
--hostdbus Connect to DBus user session from host.
--init [=INITSYSTEM] Run an init system as PID 1 in container. Solves the
zombie reaping issue. INITSYSTEM can be:
tini: Default. Mostly present as docker-init on host.
none: No init system, container command will be PID 1.
Others: systemd, sysvinit, runit, openrc, s6-overlay.
--sharecgroup Share /sys/fs/cgroup. Allows elogind in container if
used with one of --init=openrc|runit|sysvinit
Container special configuration:
--env VAR=value Set custom environment variable VAR=value
--name NAME Specify container name NAME.
--no-entrypoint Disable ENTRYPOINT in image to allow other commands, too
--runtime RUNTIME Specify docker runtime. Known by x11docker:
runc: Docker default runtime.
crun: Fast replacement for runc written in C.
nvidia: Runtime for nvidia/nvidia-docker images.
kata-runtime: Runtime using a QEMU VM.
--shell SHELL Set preferred user shell. Example: --shell=/bin/zsh
--stdin Forward stdin of x11docker to container command.
--workdir DIR Set working directory DIR.
Additional commands: (You might need to move them to background with 'CMD &'.)
--runasroot CMD Run command CMD as root in container.
Caution: Runs with --privileged host access.
--runasuser CMD Run command CMD with user privileges in container
before running image command.
--runfromhost CMD Run host command CMD on new X server.
Miscellaneous:
--cachebasedir DIR Custom base folder for cache files.
--homebasedir DIR Custom base folder for option --home.
--enforce-i Run x11docker in interactive bash mode to allow tty
access. Can help to run weston-launch on special systems.
--fallback [yes|no] Allow or deny fallbacks if a chosen option cannot
be fulfilled. By default fallbacks are allowed.
--launcher Create application launcher with current options
on desktop and exit. You can get a menu entry moving
the created .desktop file to ~/.local/share/applications
--mobyvm Use MobyVM (for WSL2 only that defaults to linux Docker).
--preset FILE Read a set of predefined options stored in file FILE.
Useful to shortcut often used option combinations.
FILE is searched in directory /etc/x11docker/preset,
or in directory ~/.config/x11docker/preset or absolute.
Multiple lines in FILE are allowed.
Comment lines must begin with #
--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 without arg).
no: Do not run or ask for '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
Output of parseable information on stdout:
Get output e.g. with: read xenv < <(x11docker --showenv x11docker/check)
--showenv Print new \$DISPLAY, \$XAUTHORITY and \$WAYLAND_DISPLAY.
--showid Print container ID.
--showinfofile Print path to internal x11docker info storage file.
--showpid1 Print host PID of container PID 1.
Verbosity options:
-D, --debug Debug mode: Show some less verbose debug output
and enable rigorous error control.
-q, --quiet Suppress x11docker terminal messages.
-v, --verbose Be verbose. Output of x11docker.log on stderr.
-V Be verbose with colored output.
Installation options (need root permissions), license and cleanup:
--install Install x11docker and x11docker-gui from current folder.
Useful to install from an extracted zip file.
--update Download and install latest release from github.
--update-master Download and install latest master version from github.
--remove Remove x11docker from your system. Includes --cleanup.
Preserves ~/.local/share/x11docker from option --home.
--license Show license of x11docker (MIT) and exit.
--cleanup Clean up orphaned containers and cache files.
Terminates currently running x11docker containers, too.
Exit codes:
0: Success
64: x11docker error
130: Terminated by ctrl-c
other: Exit code of command in container
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, 2019, 2020, 2021 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" ] && [ "$Passwordterminal" != "eval" ] && [ -e "$Cachefolder" ] && {
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
} || {
warning "Could not display message on X:
$Message"
return 1
}
return 0
}
debugnote() { # show debug output $*
[ "$Debugmode" = "yes" ] && [ "$Verbose" = "no" ] && echo "${Colblue}DEBUGNOTE[$(timestamp)]:${Colnorm} $*" >&${FDstderr}
logentry "DEBUGNOTE[$(timestamp)]: $*"
return 0
}
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: $Logfilebackup
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
"
saygoodbye error
storeinfo test error && waitfortheend
storeinfo error=64
# output to X dialogbox if not running in terminal
[ "$Runsinterminal" = "no" ] && [ "$Silent" = "no" ] && export ${Hostxenv:-DISPLAY} && alertbox "x11docker ERROR" "$Message" &
finish
}
logentry() { # write into logfile
[ -e "$Logfile" ] && {
[ -n "$Logmessages" ] && echo "$Logmessages" >>$Messagelogfile 2>/dev/null && Logmessages=""
echo "$*" >>$Messagelogfile 2>/dev/null
:
} || Logmessages="$Logmessages
$*"
}
note() { # show notice messages
[ "$Verbose" = "no" ] && echo "${Colgreen}x11docker note:${Colnorm} $*
" >&${FDstderr}
logentry "x11docker note: $*
"
}
traperror() { # trap ERR: --debug: Output for 'set -o errtrace'
debugnote "traperror: Command at Line ${2:-} returned with error code ${1:-}:
${4:-}
${3:-} - ${5:-}"
storeinfo error=64
saygoodbye traperror
}
verbose() { # show verbose messages
# only logfile notes here, terminal output is done with tail in setup_verbosity()
logentry "x11docker[$(timestamp)]: $*
"
}
warning() { # show warning messages
[ "$Verbose" = "no" ] && echo "${Colyellow}x11docker WARNING:${Colnorm} $*
" >&${FDstderr}
logentry "x11docker WARNING: $*
"
}
watchmessagefifo() { # watch for messages coming from container or dockerrc
# message in fifo must end with :$Messagetype
local Line= Message= Messagetype=
trap '' SIGINT
while [ -e "$Cachefolder" ]; do
IFS= read -r Line <&${FDmessage} ||:
[ "$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)" ] && debugnote "$(tail -c +4 <<< "$Message")" || verbose "$Message" ;;
:STDOUT) echo "$Message" ;;
esac
Message=
Messagetype=
}
done
}
#### exit
finish() { # trap EXIT routine to clean up background processes and cache
local Pid Name Zeit Exitcode Pid1pid= Dockerlogspid= Dockerstopshellpid= Wmcontainerpid1= Watchmessagefifopid= i
# do not finish() in subshell, just give signal to all other processes and terminate subshell
[ "$$" = "$BASHPID" ] || {
saygoodbye finish-subshell
exit 0
}
debugnote "Terminating x11docker."
saygoodbye "finish"
trap - EXIT
trap - ERR
trap - SIGINT
# --pw=sudo: no password prompt here, rather fail ### FIXME
[ "$Sudo" ] && {
sudo -n echo 2>/dev/null && Sudo="sudo -n" || Sudo=""
}
while read -r Line ; do
Pid="$(echo $Line | awk '{print $1}')"
Name="$(echo $Line | awk '{print $2}')"
debugnote "finish(): Checking pid $Pid ($Name): $(pspid $Pid || echo '(already gone)')"
checkpid $Pid && {
case $Name in
watchmessagefifo)
Watchmessagefifopid="$Pid"
;;
dockerstopshell)
Dockerstopshellpid="$Pid"
;;
dockerlogs)
Dockerlogspid=$Pid
#[ "$Winsubsystem" ] && Dockerlogspid=""
;;
containerpid1)
Pid1pid="$Pid"
#[ "$Winsubsystem" ] && Pid1pid=""
termpid "$Pid1pid" "$Name" || Debugmode="yes"
# Give container time for graceful shutdown
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
mysleep $(awk "BEGIN { print $Count * 0.1 }")
debugnote "finish(): Waiting for container PID 1: $Pid1pid to terminate."
done
;;
wmcontainerpid1)
Wmcontainerpid1="$Pid"
#[ "$Winsubsystem" ] && Wmcontainerpid1=""
termpid "$Wmcontainerpid1" "$Name"
;;
*)
termpid "$Pid" "$Name"
;;
esac
}
done < <(tac "$Storepidfile" 2>/dev/null)
# --pulseaudio: unload module
Pulseaudiomoduleid="$(storeinfo dump pulseaudiomoduleid)"
[ "$Pulseaudiomoduleid" ] && pactl unload-module "$Pulseaudiomoduleid"
# Check if container is still running -> docker stop
[ "$X11dockermode" = "run" ] && containerisrunning && {
Debugmode="yes"
debugnote "finish(): Container still running. Executing 'docker stop'.
Will wait up to 15 seconds for docker to finish."
case $Mobyvm in
no) echo "stop" >> "$Dockerstopsignalfifo" ;;
yes) $Dockerexe stop $Containername >>$Containerlogfile 2>&1 ;;
esac
Zeit="$(date +%s)"
while :; do
containerisrunning || break
debugnote "finish(): Waiting for container to terminate ..."
sleep 1
[ 15 -lt $(($(date +%s) - $Zeit)) ] && break
done
containerisrunning && {
Exitcode="64"
debugnote "finish(): 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"
} || debugnote "finish(): Container terminated successfully"
}
# remove container
[ "$Preservecachefiles" = "no" ] && [ "$Containername" ] && {
debugnote "Removing container $Containername
$($Dockerexe rm -f "$Containername" 2>&1)"
}
# Check if 'docker logs' is still running
[ "$FDdockerstop" ] && {
checkpid $Dockerlogspid && echo "stop" >&${FDdockerstop}
# Check if window manager container is still running
checkpid $Wmcontainerpid1 && echo "stop" >&${FDdockerstop}
# Terminate watching subshell in dockerrc
[ -e "$Dockerstopsignalfifo" ] && echo "exit" >&${FDdockerstop}
checkpid $Dockerstopshellpid && sleep 1
}
# Stop watching for messages, check others again
while read -r Line ; do
Pid="$(echo $Line | awk '{print $1}')"
Name="$(echo $Line | awk '{print $2}')"
checkpid $Pid && termpid "$Pid" "$Name"
checkpid $Pid && {
# should never happen
warning "Failed to terminate pid $Pid ($Name): $(pspid $Pid ||:)"
storeinfo error=64
}
done < <(tac "$Storepidfile" 2>/dev/null)
Exitcode=$(storeinfo dump error)
Exitcode="${Exitcode:-0}"
debugnote "x11docker exit code: $Exitcode"
storeinfo test cmdexitcode && {
Exitcode=$(storeinfo dump cmdexitcode)
debugnote "CMD exit code: $Exitcode"
}
# backup of logfile in $Cachebasefolder
[ -e "$Logfile" ] && {
[ "$Verbose" = "yes" ] && sleep 1
unpriv "cp '$Logfile' '$Logfilebackup'"
case $Winsubsystem in
WSL1|WSL2)
[ "$Mobyvm" = "yes" ] && unpriv "cp -T '$Logfilebackup' '$Hostuserhome/.cache/x11docker/x11docker.log'"
;;
esac
#unpriv "rmcr '$Logfilebackup'"
}
# close file descriptors
mysleep 0.2
for Descriptor in ${FDcmdstdin} ${FDdockerstop} ${FDmessage} ${FDstderr} ${FDtimetosaygoodbye} ${FDwatchpid} ; do
exec {Descriptor}>&-
done
# remove cache files
[ "$Preservecachefiles" = "no" ] && grep -q cache <<<$Cachefolder && grep -q x11docker <<<$Cachefolder && [ "x11docker" != "$(basename "$Cachefolder")" ] && unpriv "rm -f -R '$Cachefolder'"
case $Runssourced in
yes) return $Exitcode ;;
*) exit $Exitcode ;;
esac
}
finish_sigint() { # trap SIGINT to activate debug mode on finish()
local Pid1pid
Debugmode="yes"
debugnote "Received SIGINT"
storeinfo error=130
finish
}
saygoodbye() { # create file signaling watching processes to terminate
debugnote "time to say goodbye ($*)"
[ -e "$Timetosaygoodbyefile" ] && echo timetosaygoodbye >> $Timetosaygoodbyefile
[ -e "$Timetosaygoodbyefifo" ] && echo timetosaygoodbye >> $Timetosaygoodbyefifo
}
#### watching processes
checkpid() { # check if PID $1 is active
#ps -p ${1:-} >/dev/null 2>&1
[ -e "/proc/${1:-NONSENSE}" ]
}
containerisrunning() { # check if container is running
storeinfo test containerid || return 1
case $Mobyvm in
no) checkpid "$(storeinfo dump pid1pid)" ;;
yes) $Dockerexe inspect "$(storeinfo dump containerid)" >/dev/null 2>&1 ;;
esac
}
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 ### FIXME
# return 1 if not found
LC_ALL=C ps -p "${1:-}" 2>/dev/null | grep -v 'TIME'
}
rocknroll() { # check whether x11docker session is still running
[ -s "$Timetosaygoodbyefile" ] && return 1
[ -e "$Timetosaygoodbyefile" ] || return 1
return 0
}
setonwatchpidlist() { # add PID $1 to watchpidlist()
debugnote "watchpidlist(): Setting pid ${1:-} on watchlist: ${2:-}"
echo "${1:-}" >>$Watchpidfifo
# add to list of background processes
grep -q CONTAINER <<< "${1:-}" || storepid "${1:-}" "${2:-}"
}
storepid() { # store pid $1 and name $2 of process in file $Storepidfile.
# Store pid and process name of background processes in a file
# Used in finish() to clean up background processes
# Store:
# $1 Pid
# $2 codename
# Test for stored pid or codename:
# $1 test
# $2 pid or codename
# Dump stored pid:
# $1 dump
# $2 codename
case "${1:-}" in
dump) grep -w "${2:-}" "$Storepidfile" | cut -d' ' -f1 ;;
test) grep -q -w "${2:-}" "$Storepidfile" ;;
*)
echo "${1:-NOPID}" "${2:-NONAME}" >> "$Storepidfile"
debugnote "storepid(): Stored pid '${1:-}' of '${2:-}': $(pspid ${1:-} ||:)"
;;
esac
}
termpid() { # kill PID $1 with codename $2
# TERM
debugnote "termpid(): Terminating ${1:-} (${2:-}): $(pspid ${1:-} ||:)"
checkpid "${1:-}" && {
kill ${1:-} 2>/dev/null
:
} || return 0
mysleep 0.1
checkpid "${1:-}" && mysleep 0.4 || return 0
# KILL
debugnote "termpid(): Killing ${1:-} (${2:-}): $(pspid ${1:-} ||:)"
checkpid "${1:-}" && kill -s KILL ${1:-} 2>/dev/null
mysleep 0.2
checkpid "${1:-}" && {
note "Failed to terminate ${1:-} (${2:-}): $(ps -u -p ${1:-} 2>/dev/null | tail -n1)"
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 $Usemkfifo in
yes)
while rocknroll; do
bash -c "read -n1 <${FDtimetosaygoodbye}" && saygoodbye timetosaygoodbyefifo || sleep 1
done
;;
no) # Reading from fifo fails on Windows, workaround
while rocknroll; do
sleep 2
done
;;
esac
return 0
}
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 >{FDwatchpid} (setonwatchpidlist())
local Pid= Containername= Line= Watchpidlist=
trap '' SIGINT
while rocknroll; do
# check for new Pid once a second
read -t1 Pid <&${FDwatchpid} ||:
[ "$Usemkfifo" = "no" ] && sleep 2 # read does not wait if not a fifo
# Got new pid
[ "$Pid" ] && {
[ "${Pid:0:9}" = "CONTAINER" ] && {
# Workaround for MS Windows where the pid cannot be watched
Containername="${Pid#CONTAINER}"
debugnote "watchpidlist(): Watching Container: $Containername"
} || {
Watchpidlist="$Watchpidlist $Pid"
debugnote "watchpidlist(): Watching pids:
$(for Line in $Watchpidlist; do pspid "$Line" || echo "(pid $Line not found)" ; done)"
}
}
# check all stored pids
for Pid in $Watchpidlist; do
[ -e /proc/$Pid ] || {
debugnote "watchpidlist(): PID $Pid has terminated"
saygoodbye "watchpidlist $Pid"
}
done
# Container PID not watchable in MSYS2/Cygwin/WSL11.
[ "$Containername" ] && {
$Dockerexe inspect $Containername >/dev/null 2>&1 || {
debugnote "watchpidlist(): Container $Containername has terminated"
saygoodbye "watchpidlist $Containername"
}
}
done
saygoodbye "watchpidlist"
}
#### more or less general routines
askyesno() { # ask Yes/no question. Default 'yes' for ENTER, timeout with 'no' after 60s
local Choice
read -t60 -n1 -p "(timeout after 60s assuming no) [Y|n]" Choice
[ "$?" = '0' ] && {
[[ "$Choice" == [YyJj]* ]] || [ -z "$Choice" ] && return 0
}
return 1
}
check_envvar() { # allow only chars in string $1 that can be exspected in environment variables
# Allows only chars in "a-zA-Z0-9_:/.,@=-"
# Option -w allows whitespace, too. Can be needed for PATH.
# Char * as in LS_COLORS is not allowed to avoid abuse.
# Replaces forbidden chars with X and returns 1
# Returns 0 if no change occured.
# Echoes result.
local Newvar Space=
case "${1:-}" in
-w) Space=" " ; shift ;;
esac
Newvar="$(printf %s "${1:-}" | LC_ALL=C tr -c "a-zA-Z0-9_:/.,@=${Space}-" "X" )"
printf %s "$Newvar"
printf "\n"
[ "$Newvar" = "${1:-}" ] && return 0
debugnote "check_envvar(): Input string has been changed. Result:
$Newvar"
return 1
}
check_parent_sshd() { # check whether pid $1 runs in SSH session
local Wanted_pid="${1:-}" Process_line
local Return
ps -p 1 >/dev/null 2>&1 || {
debugnote "check_parent_sshd(): 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
[ "$Return" ] && break
done
return ${Return:-1}
}
download() { # download file at URL $1 and store it in file $2
# Uses wget or curl. If both are missing, returns 1.
# With no arguments it checks for curl/wget without downloading.
# Download follows redirects.
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
}
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; '
}
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)}')" ]
}
makecookie() { # bake a cookie
mcookie 2>/dev/null || echo $RANDOM$RANDOM$RANDOM$RANDOM$RANDOM$RANDOM | cut -b1-32
}
mysleep() { # catch cases where sleep only supports integer
sleep "${1:-1}" 2>/dev/null || sleep 1
}
storeinfo() { # store some information for later use
# store and provide pieces of information
# replace entry if codeword is already present
# Store as codeword=string:
# $1 codeword=string
# Dump stored string:
# $1 dump
# #2 codeword
# Drop stored string:
# $1 drop
# #2 codeword
# Test for codeword: (return 1 if not found)
# $1 test
# $2 codeword
#
# note: sed -i causes file permission issues if called in container in Cygwin, compare ticket #187
# chmod 666 for $Sharefolder could probably fix that. (FIXME)
#
[ -e "$Storeinfofile" ] || return 1
case "${1:-}" in
dump) grep "^${2:-}=" $Storeinfofile | sed "s/^${2:-}=//" ;; # dump entry
drop) sed -i "/^${2:-}=/d" $Storeinfofile ;; # drop entry
test) grep -q "^${2:-}=" $Storeinfofile ;; # test for entry
*) # store entry
debugnote "storeinfo(): ${1:-}"
grep -q "^$(echo "${1:-}" | cut -d= -f1)=" $Storeinfofile && {
sed -i "/^$(echo "${1:-}" | cut -d= -f1)=/d" $Storeinfofile # drop possible old entry
}
echo "${1:-}" >> $Storeinfofile
;;
esac
}
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
}
timestamp() { # print HH:MM:SS,NNN
date +%T,%N | cut -c1-12
}
unspecialstring() { # replace special chars of $1 with -
# Replace all characters except those described in "a-zA-Z0-9_" with a '-'.
# Replace newlines, too.
# Remove leading and trailing '-'
# Avoid double '--'
# Return empty string if only special chars are given.
printf %s "${1:-}" | LC_ALL=C tr -cs "a-zA-Z0-9_" "-" | sed -e 's/^-// ; s/-$//'
}
verlt() { # version number check $1 less than $2
[ "${1:-}" = "${2:-}" ] && return 1 || { verlte "${1:-}" "${2:-}" && return 0 || return 1 ; }
}
verlte() { # version number check $1 less than or equal $2
[ "${1:-}" = "$(echo -e "${1:-}\n${2:-}" | sort -V | head -n1)" ] && return 0 || return 1
}
wincmd() { # execute a command on MS Windows with cmd.exe
MSYS2_ARG_CONV_EXCL='*' cmd.exe /C "${@//&/^&}" | rmcr
}
#### file routines
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 or /mnt/c/path
# volume echo --volume compatible syntax - result: 'unixpath':'containerpath':rw (or ":ro")
# container echo path of volume in container - result: /path
# share echo path of $Sharefolder/file in container - result: /containerpath
# $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 mode 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"
# replace ~ with HOME
Path="$(sed s%"~"%"${Hostuserhome:-${HOME:-}}"% <<< "$Path")"
# share: Replace $Sharefolder with $Sharefoldercontainer
[ "$Mode" = "share" ] && {
[ -z "$Path" ] && echo "" && return 0
case $X11dockermode in
run) echo "${Sharefoldercontainer}${Path#$Sharefolder}" ;;
exe) echo "$Path" ;;
esac
return 0
}