blob: bb4f2febf9a9c0029f491864a1e3e7d8bc9954ff [file] [log] [blame]
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +00001#!/usr/bin/env perl
2#
DRCb9d8e762011-02-09 08:24:58 +00003# Copyright (C) 2009-2010 D. R. Commander. All Rights Reserved.
DRC190854c2009-03-26 18:13:00 +00004# Copyright (C) 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
5# Copyright (C) 2002-2003 Constantin Kaplinsky. All Rights Reserved.
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +00006# Copyright (C) 2002-2005 RealVNC Ltd.
7# Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
8#
9# This is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This software is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this software; if not, write to the Free Software
21# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
22# USA.
23#
24
25#
26# vncserver - wrapper script to start an X VNC server.
27#
28
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000029# First make sure we're operating in a sane environment.
DRC190854c2009-03-26 18:13:00 +000030$exedir = "";
31$slashndx = rindex($0, "/");
32if($slashndx>=0) {
33 $exedir = substr($0, 0, $slashndx+1);
34}
35
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000036&SanityCheck();
37
38#
Jeff Blaine8a9abc12016-08-06 16:22:18 -040039# Global variables. You may want to configure some of these for
40# your site
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000041#
42
43$geometry = "1024x768";
DRC9d1c1572009-03-26 18:18:51 +000044#$depth = 16;
Koichiro IWAO977fbde2016-10-03 18:07:57 +090045
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000046$vncUserDir = "$ENV{HOME}/.vnc";
Jeff Blaine8a9abc12016-08-06 16:22:18 -040047$vncUserConfig = "$vncUserDir/config";
48
49$vncSystemConfigDir = "/etc/tigervnc";
50$vncSystemConfigDefaultsFile = "$vncSystemConfigDir/vncserver-config-defaults";
51$vncSystemConfigMandatoryFile = "$vncSystemConfigDir/vncserver-config-mandatory";
52
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +020053$skipxstartup = 0;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000054$xauthorityFile = "$ENV{XAUTHORITY}" || "$ENV{HOME}/.Xauthority";
55
Jeff Blaine8a9abc12016-08-06 16:22:18 -040056$xstartupFile = $vncUserDir . "/xstartup";
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000057$defaultXStartup
58 = ("#!/bin/sh\n\n".
DRC93248982009-03-26 18:14:38 +000059 "unset SESSION_MANAGER\n".
Adam Tkacc071e492009-05-20 09:01:24 +000060 "unset DBUS_SESSION_BUS_ADDRESS\n".
DRC93248982009-03-26 18:14:38 +000061 "OS=`uname -s`\n".
62 "if [ \$OS = 'Linux' ]; then\n".
63 " case \"\$WINDOWMANAGER\" in\n".
64 " \*gnome\*)\n".
65 " if [ -e /etc/SuSE-release ]; then\n".
66 " PATH=\$PATH:/opt/gnome/bin\n".
67 " export PATH\n".
68 " fi\n".
69 " ;;\n".
70 " esac\n".
71 "fi\n".
72 "if [ -x /etc/X11/xinit/xinitrc ]; then\n".
73 " exec /etc/X11/xinit/xinitrc\n".
74 "fi\n".
75 "if [ -f /etc/X11/xinit/xinitrc ]; then\n".
76 " exec sh /etc/X11/xinit/xinitrc\n".
77 "fi\n".
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000078 "[ -r \$HOME/.Xresources ] && xrdb \$HOME/.Xresources\n".
79 "xsetroot -solid grey\n".
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000080 "xterm -geometry 80x24+10+10 -ls -title \"\$VNCDESKTOP Desktop\" &\n".
81 "twm &\n");
82
grayskyddff8d02015-10-19 08:24:14 -040083$defaultConfig
84 = ("## Supported server options to pass to vncserver upon invocation can be listed\n".
85 "## in this file. See the following manpages for more: vncserver(1) Xvnc(1).\n".
86 "## Several common ones are shown below. Uncomment and modify to your liking.\n".
87 "##\n".
88 "# securitytypes=vncauth,tlsvnc\n".
89 "# desktop=sandbox\n".
90 "# geometry=2000x1200\n".
91 "# localhost\n".
92 "# alwaysshared\n");
93
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000094chop($host = `uname -n`);
95
DRC989dbd12009-04-22 13:23:17 +000096if (-d "/etc/X11/fontpath.d") {
97 $fontPath = "catalogue:/etc/X11/fontpath.d";
98}
DRC36546c12009-04-15 06:47:23 +000099
DRCd6821bf2009-03-26 18:17:49 +0000100@fontpaths = ('/usr/share/X11/fonts', '/usr/share/fonts', '/usr/share/fonts/X11/');
101if (! -l "/usr/lib/X11") {push(@fontpaths, '/usr/lib/X11/fonts');}
102if (! -l "/usr/X11") {push(@fontpaths, '/usr/X11/lib/X11/fonts');}
103if (! -l "/usr/X11R6") {push(@fontpaths, '/usr/X11R6/lib/X11/fonts');}
104push(@fontpaths, '/usr/share/fonts/default');
105
106@fonttypes = ('misc',
107 '75dpi',
108 '100dpi',
109 'Speedo',
110 'Type1');
111
112foreach $_fpath (@fontpaths) {
113 foreach $_ftype (@fonttypes) {
114 if (-f "$_fpath/$_ftype/fonts.dir") {
115 if (! -l "$_fpath/$_ftype") {
DRC36546c12009-04-15 06:47:23 +0000116 $defFontPath .= "$_fpath/$_ftype,";
DRCd6821bf2009-03-26 18:17:49 +0000117 }
118 }
119 }
120}
DRCd28792b2010-01-11 20:53:00 +0000121
DRC36546c12009-04-15 06:47:23 +0000122if ($defFontPath) {
123 if (substr($defFontPath, -1, 1) == ',') {
124 chop $defFontPath;
DRCd6821bf2009-03-26 18:17:49 +0000125 }
126}
127
DRCd28792b2010-01-11 20:53:00 +0000128if ($fontPath eq "") {
129 $fontPath = $defFontPath;
130}
131
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000132# Check command line options
133
134&ParseOptions("-geometry",1,"-depth",1,"-pixelformat",1,"-name",1,"-kill",1,
Llorenç Garcia Martineze76c2fb2015-10-30 11:07:40 +0100135 "-help",0,"-h",0,"--help",0,"-fp",1,"-list",0,"-fg",0,"-autokill",0,"-noxstartup",0,"-xstartup",1);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000136
137&Usage() if ($opt{'-help'} || $opt{'-h'} || $opt{'--help'});
138
139&Kill() if ($opt{'-kill'});
140
DRCb9d8e762011-02-09 08:24:58 +0000141&List() if ($opt{'-list'});
142
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000143# Uncomment this line if you want default geometry, depth and pixelformat
144# to match the current X display:
145# &GetXDisplayDefaults();
146
147if ($opt{'-geometry'}) {
148 $geometry = $opt{'-geometry'};
149}
150if ($opt{'-depth'}) {
151 $depth = $opt{'-depth'};
152 $pixelformat = "";
153}
154if ($opt{'-pixelformat'}) {
155 $pixelformat = $opt{'-pixelformat'};
156}
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200157if ($opt{'-noxstartup'}) {
158 $skipxstartup = 1;
159}
Llorenç Garcia Martineze76c2fb2015-10-30 11:07:40 +0100160if ($opt{'-xstartup'}) {
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400161 $xstartupFile = $opt{'-xstartup'};
Llorenç Garcia Martineze76c2fb2015-10-30 11:07:40 +0100162}
DRCeed5d1f2009-03-26 19:16:19 +0000163if ($opt{'-fp'}) {
164 $fontPath = $opt{'-fp'};
DRC36546c12009-04-15 06:47:23 +0000165 $fpArgSpecified = 1;
DRCeed5d1f2009-03-26 19:16:19 +0000166}
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000167
168&CheckGeometryAndDepth();
169
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000170# Create the user's vnc directory if necessary.
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000171if (!(-e $vncUserDir)) {
172 if (!mkdir($vncUserDir,0755)) {
173 die "$prog: Could not create $vncUserDir.\n";
174 }
175}
Koichiro IWAO977fbde2016-10-03 18:07:57 +0900176
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400177# Find display number.
178if ((@ARGV > 0) && ($ARGV[0] =~ /^:(\d+)$/)) {
179 $displayNumber = $1;
180 shift(@ARGV);
181 if (!&CheckDisplayNumber($displayNumber)) {
182 die "A VNC server is already running as :$displayNumber\n";
183 }
184} elsif ((@ARGV > 0) && ($ARGV[0] !~ /^-/) && ($ARGV[0] !~ /^\+/)) {
185 &Usage();
186} else {
187 $displayNumber = &GetDisplayNumber();
188}
189
190$vncPort = 5900 + $displayNumber;
191
192if ($opt{'-name'}) {
193 $desktopName = $opt{'-name'};
194} else {
195 $desktopName = "$host:$displayNumber ($ENV{USER})";
196}
197
198my %default_opts;
199my %config;
200
201# We set some reasonable defaults. Config file settings
202# override these where present.
203$default_opts{desktop} = &quotedString($desktopName);
Oliver Gondža2d614c02018-02-08 17:12:11 +0100204$default_opts{auth} = &quotedString($xauthorityFile);
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400205$default_opts{geometry} = $geometry if ($geometry);
206$default_opts{depth} = $depth if ($depth);
207$default_opts{pixelformat} = $pixelformat if ($pixelformat);
208$default_opts{rfbwait} = 30000;
209$default_opts{rfbauth} = "$vncUserDir/passwd";
210$default_opts{rfbport} = $vncPort;
211$default_opts{fp} = $fontPath if ($fontPath);
212$default_opts{pn} = "";
213
214# Load user-overrideable system defaults
215LoadConfig($vncSystemConfigDefaultsFile);
216
217# Then the user's settings
218LoadConfig($vncUserConfig);
219
220# And then override anything set above if mandatory settings exist.
221# WARNING: "Mandatory" is used loosely here! As the man page says,
222# there is nothing stopping someone from EASILY subverting the
223# settings in $vncSystemConfigMandatoryFile by simply passing
224# CLI args to vncserver, which trump config files! To properly
225# hard force policy in a non-subvertible way would require major
226# development work that touches Xvnc itself.
227LoadConfig($vncSystemConfigMandatoryFile, 1);
228
229#
Adam Tkacf586b842011-04-27 11:20:18 +0000230# Check whether VNC authentication is enabled, and if so, prompt the user to
231# create a VNC password if they don't already have one.
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400232#
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000233
Adam Tkacf586b842011-04-27 11:20:18 +0000234$securityTypeArgSpecified = 0;
235$vncAuthEnabled = 0;
236$passwordArgSpecified = 0;
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400237@vncAuthStrings = ("vncauth", "tlsvnc", "x509vnc");
Adam Tkacf586b842011-04-27 11:20:18 +0000238
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400239# ...first we check our configuration files' settings
240if ($config{'securitytypes'}) {
241 $securityTypeArgSpecified = 1;
242 foreach $arg2 (split(',', $config{'securitytypes'})) {
243 if (grep {$_ eq lc($arg2)} @vncAuthStrings) {
244 $vncAuthEnabled = 1;
245 }
246 }
247}
248
249# ...and finally we check CLI args, which in the case of the topic at
250# hand (VNC auth or not), override anything found in configuration files
251# (even so-called "mandatory" settings).
Adam Tkacf586b842011-04-27 11:20:18 +0000252for ($i = 0; $i < @ARGV; ++$i) {
253 # -SecurityTypes can be followed by a space or "="
254 my @splitargs = split('=', $ARGV[$i]);
255 if (@splitargs <= 1 && $i < @ARGV - 1) {
256 push(@splitargs, $ARGV[$i + 1]);
257 }
258 if (lc(@splitargs[0]) eq "-securitytypes") {
259 if (@splitargs > 1) {
260 $securityTypeArgSpecified = 1;
261 }
262 foreach $arg2 (split(',', @splitargs[1])) {
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400263 if (grep {$_ eq lc($arg2)} @vncAuthStrings) {
Adam Tkacf586b842011-04-27 11:20:18 +0000264 $vncAuthEnabled = 1;
265 }
266 }
267 }
268 if ((lc(@splitargs[0]) eq "-password")
269 || (lc(@splitargs[0]) eq "-passwordfile"
270 || (lc(@splitargs[0]) eq "-rfbauth"))) {
271 $passwordArgSpecified = 1;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000272 }
273}
274
Adam Tkacf586b842011-04-27 11:20:18 +0000275if ((!$securityTypeArgSpecified || $vncAuthEnabled) && !$passwordArgSpecified) {
276 ($z,$z,$mode) = stat("$vncUserDir/passwd");
277 if (!(-e "$vncUserDir/passwd") || ($mode & 077)) {
278 warn "\nYou will require a password to access your desktops.\n\n";
279 system($exedir."vncpasswd -q $vncUserDir/passwd");
280 if (($? >> 8) != 0) {
281 exit 1;
282 }
283 }
284}
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000285
286$desktopLog = "$vncUserDir/$host:$displayNumber.log";
287unlink($desktopLog);
288
Pierre Ossman5fe60702015-12-29 14:27:07 +0100289# Make an X server cookie and set up the Xauthority file
Koichiro IWAO31cad942016-10-04 17:17:06 +0900290# mcookie is a part of util-linux, usually only GNU/Linux systems have it.
Pierre Ossman5fe60702015-12-29 14:27:07 +0100291$cookie = `mcookie`;
Koichiro IWAO31cad942016-10-04 17:17:06 +0900292# Fallback for non GNU/Linux OS - use /dev/urandom on systems that have it,
293# otherwise use perl's random number generator, seeded with the sum
294# of the current time, our PID and part of the encrypted form of the password.
295if ($cookie eq "" && open(URANDOM, '<', '/dev/urandom')) {
296 my $randata;
297 if (sysread(URANDOM, $randata, 16) == 16) {
298 $cookie = unpack 'h*', $randata;
299 }
300 close(URANDOM);
301}
302if ($cookie eq "") {
303 srand(time+$$+unpack("L",`cat $vncUserDir/passwd`));
304 for (1..16) {
305 $cookie .= sprintf("%02x", int(rand(256)) % 256);
306 }
307}
Adam Tkac6cbd9d12009-11-12 10:39:54 +0000308
Pierre Ossmancddd6482015-12-29 14:30:32 +0100309open(XAUTH, "|xauth -f $xauthorityFile source -");
310print XAUTH "add $host:$displayNumber . $cookie\n";
311print XAUTH "add $host/unix:$displayNumber . $cookie\n";
312close(XAUTH);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000313
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000314# Now start the X VNC Server
315
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400316# We build up our Xvnc command with options
DRC190854c2009-03-26 18:13:00 +0000317$cmd = $exedir."Xvnc :$displayNumber";
grayskyddff8d02015-10-19 08:24:14 -0400318
grayskyddff8d02015-10-19 08:24:14 -0400319foreach my $k (sort keys %config) {
320 $cmd .= " -$k $config{$k}";
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400321 delete $default_opts{$k}; # file options take precedence
grayskyddff8d02015-10-19 08:24:14 -0400322}
323
324foreach my $k (sort keys %default_opts) {
325 $cmd .= " -$k $default_opts{$k}";
326}
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000327
DRCd6821bf2009-03-26 18:17:49 +0000328# Add color database stuff here, e.g.:
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000329# $cmd .= " -co /usr/lib/X11/rgb";
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000330
331foreach $arg (@ARGV) {
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400332 $cmd .= " " . &quotedString($arg);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000333}
334$cmd .= " >> " . &quotedString($desktopLog) . " 2>&1";
335
336# Run $cmd and record the process ID.
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000337$pidFile = "$vncUserDir/$host:$displayNumber.pid";
338system("$cmd & echo \$! >$pidFile");
339
340# Give Xvnc a chance to start up
341
Koichiro IWAO977fbde2016-10-03 18:07:57 +0900342sleep(3);
DRCd28792b2010-01-11 20:53:00 +0000343if ($fontPath ne $defFontPath) {
344 unless (kill 0, `cat $pidFile`) {
345 if ($fpArgSpecified) {
346 warn "\nWARNING: The first attempt to start Xvnc failed, probably because the font\n";
347 warn "path you specified using the -fp argument is incorrect. Attempting to\n";
348 warn "determine an appropriate font path for this system and restart Xvnc using\n";
349 warn "that font path ...\n";
350 } else {
351 warn "\nWARNING: The first attempt to start Xvnc failed, possibly because the font\n";
352 warn "catalog is not properly configured. Attempting to determine an appropriate\n";
353 warn "font path for this system and restart Xvnc using that font path ...\n";
354 }
355 $cmd =~ s@-fp [^ ]+@@;
356 $cmd .= " -fp $defFontPath" if ($defFontPath);
357 system("$cmd & echo \$! >$pidFile");
358 sleep(3);
DRC36546c12009-04-15 06:47:23 +0000359 }
DRCd6821bf2009-03-26 18:17:49 +0000360}
361unless (kill 0, `cat $pidFile`) {
362 warn "Could not start Xvnc.\n\n";
Michal Srbe6e11f92015-10-02 02:28:26 +0300363 unlink $pidFile;
DRCd6821bf2009-03-26 18:17:49 +0000364 open(LOG, "<$desktopLog");
365 while (<LOG>) { print; }
366 close(LOG);
367 die "\n";
368}
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000369
370warn "\nNew '$desktopName' desktop is $host:$displayNumber\n\n";
371
372# Create the user's xstartup script if necessary.
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200373if (! $skipxstartup) {
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400374 if (!(-e "$xstartupFile")) {
375 warn "Creating default startup script $xstartupFile\n";
376 open(XSTARTUP, ">$xstartupFile");
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200377 print XSTARTUP $defaultXStartup;
378 close(XSTARTUP);
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400379 chmod 0755, "$xstartupFile";
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200380 }
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000381}
382
grayskyddff8d02015-10-19 08:24:14 -0400383# Create the user's config file if necessary.
grayskyddff8d02015-10-19 08:24:14 -0400384if (!(-e "$vncUserDir/config")) {
385 warn "Creating default config $vncUserDir/config\n";
Jeff Blained6777a62016-05-23 21:43:59 -0400386 open(VNCUSERCONFIG, ">$vncUserDir/config");
387 print VNCUSERCONFIG $defaultConfig;
388 close(VNCUSERCONFIG);
grayskyddff8d02015-10-19 08:24:14 -0400389 chmod 0644, "$vncUserDir/config";
390}
391
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000392# Run the X startup script.
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200393if (! $skipxstartup) {
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400394 warn "Starting applications specified in $xstartupFile\n";
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200395}
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000396warn "Log file is $desktopLog\n\n";
397
398# If the unix domain socket exists then use that (DISPLAY=:n) otherwise use
399# TCP (DISPLAY=host:n)
400
401if (-e "/tmp/.X11-unix/X$displayNumber" ||
402 -e "/usr/spool/sockets/X11/$displayNumber")
403{
404 $ENV{DISPLAY}= ":$displayNumber";
405} else {
406 $ENV{DISPLAY}= "$host:$displayNumber";
407}
408$ENV{VNCDESKTOP}= $desktopName;
409
DRC8fb11912011-03-03 10:42:14 +0000410if ($opt{'-fg'}) {
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200411 if (! $skipxstartup) {
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400412 system("$xstartupFile >> " . &quotedString($desktopLog) . " 2>&1");
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200413 }
Adam Tkac38ba8cf2011-04-27 11:28:09 +0000414 if (kill 0, `cat $pidFile`) {
415 $opt{'-kill'} = ':'.$displayNumber;
416 &Kill();
417 }
DRC8fb11912011-03-03 10:42:14 +0000418} else {
Adam Tkac38ba8cf2011-04-27 11:28:09 +0000419 if ($opt{'-autokill'}) {
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200420 if (! $skipxstartup) {
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400421 system("($xstartupFile; $0 -kill :$displayNumber) >> "
Llorenç Garcia Martineze76c2fb2015-10-30 11:07:40 +0100422 . &quotedString($desktopLog) . " 2>&1 &");
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200423 }
Adam Tkac38ba8cf2011-04-27 11:28:09 +0000424 } else {
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200425 if (! $skipxstartup) {
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400426 system("$xstartupFile >> " . &quotedString($desktopLog)
Llorenç Garcia Martineze76c2fb2015-10-30 11:07:40 +0100427 . " 2>&1 &");
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200428 }
Adam Tkac38ba8cf2011-04-27 11:28:09 +0000429 }
DRC8fb11912011-03-03 10:42:14 +0000430}
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000431
432exit;
433
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000434###############################################################################
Jeff Blaine8a9abc12016-08-06 16:22:18 -0400435# Functions
436###############################################################################
437
438#
439# Populate the global %config hash with settings from a specified
440# vncserver configuration file if it exists
441#
442# Args: 1. file path
443# 2. optional boolean flag to enable warning when a previously
444# set configuration setting is being overridden
445#
446sub LoadConfig {
447 local ($configFile, $warnoverride) = @_;
448 local ($toggle) = undef;
449
450 if (stat($configFile)) {
451 if (open(IN, $configFile)) {
452 while (<IN>) {
453 next if /^#/;
454 if (my ($k, $v) = /^\s*(\w+)\s*=\s*(.+)$/) {
455 $k = lc($k); # must normalize key case
456 if ($warnoverride && $config{$k}) {
457 print("Warning: $configFile is overriding previously defined '$k' to be '$v'\n");
458 }
459 $config{$k} = $v;
460 } elsif ($_ =~ m/^\s*(\S+)/) {
461 # We can't reasonably warn on override of toggles (e.g. AlwaysShared)
462 # because it would get crazy to do so. We'd have to check if the
463 # current config file being loaded defined the logical opposite setting
464 # (NeverShared vs. AlwaysShared, etc etc).
465 $toggle = lc($1); # must normalize key case
466 $config{$toggle} = $k;
467 }
468 }
469 close(IN);
470 }
471 }
472}
473
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000474#
475# CheckGeometryAndDepth simply makes sure that the geometry and depth values
476# are sensible.
477#
478
479sub CheckGeometryAndDepth
480{
481 if ($geometry =~ /^(\d+)x(\d+)$/) {
482 $width = $1; $height = $2;
483
484 if (($width<1) || ($height<1)) {
485 die "$prog: geometry $geometry is invalid\n";
486 }
487
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000488 $geometry = "${width}x$height";
489 } else {
490 die "$prog: geometry $geometry is invalid\n";
491 }
492
DRCe5b4f752009-03-26 18:23:29 +0000493 if ($depth && (($depth < 8) || ($depth > 32))) {
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000494 die "Depth must be between 8 and 32\n";
495 }
496}
497
498
499#
500# GetDisplayNumber gets the lowest available display number. A display number
501# n is taken if something is listening on the VNC server port (5900+n) or the
502# X server port (6000+n).
503#
504
505sub GetDisplayNumber
506{
507 foreach $n (1..99) {
508 if (&CheckDisplayNumber($n)) {
509 return $n+0; # Bruce Mah's workaround for bug in perl 5.005_02
510 }
511 }
Koichiro IWAO977fbde2016-10-03 18:07:57 +0900512
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000513 die "$prog: no free display number on $host.\n";
514}
515
516
517#
518# CheckDisplayNumber checks if the given display number is available. A
519# display number n is taken if something is listening on the VNC server port
520# (5900+n) or the X server port (6000+n).
521#
522
523sub CheckDisplayNumber
524{
525 local ($n) = @_;
526
527 socket(S, $AF_INET, $SOCK_STREAM, 0) || die "$prog: socket failed: $!\n";
528 eval 'setsockopt(S, &SOL_SOCKET, &SO_REUSEADDR, pack("l", 1))';
529 if (!bind(S, pack('S n x12', $AF_INET, 6000 + $n))) {
530 close(S);
531 return 0;
532 }
533 close(S);
534
535 socket(S, $AF_INET, $SOCK_STREAM, 0) || die "$prog: socket failed: $!\n";
536 eval 'setsockopt(S, &SOL_SOCKET, &SO_REUSEADDR, pack("l", 1))';
537 if (!bind(S, pack('S n x12', $AF_INET, 5900 + $n))) {
538 close(S);
539 return 0;
540 }
541 close(S);
542
543 if (-e "/tmp/.X$n-lock") {
544 warn "\nWarning: $host:$n is taken because of /tmp/.X$n-lock\n";
545 warn "Remove this file if there is no X server $host:$n\n";
546 return 0;
547 }
548
549 if (-e "/tmp/.X11-unix/X$n") {
550 warn "\nWarning: $host:$n is taken because of /tmp/.X11-unix/X$n\n";
551 warn "Remove this file if there is no X server $host:$n\n";
552 return 0;
553 }
554
555 if (-e "/usr/spool/sockets/X11/$n") {
556 warn("\nWarning: $host:$n is taken because of ".
557 "/usr/spool/sockets/X11/$n\n");
558 warn "Remove this file if there is no X server $host:$n\n";
559 return 0;
560 }
561
562 return 1;
563}
564
565
566#
567# GetXDisplayDefaults uses xdpyinfo to find out the geometry, depth and pixel
568# format of the current X display being used. If successful, it sets the
569# options as appropriate so that the X VNC server will use the same settings
570# (minus an allowance for window manager decorations on the geometry). Using
571# the same depth and pixel format means that the VNC server won't have to
572# translate pixels when the desktop is being viewed on this X display (for
573# TrueColor displays anyway).
574#
575
576sub GetXDisplayDefaults
577{
578 local (@lines, @matchlines, $width, $height, $defaultVisualId, $i,
579 $red, $green, $blue);
580
581 $wmDecorationWidth = 4; # a guess at typical size for window manager
582 $wmDecorationHeight = 24; # decoration size
583
584 return if (!defined($ENV{DISPLAY}));
585
586 @lines = `xdpyinfo 2>/dev/null`;
587
588 return if ($? != 0);
589
590 @matchlines = grep(/dimensions/, @lines);
591 if (@matchlines) {
592 ($width, $height) = ($matchlines[0] =~ /(\d+)x(\d+) pixels/);
593
594 $width -= $wmDecorationWidth;
595 $height -= $wmDecorationHeight;
596
597 $geometry = "${width}x$height";
598 }
599
600 @matchlines = grep(/default visual id/, @lines);
601 if (@matchlines) {
602 ($defaultVisualId) = ($matchlines[0] =~ /id:\s+(\S+)/);
603
604 for ($i = 0; $i < @lines; $i++) {
605 if ($lines[$i] =~ /^\s*visual id:\s+$defaultVisualId$/) {
606 if (($lines[$i+1] !~ /TrueColor/) ||
607 ($lines[$i+2] !~ /depth/) ||
608 ($lines[$i+4] !~ /red, green, blue masks/))
609 {
610 return;
611 }
612 last;
613 }
614 }
615
616 return if ($i >= @lines);
617
618 ($depth) = ($lines[$i+2] =~ /depth:\s+(\d+)/);
619 ($red,$green,$blue)
620 = ($lines[$i+4]
621 =~ /masks:\s+0x([0-9a-f]+), 0x([0-9a-f]+), 0x([0-9a-f]+)/);
622
623 $red = hex($red);
624 $green = hex($green);
625 $blue = hex($blue);
626
627 if ($red > $blue) {
628 $red = int(log($red) / log(2)) - int(log($green) / log(2));
629 $green = int(log($green) / log(2)) - int(log($blue) / log(2));
630 $blue = int(log($blue) / log(2)) + 1;
631 $pixelformat = "rgb$red$green$blue";
632 } else {
633 $blue = int(log($blue) / log(2)) - int(log($green) / log(2));
634 $green = int(log($green) / log(2)) - int(log($red) / log(2));
635 $red = int(log($red) / log(2)) + 1;
636 $pixelformat = "bgr$blue$green$red";
637 }
638 }
639}
640
641
642#
643# quotedString returns a string which yields the original string when parsed
644# by a shell.
645#
646
647sub quotedString
648{
649 local ($in) = @_;
650
651 $in =~ s/\'/\'\"\'\"\'/g;
652
653 return "'$in'";
654}
655
656
657#
658# removeSlashes turns slashes into underscores for use as a file name.
659#
660
661sub removeSlashes
662{
663 local ($in) = @_;
664
665 $in =~ s|/|_|g;
666
667 return "$in";
668}
669
670
671#
672# Usage
673#
674
675sub Usage
676{
677 die("\nusage: $prog [:<number>] [-name <desktop-name>] [-depth <depth>]\n".
678 " [-geometry <width>x<height>]\n".
679 " [-pixelformat rgbNNN|bgrNNN]\n".
DRCeed5d1f2009-03-26 19:16:19 +0000680 " [-fp <font-path>]\n".
DRC8fb11912011-03-03 10:42:14 +0000681 " [-fg]\n".
Adam Tkac38ba8cf2011-04-27 11:28:09 +0000682 " [-autokill]\n".
Llorenç Garcia Martinez861cb062015-10-23 13:37:42 +0200683 " [-noxstartup]\n".
Llorenç Garcia Martineze76c2fb2015-10-30 11:07:40 +0100684 " [-xstartup <file>]\n".
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000685 " <Xvnc-options>...\n\n".
DRCb9d8e762011-02-09 08:24:58 +0000686 " $prog -kill <X-display>\n\n".
687 " $prog -list\n\n");
688}
689
690
691#
692# List
693#
694
695sub List
696{
697 opendir(dir, $vncUserDir);
698 my @filelist = readdir(dir);
699 closedir(dir);
DRC075d9fa2011-02-10 04:19:46 +0000700 print "\nTigerVNC server sessions:\n\n";
DRCb9d8e762011-02-09 08:24:58 +0000701 print "X DISPLAY #\tPROCESS ID\n";
702 foreach my $file (@filelist) {
703 if ($file =~ /$host:(\d+)$\.pid/) {
Michal Srbe6e11f92015-10-02 02:28:26 +0300704 chop($tmp_pid = `cat $vncUserDir/$file`);
705 if (kill 0, $tmp_pid) {
706 print ":".$1."\t\t".`cat $vncUserDir/$file`;
707 } else {
708 unlink ($vncUserDir . "/" . $file);
709 }
DRCb9d8e762011-02-09 08:24:58 +0000710 }
711 }
712 exit 1;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000713}
714
715
716#
717# Kill
718#
719
720sub Kill
721{
722 $opt{'-kill'} =~ s/(:\d+)\.\d+$/$1/; # e.g. turn :1.0 into :1
723
724 if ($opt{'-kill'} =~ /^:\d+$/) {
725 $pidFile = "$vncUserDir/$host$opt{'-kill'}.pid";
726 } else {
727 if ($opt{'-kill'} !~ /^$host:/) {
728 die "\nCan't tell if $opt{'-kill'} is on $host\n".
729 "Use -kill :<number> instead\n\n";
730 }
731 $pidFile = "$vncUserDir/$opt{'-kill'}.pid";
732 }
733
734 if (! -r $pidFile) {
735 die "\nCan't find file $pidFile\n".
736 "You'll have to kill the Xvnc process manually\n\n";
737 }
738
739 $SIG{'HUP'} = 'IGNORE';
740 chop($pid = `cat $pidFile`);
741 warn "Killing Xvnc process ID $pid\n";
DRCb9d8e762011-02-09 08:24:58 +0000742
743 if (kill 0, $pid) {
744 system("kill $pid");
745 sleep(1);
746 if (kill 0, $pid) {
747 print "Xvnc seems to be deadlocked. Kill the process manually and then re-run\n";
748 print " ".$0." -kill ".$opt{'-kill'}."\n";
749 print "to clean up the socket files.\n";
750 exit
751 }
752
753 } else {
754 warn "Xvnc process ID $pid already killed\n";
755 $opt{'-kill'} =~ s/://;
Koichiro IWAO977fbde2016-10-03 18:07:57 +0900756
DRCb9d8e762011-02-09 08:24:58 +0000757 if (-e "/tmp/.X11-unix/X$opt{'-kill'}") {
758 print "Xvnc did not appear to shut down cleanly.";
759 print " Removing /tmp/.X11-unix/X$opt{'-kill'}\n";
760 unlink "/tmp/.X11-unix/X$opt{'-kill'}";
761 }
762 if (-e "/tmp/.X$opt{'-kill'}-lock") {
763 print "Xvnc did not appear to shut down cleanly.";
764 print " Removing /tmp/.X$opt{'-kill'}-lock\n";
765 unlink "/tmp/.X$opt{'-kill'}-lock";
766 }
767 }
768
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000769 unlink $pidFile;
770 exit;
771}
772
773
774#
775# ParseOptions takes a list of possible options and a boolean indicating
776# whether the option has a value following, and sets up an associative array
777# %opt of the values of the options given on the command line. It removes all
778# the arguments it uses from @ARGV and returns them in @optArgs.
779#
780
781sub ParseOptions
782{
783 local (@optval) = @_;
784 local ($opt, @opts, %valFollows, @newargs);
785
786 while (@optval) {
787 $opt = shift(@optval);
788 push(@opts,$opt);
789 $valFollows{$opt} = shift(@optval);
790 }
791
792 @optArgs = ();
793 %opt = ();
794
795 arg: while (defined($arg = shift(@ARGV))) {
796 foreach $opt (@opts) {
797 if ($arg eq $opt) {
798 push(@optArgs, $arg);
799 if ($valFollows{$opt}) {
800 if (@ARGV == 0) {
801 &Usage();
802 }
803 $opt{$opt} = shift(@ARGV);
804 push(@optArgs, $opt{$opt});
805 } else {
806 $opt{$opt} = 1;
807 }
808 next arg;
809 }
810 }
811 push(@newargs,$arg);
812 }
813
814 @ARGV = @newargs;
815}
816
817
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000818# Routine to make sure we're operating in a sane environment.
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000819sub SanityCheck
820{
821 local ($cmd);
822
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000823 # Get the program name
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000824 ($prog) = ($0 =~ m|([^/]+)$|);
825
826 #
827 # Check we have all the commands we'll need on the path.
828 #
829
830 cmd:
Koichiro IWAO31cad942016-10-04 17:17:06 +0900831 foreach $cmd ("uname","xauth") {
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000832 for (split(/:/,$ENV{PATH})) {
833 if (-x "$_/$cmd") {
834 next cmd;
835 }
836 }
837 die "$prog: couldn't find \"$cmd\" on your PATH.\n";
838 }
DRC190854c2009-03-26 18:13:00 +0000839
840 if($exedir eq "") {
841 cmd2:
842 foreach $cmd ("Xvnc","vncpasswd") {
843 for (split(/:/,$ENV{PATH})) {
844 if (-x "$_/$cmd") {
DRC190854c2009-03-26 18:13:00 +0000845 next cmd2;
846 }
847 }
848 die "$prog: couldn't find \"$cmd\" on your PATH.\n";
849 }
850 }
851 else {
852 cmd3:
853 foreach $cmd ($exedir."Xvnc",$exedir."vncpasswd") {
854 for (split(/:/,$ENV{PATH})) {
855 if (-x "$cmd") {
DRC190854c2009-03-26 18:13:00 +0000856 next cmd3;
857 }
858 }
859 die "$prog: couldn't find \"$cmd\".\n";
860 }
861 }
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000862
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000863 if (!defined($ENV{HOME})) {
864 die "$prog: The HOME environment variable is not set.\n";
865 }
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000866
867 #
868 # Find socket constants. 'use Socket' is a perl5-ism, so we wrap it in an
869 # eval, and if it fails we try 'require "sys/socket.ph"'. If this fails,
870 # we just guess at the values. If you find perl moaning here, just
871 # hard-code the values of AF_INET and SOCK_STREAM. You can find these out
872 # for your platform by looking in /usr/include/sys/socket.h and related
873 # files.
874 #
875
876 chop($os = `uname`);
877 chop($osrev = `uname -r`);
878
879 eval 'use Socket';
880 if ($@) {
881 eval 'require "sys/socket.ph"';
882 if ($@) {
883 if (($os eq "SunOS") && ($osrev !~ /^4/)) {
884 $AF_INET = 2;
885 $SOCK_STREAM = 2;
886 } else {
887 $AF_INET = 2;
888 $SOCK_STREAM = 1;
889 }
890 } else {
891 $AF_INET = &AF_INET;
892 $SOCK_STREAM = &SOCK_STREAM;
893 }
894 } else {
895 $AF_INET = &AF_INET;
896 $SOCK_STREAM = &SOCK_STREAM;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000897 }
898}