-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathx11docker
executable file
·11640 lines (10728 loc) · 446 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="7.6.1-beta"
Packagedversion="no" # Set to "yes" if you want to package x11docker. This disables installation options.
# --enforce-i: Enforce running in interactive mode to allow commands tty and weston-launch in special setups. (deprecated)
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 containers.
Supports docker, podman, and (experimental) nerdctl.
Can run X servers from host or in containers of x11docker/xserver.
Can also provide X servers to host applications.
Usage:
To run a container on a new X server:
x11docker IMAGE
x11docker [OPTIONS] IMAGE [COMMAND]
x11docker [OPTIONS] -- IMAGE [COMMAND [ARG1 ARG2 ...]]
x11docker [OPTIONS] -- CUSTOM_RUN_OPTIONS -- IMAGE [COMMAND [ARG1 ARG2 ...]]
To run a host application on a new X server:
x11docker [OPTIONS] --backend=host COMMAND
x11docker [OPTIONS] --backend=host -- COMMAND [ARG1 ARG2 ...]
x11docker [OPTIONS] --backend=host -- -- COMMAND [ARG1 ARG2 ...] -- [ARG3]
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 and backends
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.
To switch between docker, podman and nerdctl use option --backend.
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 or --sudouser.
Dependencies on host:
For core functionality x11docker only needs bash, an X server and one of
docker, podman or nerdctl.
Depending on chosen options x11docker might need some additional tools.
It checks for them on startup and shows messages if some are missing.
* Most recommended: Provide image x11docker/xserver to run X or Wayland
in container. The image contains all X related dependencies.
Otherwise provide on host:
* Recommended to allow security and convenience:
X servers: xpra Xephyr nxagent Xorg
X tools: xauth xclip xrandr xhost xinit
* Additional for 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.
--license Show license of x11docker (MIT) and exit.
--version Show x11docker version and exit.
Basic settings:
-d, --desktop Indicate a desktop environment in image.
-i, --interactive Run with an interactive tty to allow shell commands.
Useful with commands like bash.
--backend=BACKEND Container backend to use. BACKEND can be:
docker (recommended for rootful) (default)
podman (recommended for rootless and rootful)
nerdctl (experimental)
host Run a host application, no container.
--rootless [=yes|no] Use (or disallow) rootless backend.
Default behaviour without option --rootless:
--backend=docker: rootful unless DOCKER_HOST is set.
--backend=podman: rootless except started as root.
--backend=nerdctl: rootless except started as root
--xc [=yes|no|BACKEND] Run X server in container of x11docker/xserver.
BACKEND can specify one of docker|podman|nerdctl.
--xonly Only start empty X server.
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 [=yes|no|oneway|superv|altv] Share clipboard with host.
Possible arguments:
yes: Share clipboard in both directions.
Includes middle-mouse-click selection.
oneway: Copy clipboard from container to host only.
Includes middle-mouse-click selection.
superv: Keys [SUPER][v] copy clipboard from host to
container. Does not copy middle-mouse-click
to container. Otherwise same as 'oneway'.
altv: Same as 'superv' but using keys [ALT][v].
no: Do not share clipboard.
-g, --gpu [=yes|no|iglx|virgl] GPU access for hardware accelerated OpenGL.
Works best with open source drivers on host and in image.
For closed source nvidia drivers regard terminal output.
Direct rendering supported by few X server options only.
Arg 'iglx' enables indirect rendering (--xorg only).
Arg 'virgl' allows GPU access for all X servers, but
with limited performance and with --xc only.
-I, --network [=NET] Allow internet access. (i.e. allow Docker default.)
For optional argument NET see Docker documentation of
docker run option --network. Docker default is bridge.
-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', 'tcp'
or 'host'. tcp mode needs network access with --network.
--webcam Share host webcam device files.
Shared host folders or volumes:
-m, --home [=ARG] Create a persistent HOME folder for data storage.
Default: Uses ~/.local/share/x11docker/IMAGENAME.
ARG can be another host folder or a 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 volume instead of a host folder.
X server options:
--auto Automatically choose X server (default). Influenced
notably by options --desktop, --gpu, --wayland, --wm.
-h, --hostdisplay Share host display :0. Quite bad container isolation!
Least overhead of all X server options.
-a, --xpra Nested X server supporting seamless and --desktop mode.
--xpra2 Like --xpra --xc, but runs xpra client on host.
-A, --xpra-xwayland Like --xpra, but supports option --gpu.
--xpra2-xwayland Like --xpra2, but supports option --gpu.
-n, --nxagent Nested X server supporting seamless and --desktop mode.
Faster than --xpra, but can have compositing issues.
-y, --xephyr Nested X server for --desktop mode. Without --desktop
a host window manager will be provided (option --wm).
-Y, --weston-xwayland Desktop mode like --xephyr, but supports option --gpu.
Runs from console, within X and within Wayland.
-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.
Special X server options:
-t, --tty Terminal only mode. Does not run an X or Wayland server.
--xvfb Invisible X server using Xvfb.
Can be used for custom access with xpra or VNC.
-X, --xwayland Blanc Xwayland, needs a running Wayland compositor.
--xwin X server to run in Cygwin/X on MS Windows.
--runx X server wrapper for VcXsrv and Xwin 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 or KWin.
--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* and --xorg: 0.25...8.0.
Allowed for --weston and --weston-xwayland: 1...9.
--size=WxH Screen size of new X server (e.g. 800x600).
-w, --wm [=ARG] Provide a host window manager to container applications.
Possible ARG:
host: autodetection of a host window manager.
COMMAND: command of a desired host window manager.
none: Run without a window manager. Same as --desktop.
-F, --xfishtank Show fish tank on new X server.
X and Wayland special configuration:
--checkwindow [=ARG] Run container until all X windows are closed.
If ARG is provided, run container as long as 'grep' can
find ARG in output of 'xwininfo -root -children'.
This option helps to keep alive containers with
self-forking applications like gnome-terminal
or to stop endless running ones like chromium.
--clean-xhost Disable xhost access policies on host display.
--composite [=yes|no] Enable or disable X extension Composite.
Default is yes except for --nxagent. Can cause or
fix issues with some applications on nxagent.
--display=N Use display number N for new X server.
--keymap=LAYOUT Set keyboard layout for new X server, e.g. de, us, ru.
For possible LAYOUT look at /usr/share/X11/xkb/symbols.
--vt [=N] Use vt / tty N. Without N search an unused tty.
--westonini=FILE Custom weston.ini for --weston and --weston-xwayland.
--xhost [=STR] Set \"xhost STR\" on new X server (see 'man xhost').
Without STR will set: +SI:localuser:\$USER
(Use with care. '--xhost=+' allows access for everyone).
--xoverip [=yes|no|listentcp|socat] Connect to X over TCP network. Special
setups only, usually only enabled by x11docker itself.
yes: Use listentcp if possible, otherwise socat.
no: Use shared unix socket (default).
listentcp: Use X option '-listen tcp'.
socat: Use socat to create a fake TCP connection.
--xauth [=yes|trusted|untrusted|no] Configure X cookie authentication.
Possible arguments:
yes|trusted: Enable cookie authentication with trusted
cookies. (General x11docker default.)
untrusted: Untrusted cookie for untrusted apps
limiting access to X resources.
Useful to avoid MIT-SHM with --hostdisplay.
no: Disable cookie authentication. Dangerous!
--xtest [=yes|no] Enable or disable X extension XTEST. Default is yes for
--xpra and --xvfb, no for other X servers.
Needed to allow keyboard and mouse control 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 container capabilities.
Includes --newprivileges=yes.
--ipc [=ARG] Without ARG sets run option --ipc=host. (Discouraged)
For other possible ARG see docker run reference.
--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 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. x11docker might as well use
catatonit provided by podman.
systemd: systemd in container.
sysvinit: sysvinit in container.
runit: runit in container
openrc: openrc in container
s6-overlay: s6-overlay in container.
none: No init system, CMD will be PID 1.
--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
--no-setup No x11docker setup in running container. Disallows
several other options. See also --user=RETAIN.
--runtime=RUNTIME Specify container runtime. Known by x11docker:
runc: Docker default runtime.
crun: Fast replacement for runc written in C.
nvidia: Runtime for nvidia/nvidia-docker images.
sysbox-runc: Runtime for powerful root in container.
--shell=SHELL Set preferred user shell. Example: --shell=/bin/zsh
--snap Enable support for Docker in snap.
--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.
--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:
--build IMAGE Build an image from a Dockerfile from x11docker
repository. Example: 'x11docker --build x11docker/fvwm'
Works for all repositories beginning with 'dockerfile'
at https://github.com/mviereck?tab=repositories
Regards (only) option --backend=BACKEND.
--cachebasedir=DIR Custom base folder for cache files.
--homebasedir=DIR Custom base folder for option --home.
--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.
- Multiple lines in FILE are allowed.
- Comment lines must begin with #
- Local presets supersede global ones in /etc
Special case: A preset file with file name 'default'
will be applied automatically for all x11docker sessions.
Output of parseable information on stdout:
Get output e.g. with: read xenv < <(x11docker --printenv x11docker/check)
Optional argument FILE allows to print the information into a file.
--printenv [=FILE] Print variables to access new display.
--printid [=FILE] Print container ID.
--printinfofile [=FILE] Print path to internal x11docker info storage.
--printpid1 [=FILE] Print host PID of container PID 1.
Verbosity options:
-D, --debug Debug mode: Show some less verbose debug output
and enable rigorous error control.
--printcheck Show dependency check messages.
-q, --quiet Suppress x11docker terminal messages.
-v, --verbose Be verbose. Output of x11docker.log on stderr.
-V Be verbose with colored output.
Cleanup options (might need root permissions):
--cleanup Clean up orphaned containers and cache files. Those
can remain if x11docker still runs on system shutdown.
Terminates currently running x11docker containers, too.
Regards (only) option --backend=BACKEND."
case "$Packagedversion" in
yes) ;;
*)
echo "
Installation options (need root permissions):
--install Install x11docker from current folder.
Useful to install from an extracted zip file.
--update [=diff] Download and install latest release from github.
--update-master [=diff] Download and install latest master version.
Optional argument 'diff' shows the difference between
installed and new version without installing it.
--remove Remove x11docker from your system. Includes --cleanup.
Preserves ~/.local/share/x11docker from option --home.
--remove-oldprefix Before version 7.6.0 x11docker installed itself
into /usr/bin. Now it installs into /usr/local/bin.
Use --remove-oldprefix to remove /usr/bin installations."
;;
esac
echo "
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, 2022 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 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" ||:
}
} || {
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" != "yes" ] && echo "${Colblue}DEBUGNOTE[$(timestamp)]:${Colnorm} $*" >&${FDstderr}
logentry "DEBUGNOTE[$(timestamp)]: $*"
return 0
}
error() { # show error message and exit
local Message
break >/dev/null 2>&1 # just in case error occurred in a loop
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
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" = "yes" ] || 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" = "yes" ] || echo "${Colyellow}x11docker WARNING:${Colnorm} $*
" >&${FDstderr}
logentry "x11docker WARNING: $*
"
}
watchmessagefifo() { # watch for messages coming from inside of container
# 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 | tr -d ' ')"
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= Watchmessagefifopid= Count Xpid1pid
# 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
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) ;;
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
checkpid "$Pid1pid" && unpriv_backend "$Backendbin stop $Containername"
;;
Xcontainerpid1)
Xpid1pid="$Pid"
#[ "$Winsubsystem" ] && Pid1pid=""
termpid "$Xpid1pid" "$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 "$Xpid1pid" || break
mysleep "$(awk "BEGIN { print $Count * 0.1 }")"
debugnote "finish(): Waiting for X container PID 1: $Xpid1pid to terminate."
done
checkpid "$Xpid1pid" && unpriv_xcbackend "$Xcontainerbackend stop $Xcontainername"
;;
*)
termpid "$Pid" "$Name"
;;
esac
}
done < <(tac "$Storepidfile" 2>/dev/null)
# --pulseaudio: unload module
Pulseaudiomoduleid="$(storeinfo dump pulseaudiomoduleid)"
[ "$Pulseaudiomoduleid" ] && unpriv "pactl unload-module '$Pulseaudiomoduleid'"
# --xc --xoverip: remove possible internal network
setup_xcnetwork remove
# Check if container is still running -> docker stop
case "$Backend" in
docker|podman|nerdctl)
containerisrunning && {
Debugmode="yes"
debugnote "finish(): Container still running. Executing 'docker stop'.
Will wait up to 15 seconds for docker to finish."
unpriv_backend "$Backendbin stop $Containername" >> "$Containerlogfile" 2>&1
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"
} || debugnote "finish(): Container terminated successfully"
}
;;
esac
# 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" ] && 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'"
}
# softlink to X unix socket in container
case "$Xcontainer" in
yes)
[ -L "/tmp/.X11-unix/X$Newdisplaynumber" ] && rm "/tmp/.X11-unix/X$Newdisplaynumber"
[ -L "$XDG_RUNTIME_DIR/wayland-$Newdisplaynumber" ] && rm "$XDG_RUNTIME_DIR/wayland-$Newdisplaynumber"
;;
esac
# close file descriptors
mysleep 0.2
for Descriptor in ${FDcmdstdin} ${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 X11dockerpid
X11dockerpid="$(storeinfo dump x11dockerpid)"
Debugmode="yes"
[ "$$" = "$X11dockerpid" ] && {
debugnote "Received SIGINT"
storeinfo error=130
finish
:
} || {
debugnote "Received SIGINT in subshell $SHLVL: $$"
kill -s SIGINT "$X11dockerpid"
trap - EXIT
exit 130
}
}
saygoodbye() { # create file signaling watching processes to terminate
debugnote "time to say goodbye ($*)"
[ -e "$Timetosaygoodbyefile" ] && echo timetosaygoodbye >> "$Timetosaygoodbyefile"
[ -e "$Timetosaygoodbyefifo" ] && echo timetosaygoodbye >> "$Timetosaygoodbyefifo"
return 0
}
#### 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) unpriv_backend "$Backendbin 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/WSL1.
[ "$Containername" ] && {
unpriv_backend "$Backendbin inspect '$Containername'" >/dev/null || {
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 expected 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 occurred.
# 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}"
}
cookiebaker() { # create an X cookie without xauth
# $1 DISPLAY
# Write directly to file, bash cannot store nullbytes in a string.
# Based on https://stackoverflow.com/questions/70932880/what-is-the-internal-format-of-xauthority-file
# and chapter 6.2.5 in https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Desktop-generic/LSB-Desktop-generic/libx11-ddefs.html
local Display
local Address Addresslength Displaynumber Displaynumberlength Data Part Code
Display="${1:-$DISPLAY}"
Address="$(printf "%s" "$Display" | cut -d: -f1)"
case "$Address" in
"")
Address="$(hostname)/unix"
Addresslength="$(strlenhex "$Address")"
;;
*.*.*.*)
Data="$Address"
Address=""
while [ "$(printf "%s" "$Data" | wc -c)" -gt 0 ]; do
Part="$( printf "%s" "$Data" | cut -d. -f1)"
Address="${Address}\x$(printf "%x" "$Part")"
Data="$( printf "%s" "$Data" | cut -s -d. -f2-)"
done
Addresslength="4"
;;
*)
Addresslength="$(strlenhex "$Address")"
;;
esac
Displaynumber="$(printf "%s" "$Display" | cut -d: -f2)"
Displaynumber="$(printf "%s" "$Displaynumber" | cut -d. -f1)"
Displaynumberlength="$(strlenhex "$Displaynumber")"
Data="$(makecookie)"
while [ "$(printf "%s" "$Data" | wc -c)" -gt 0 ]; do
Part="$( printf "%s" "$Data" | cut -c1-2)"
Code="${Code}\x$Part"
Data="$( printf "%s" "$Data" | cut -c3-)"
done
awk "BEGIN{
printf \"\xFF\xFF\"
printf \"\x00\x${Addresslength}\"
printf \"${Address}\"
printf \"\x00\x${Displaynumberlength}\"
printf \"${Displaynumber}\"
printf \"\x00\x12\"
printf \"MIT-MAGIC-COOKIE-1\"
printf \"\x00\x10\"
printf \"${Code}\"
}"
}
devicelist_gpu() { # print list of GPU devices
find /dev/dri/* /dev/nvidia* /dev/vga_arbiter /dev/nvhost* /dev/nvmap -maxdepth 0 -type c 2>/dev/null ||:
}
devicelist_input() { # print list of input devices
find /dev/input/* -maxdepth 0 -type c 2>/dev/null ||:
}
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:-}" || return 1;;
curl) curl -L "${1:-}" --fail --output "${2:-}" || return 1;;
esac
return $?
}
escapestring() { # escape special chars of $1
# escape all characters except those described in [^a-zA-Z0-9,._+@=:/-]
grep -q "'" <<< "${1:-}" && {
error "escapestring(): x11docker cannot escape char ' in :
${1:-}"
return 1
}