acbd46
#!/usr/bin/perl
acbd46
#
acbd46
#  Copyright (C) 2009-2010 D. R. Commander.  All Rights Reserved.
acbd46
#  Copyright (C) 2005-2006 Sun Microsystems, Inc.  All Rights Reserved.
acbd46
#  Copyright (C) 2002-2003 Constantin Kaplinsky.  All Rights Reserved.
acbd46
#  Copyright (C) 2002-2005 RealVNC Ltd.
acbd46
#  Copyright (C) 1999 AT&T Laboratories Cambridge.  All Rights Reserved.
acbd46
#
acbd46
#  This is free software; you can redistribute it and/or modify
acbd46
#  it under the terms of the GNU General Public License as published by
acbd46
#  the Free Software Foundation; either version 2 of the License, or
acbd46
#  (at your option) any later version.
acbd46
#
acbd46
#  This software is distributed in the hope that it will be useful,
acbd46
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
acbd46
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
acbd46
#  GNU General Public License for more details.
acbd46
#
acbd46
#  You should have received a copy of the GNU General Public License
acbd46
#  along with this software; if not, write to the Free Software
acbd46
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
acbd46
#  USA.
acbd46
#
acbd46
acbd46
#
acbd46
# vncserver - wrapper script to start an X VNC server.
acbd46
#
acbd46
acbd46
# First make sure we're operating in a sane environment.
acbd46
$exedir = "";
acbd46
$slashndx = rindex($0, "/");
acbd46
if($slashndx>=0) {
acbd46
    $exedir = substr($0, 0, $slashndx+1);
acbd46
}
acbd46
acbd46
&SanityCheck();
acbd46
acbd46
&NotifyAboutDeprecation();
acbd46
acbd46
#
acbd46
# Global variables.  You may want to configure some of these for
acbd46
# your site
acbd46
#
acbd46
acbd46
$geometry = "1024x768";
acbd46
#$depth = 16;
acbd46
acbd46
$vncUserDir = "$ENV{HOME}/.vnc";
acbd46
$vncUserConfig = "$vncUserDir/config";
acbd46
acbd46
$vncSystemConfigDir = "/etc/tigervnc";
acbd46
$vncSystemConfigDefaultsFile = "$vncSystemConfigDir/vncserver-config-defaults";
acbd46
$vncSystemConfigMandatoryFile = "$vncSystemConfigDir/vncserver-config-mandatory";
acbd46
acbd46
$skipxstartup = 0;
acbd46
$xauthorityFile = "$ENV{XAUTHORITY}" || "$ENV{HOME}/.Xauthority";
acbd46
acbd46
$xstartupFile = $vncUserDir . "/xstartup";
acbd46
$defaultXStartup
acbd46
    = ("#!/bin/sh\n\n".
acbd46
       "unset SESSION_MANAGER\n".
acbd46
       "unset DBUS_SESSION_BUS_ADDRESS\n".
acbd46
       "/etc/X11/xinit/xinitrc\n".
acbd46
       "# Assume either Gnome will be started by default when installed\n".
acbd46
       "# We want to kill the session automatically in this case when user logs out. In case you modify\n".
acbd46
       "# /etc/X11/xinit/Xclients or ~/.Xclients yourself to achieve a different result, then you should\n".
acbd46
       "# be responsible to modify below code to avoid that your session will be automatically killed\n".
acbd46
       "if [ -e /usr/bin/gnome-session ]; then\n".
acbd46
       "    vncserver -kill \$DISPLAY\n".
acbd46
       "fi\n");
acbd46
acbd46
$defaultConfig
acbd46
    = ("## Supported server options to pass to vncserver upon invocation can be listed\n".
acbd46
       "## in this file. See the following manpages for more: vncserver(1) Xvnc(1).\n".
acbd46
       "## Several common ones are shown below. Uncomment and modify to your liking.\n".
acbd46
       "##\n".
acbd46
       "# securitytypes=vncauth,tlsvnc\n".
acbd46
       "# desktop=sandbox\n".
acbd46
       "# geometry=2000x1200\n".
acbd46
       "# localhost\n".
acbd46
       "# alwaysshared\n");
acbd46
acbd46
chop($host = `uname -n`);
acbd46
acbd46
if (-d "/etc/X11/fontpath.d") {
acbd46
    $fontPath = "catalogue:/etc/X11/fontpath.d";
acbd46
}
acbd46
acbd46
@fontpaths = ('/usr/share/X11/fonts', '/usr/share/fonts', '/usr/share/fonts/X11/');
acbd46
if (! -l "/usr/lib/X11") {push(@fontpaths, '/usr/lib/X11/fonts');}
acbd46
if (! -l "/usr/X11") {push(@fontpaths, '/usr/X11/lib/X11/fonts');}
acbd46
if (! -l "/usr/X11R6") {push(@fontpaths, '/usr/X11R6/lib/X11/fonts');}
acbd46
push(@fontpaths, '/usr/share/fonts/default');
acbd46
acbd46
@fonttypes = ('misc',
acbd46
             '75dpi',
acbd46
             '100dpi',
acbd46
             'Speedo',
acbd46
             'Type1');
acbd46
acbd46
foreach $_fpath (@fontpaths) {
acbd46
    foreach $_ftype (@fonttypes) {
acbd46
        if (-f "$_fpath/$_ftype/fonts.dir") {
acbd46
            if (! -l "$_fpath/$_ftype") {
acbd46
                $defFontPath .= "$_fpath/$_ftype,";
acbd46
            }
acbd46
        }
acbd46
    }
acbd46
}
acbd46
acbd46
if ($defFontPath) {
acbd46
    if (substr($defFontPath, -1, 1) == ',') {
acbd46
        chop $defFontPath;
acbd46
    }
acbd46
}
acbd46
acbd46
if ($fontPath eq "") {
acbd46
    $fontPath = $defFontPath;
acbd46
}
acbd46
acbd46
# Check command line options
acbd46
acbd46
&ParseOptions("-geometry",1,"-depth",1,"-pixelformat",1,"-name",1,"-kill",1,
acbd46
	      "-help",0,"-h",0,"--help",0,"-fp",1,"-list",0,"-fg",0,"-autokill",0,"-noxstartup",0,"-xstartup",1);
acbd46
acbd46
&Usage() if ($opt{'-help'} || $opt{'-h'} || $opt{'--help'});
acbd46
acbd46
&Kill() if ($opt{'-kill'});
acbd46
acbd46
&List() if ($opt{'-list'});
acbd46
acbd46
# Uncomment this line if you want default geometry, depth and pixelformat
acbd46
# to match the current X display:
acbd46
# &GetXDisplayDefaults();
acbd46
acbd46
if ($opt{'-geometry'}) {
acbd46
    $geometry = $opt{'-geometry'};
acbd46
}
acbd46
if ($opt{'-depth'}) {
acbd46
    $depth = $opt{'-depth'};
acbd46
    $pixelformat = "";
acbd46
}
acbd46
if ($opt{'-pixelformat'}) {
acbd46
    $pixelformat = $opt{'-pixelformat'};
acbd46
}
acbd46
if ($opt{'-noxstartup'}) {
acbd46
    $skipxstartup = 1;
acbd46
}
acbd46
if ($opt{'-xstartup'}) {
acbd46
    $xstartupFile = $opt{'-xstartup'};
acbd46
}
acbd46
if ($opt{'-fp'}) {
acbd46
    $fontPath = $opt{'-fp'};
acbd46
    $fpArgSpecified = 1;
acbd46
}
acbd46
acbd46
&CheckGeometryAndDepth();
acbd46
acbd46
# Create the user's vnc directory if necessary.
acbd46
if (!(-e $vncUserDir)) {
acbd46
    if (!mkdir($vncUserDir,0755)) {
acbd46
	die "$prog: Could not create $vncUserDir.\n";
acbd46
    }
acbd46
}
acbd46
acbd46
# Find display number.
acbd46
if ((@ARGV > 0) && ($ARGV[0] =~ /^:(\d+)$/)) {
acbd46
    $displayNumber = $1;
acbd46
    shift(@ARGV);
acbd46
    if (!&CheckDisplayNumber($displayNumber)) {
324a25
        warn "A VNC server is already running as :$displayNumber\n";
324a25
        $displayNumber = &GetDisplayNumber();
acbd46
    }
acbd46
} elsif ((@ARGV > 0) && ($ARGV[0] !~ /^-/) && ($ARGV[0] !~ /^\+/)) {
acbd46
    &Usage();
acbd46
} else {
acbd46
    $displayNumber = &GetDisplayNumber();
acbd46
}
acbd46
acbd46
$vncPort = 5900 + $displayNumber;
acbd46
acbd46
if ($opt{'-name'}) {
acbd46
    $desktopName = $opt{'-name'};
acbd46
} else {
acbd46
    $desktopName = "$host:$displayNumber ($ENV{USER})";
acbd46
}
acbd46
acbd46
my %default_opts;
acbd46
my %config;
acbd46
acbd46
# We set some reasonable defaults. Config file settings
acbd46
# override these where present.
acbd46
$default_opts{desktop} = &quotedString($desktopName);
acbd46
$default_opts{auth} = &quotedString($xauthorityFile);
acbd46
$default_opts{geometry} = $geometry if ($geometry);
acbd46
$default_opts{depth} = $depth if ($depth);
acbd46
$default_opts{pixelformat} = $pixelformat if ($pixelformat);
acbd46
$default_opts{rfbauth} = "$vncUserDir/passwd";
acbd46
$default_opts{rfbport} = $vncPort;
acbd46
$default_opts{fp} = $fontPath if ($fontPath);
acbd46
$default_opts{pn} = "";
acbd46
acbd46
# Load user-overrideable system defaults
acbd46
LoadConfig($vncSystemConfigDefaultsFile);
acbd46
acbd46
# Then the user's settings
acbd46
LoadConfig($vncUserConfig);
acbd46
acbd46
# And then override anything set above if mandatory settings exist.
acbd46
# WARNING: "Mandatory" is used loosely here! As the man page says,
acbd46
# there is nothing stopping someone from EASILY subverting the
acbd46
# settings in $vncSystemConfigMandatoryFile by simply passing
acbd46
# CLI args to vncserver, which trump config files! To properly
acbd46
# hard force policy in a non-subvertible way would require major
acbd46
# development work that touches Xvnc itself.
acbd46
LoadConfig($vncSystemConfigMandatoryFile, 1);
acbd46
acbd46
#
acbd46
# Check whether VNC authentication is enabled, and if so, prompt the user to
acbd46
# create a VNC password if they don't already have one.
acbd46
#
acbd46
acbd46
$securityTypeArgSpecified = 0;
acbd46
$vncAuthEnabled = 0;
acbd46
$passwordArgSpecified = 0;
acbd46
@vncAuthStrings = ("vncauth", "tlsvnc", "x509vnc");
acbd46
acbd46
# ...first we check our configuration files' settings
acbd46
if ($config{'securitytypes'}) {
acbd46
  $securityTypeArgSpecified = 1;
acbd46
  foreach $arg2 (split(',', $config{'securitytypes'})) {
acbd46
    if (grep {$_ eq lc($arg2)} @vncAuthStrings) {
acbd46
      $vncAuthEnabled = 1;
acbd46
    }
acbd46
  }
acbd46
}
acbd46
acbd46
# ...and finally we check CLI args, which in the case of the topic at
acbd46
# hand (VNC auth or not), override anything found in configuration files
acbd46
# (even so-called "mandatory" settings).
acbd46
for ($i = 0; $i < @ARGV; ++$i) {
acbd46
    # -SecurityTypes can be followed by a space or "="
acbd46
    my @splitargs = split('=', $ARGV[$i]);
acbd46
    if (@splitargs <= 1 && $i < @ARGV - 1) {
acbd46
        push(@splitargs, $ARGV[$i + 1]);
acbd46
    }
acbd46
    if (lc(@splitargs[0]) eq "-securitytypes") {
acbd46
        if (@splitargs > 1) {
acbd46
            $securityTypeArgSpecified = 1;
acbd46
        }
acbd46
        foreach $arg2 (split(',', @splitargs[1])) {
acbd46
            if (grep {$_ eq lc($arg2)} @vncAuthStrings) {
acbd46
                $vncAuthEnabled = 1;
acbd46
            }
acbd46
        }
acbd46
    }
acbd46
    if ((lc(@splitargs[0]) eq "-password")
acbd46
     || (lc(@splitargs[0]) eq "-passwordfile"
acbd46
     || (lc(@splitargs[0]) eq "-rfbauth"))) {
acbd46
        $passwordArgSpecified = 1;
acbd46
    }
acbd46
}
acbd46
acbd46
if ((!$securityTypeArgSpecified || $vncAuthEnabled) && !$passwordArgSpecified) {
acbd46
    ($z,$z,$mode) = stat("$vncUserDir/passwd");
acbd46
    if (!(-e "$vncUserDir/passwd") || ($mode & 077)) {
acbd46
        warn "\nYou will require a password to access your desktops.\n\n";
acbd46
        system($exedir."vncpasswd -q $vncUserDir/passwd");
acbd46
        if (($? >> 8) != 0) {
acbd46
            exit 1;
acbd46
        }
acbd46
    }
acbd46
}
acbd46
acbd46
$desktopLog = "$vncUserDir/$host:$displayNumber.log";
acbd46
unlink($desktopLog);
acbd46
acbd46
# Make an X server cookie and set up the Xauthority file
acbd46
# mcookie is a part of util-linux, usually only GNU/Linux systems have it.
acbd46
$cookie = `mcookie`;
acbd46
# Fallback for non GNU/Linux OS - use /dev/urandom on systems that have it,
acbd46
# otherwise use perl's random number generator, seeded with the sum
acbd46
# of the current time, our PID and part of the encrypted form of the password.
acbd46
if ($cookie eq "" && open(URANDOM, '<', '/dev/urandom')) {
acbd46
  my $randata;
acbd46
  if (sysread(URANDOM, $randata, 16) == 16) {
acbd46
    $cookie = unpack 'h*', $randata;
acbd46
  }
acbd46
  close(URANDOM);
acbd46
}
acbd46
if ($cookie eq "") {
acbd46
  srand(time+$$+unpack("L",`cat $vncUserDir/passwd`));
acbd46
  for (1..16) {
acbd46
    $cookie .= sprintf("%02x", int(rand(256)) % 256);
acbd46
  }
acbd46
}
acbd46
acbd46
open(XAUTH, "|xauth -f $xauthorityFile source -");
acbd46
print XAUTH "add $host:$displayNumber . $cookie\n";
acbd46
print XAUTH "add $host/unix:$displayNumber . $cookie\n";
acbd46
close(XAUTH);
acbd46
acbd46
# Now start the X VNC Server
acbd46
acbd46
# We build up our Xvnc command with options
acbd46
$cmd = $exedir."Xvnc :$displayNumber";
acbd46
acbd46
foreach my $k (sort keys %config) {
acbd46
  $cmd .= " -$k $config{$k}";
acbd46
  delete $default_opts{$k}; # file options take precedence
acbd46
}
acbd46
acbd46
foreach my $k (sort keys %default_opts) {
acbd46
  $cmd .= " -$k $default_opts{$k}";
acbd46
}
acbd46
acbd46
# Add color database stuff here, e.g.:
acbd46
# $cmd .= " -co /usr/lib/X11/rgb";
acbd46
acbd46
foreach $arg (@ARGV) {
acbd46
  $cmd .= " " . &quotedString($arg);
acbd46
}
acbd46
$cmd .= " >> " . &quotedString($desktopLog) . " 2>&1;;
acbd46
acbd46
# Run $cmd and record the process ID.
acbd46
$pidFile = "$vncUserDir/$host:$displayNumber.pid";
acbd46
system("$cmd & echo \$! >$pidFile");
acbd46
acbd46
# Give Xvnc a chance to start up
acbd46
acbd46
sleep(3);
acbd46
if ($fontPath ne $defFontPath) {
acbd46
    unless (kill 0, `cat $pidFile`) {
acbd46
        if ($fpArgSpecified) {
acbd46
	    warn "\nWARNING: The first attempt to start Xvnc failed, probably because the font\n";
acbd46
	    warn "path you specified using the -fp argument is incorrect.  Attempting to\n";
acbd46
	    warn "determine an appropriate font path for this system and restart Xvnc using\n";
acbd46
	    warn "that font path ...\n";
acbd46
        } else {
acbd46
	    warn "\nWARNING: The first attempt to start Xvnc failed, possibly because the font\n";
acbd46
	    warn "catalog is not properly configured.  Attempting to determine an appropriate\n";
acbd46
	    warn "font path for this system and restart Xvnc using that font path ...\n";
acbd46
        }
acbd46
	$cmd =~ s@-fp [^ ]+@@;
acbd46
	$cmd .= " -fp $defFontPath" if ($defFontPath);
acbd46
	system("$cmd & echo \$! >$pidFile");
acbd46
	sleep(3);
acbd46
    }
acbd46
}
acbd46
unless (kill 0, `cat $pidFile`) {
acbd46
    warn "Could not start Xvnc.\n\n";
acbd46
    unlink $pidFile;
acbd46
    open(LOG, "<$desktopLog");
acbd46
    while (<LOG>) { print; }
acbd46
    close(LOG);
acbd46
    die "\n";
acbd46
}
acbd46
acbd46
warn "\nNew '$desktopName' desktop is $host:$displayNumber\n\n";
acbd46
acbd46
# Create the user's xstartup script if necessary.
acbd46
if (! $skipxstartup) {
acbd46
    if (!(-e "$xstartupFile")) {
acbd46
	warn "Creating default startup script $xstartupFile\n";
acbd46
	open(XSTARTUP, ">$xstartupFile");
acbd46
        print XSTARTUP $defaultXStartup;
acbd46
        close(XSTARTUP);
acbd46
        chmod 0755, "$xstartupFile";
acbd46
    }
acbd46
}
acbd46
acbd46
# Create the user's config file if necessary.
acbd46
if (!(-e "$vncUserDir/config")) {
acbd46
    warn "Creating default config $vncUserDir/config\n";
acbd46
    open(VNCUSERCONFIG, ">$vncUserDir/config");
acbd46
    print VNCUSERCONFIG $defaultConfig;
acbd46
    close(VNCUSERCONFIG);
acbd46
    chmod 0644, "$vncUserDir/config";
acbd46
}
acbd46
acbd46
# Run the X startup script.
acbd46
if (! $skipxstartup) {
acbd46
    warn "Starting applications specified in $xstartupFile\n";
acbd46
}
acbd46
warn "Log file is $desktopLog\n\n";
acbd46
acbd46
# If the unix domain socket exists then use that (DISPLAY=:n) otherwise use
acbd46
# TCP (DISPLAY=host:n)
acbd46
acbd46
if (-e "/tmp/.X11-unix/X$displayNumber" ||
acbd46
    -e "/usr/spool/sockets/X11/$displayNumber")
acbd46
{
acbd46
    $ENV{DISPLAY}= ":$displayNumber";
acbd46
} else {
acbd46
    $ENV{DISPLAY}= "$host:$displayNumber";
acbd46
}
acbd46
$ENV{VNCDESKTOP}= $desktopName;
acbd46
acbd46
if ($opt{'-fg'}) {
acbd46
    if (! $skipxstartup) {
acbd46
        system("$xstartupFile >> " . &quotedString($desktopLog) . " 2>&1");
acbd46
    }
acbd46
    if (kill 0, `cat $pidFile`) {
acbd46
        $opt{'-kill'} = ':'.$displayNumber;
acbd46
        &Kill();
acbd46
    }
acbd46
} else {
acbd46
    if ($opt{'-autokill'}) {
acbd46
    	if (! $skipxstartup) {
acbd46
            system("($xstartupFile; $0 -kill :$displayNumber) >> "
acbd46
	     . &quotedString($desktopLog) . " 2>&1 &";;
acbd46
    	}
acbd46
    } else {
acbd46
    	if (! $skipxstartup) {
acbd46
            system("$xstartupFile >> " . &quotedString($desktopLog)
acbd46
	     . " 2>&1 &";;
acbd46
    	}
acbd46
    }
acbd46
}
acbd46
acbd46
exit;
acbd46
acbd46
###############################################################################
acbd46
# Functions
acbd46
###############################################################################
acbd46
acbd46
#
acbd46
# Populate the global %config hash with settings from a specified
acbd46
# vncserver configuration file if it exists
acbd46
#
acbd46
# Args: 1. file path
acbd46
#       2. optional boolean flag to enable warning when a previously
acbd46
#          set configuration setting is being overridden
acbd46
#
acbd46
sub LoadConfig {
acbd46
  local ($configFile, $warnoverride) = @_;
acbd46
  local ($toggle) = undef;
acbd46
acbd46
  if (stat($configFile)) {
acbd46
    if (open(IN, $configFile)) {
acbd46
      while (<IN>) {
acbd46
        next if /^#/;
acbd46
        if (my ($k, $v) = /^\s*(\w+)\s*=\s*(.+)$/) {
acbd46
          $k = lc($k); # must normalize key case
acbd46
          if ($k eq "session") {
acbd46
            next;
acbd46
          }
acbd46
          if ($warnoverride && $config{$k}) {
acbd46
            print("Warning: $configFile is overriding previously defined '$k' to be '$v'\n");
acbd46
          }
acbd46
          $config{$k} = $v;
acbd46
        } elsif ($_ =~ m/^\s*(\S+)/) {
acbd46
          # We can't reasonably warn on override of toggles (e.g. AlwaysShared)
acbd46
          # because it would get crazy to do so. We'd have to check if the
acbd46
          # current config file being loaded defined the logical opposite setting
acbd46
          # (NeverShared vs. AlwaysShared, etc etc).
acbd46
          $toggle = lc($1); # must normalize key case
acbd46
          $config{$toggle} = $k;
acbd46
        }
acbd46
      }
acbd46
      close(IN);
acbd46
    }
acbd46
  }
acbd46
}
acbd46
acbd46
#
acbd46
# CheckGeometryAndDepth simply makes sure that the geometry and depth values
acbd46
# are sensible.
acbd46
#
acbd46
acbd46
sub CheckGeometryAndDepth
acbd46
{
acbd46
    if ($geometry =~ /^(\d+)x(\d+)$/) {
acbd46
	$width = $1; $height = $2;
acbd46
acbd46
	if (($width<1) || ($height<1)) {
acbd46
	    die "$prog: geometry $geometry is invalid\n";
acbd46
	}
acbd46
acbd46
	$geometry = "${width}x$height";
acbd46
    } else {
acbd46
	die "$prog: geometry $geometry is invalid\n";
acbd46
    }
acbd46
acbd46
    if ($depth && (($depth < 8) || ($depth > 32))) {
acbd46
	die "Depth must be between 8 and 32\n";
acbd46
    }
acbd46
}
acbd46
acbd46
acbd46
#
acbd46
# GetDisplayNumber gets the lowest available display number.  A display number
acbd46
# n is taken if something is listening on the VNC server port (5900+n) or the
acbd46
# X server port (6000+n).
acbd46
#
acbd46
acbd46
sub GetDisplayNumber
acbd46
{
acbd46
    foreach $n (1..99) {
acbd46
	if (&CheckDisplayNumber($n)) {
acbd46
	    return $n+0; # Bruce Mah's workaround for bug in perl 5.005_02
acbd46
	}
acbd46
    }
acbd46
acbd46
    die "$prog: no free display number on $host.\n";
acbd46
}
acbd46
acbd46
acbd46
#
acbd46
# CheckDisplayNumber checks if the given display number is available.  A
acbd46
# display number n is taken if something is listening on the VNC server port
acbd46
# (5900+n) or the X server port (6000+n).
acbd46
#
acbd46
acbd46
sub CheckDisplayNumber
acbd46
{
acbd46
    local ($n) = @_;
acbd46
acbd46
    socket(S, $AF_INET, $SOCK_STREAM, 0) || die "$prog: socket failed: $!\n";
acbd46
    eval 'setsockopt(S, &SOL_SOCKET, &SO_REUSEADDR, pack("l", 1))';
acbd46
    if (!bind(S, pack('S n x12', $AF_INET, 6000 + $n))) {
acbd46
	close(S);
acbd46
	return 0;
acbd46
    }
acbd46
    close(S);
acbd46
acbd46
    socket(S, $AF_INET, $SOCK_STREAM, 0) || die "$prog: socket failed: $!\n";
acbd46
    eval 'setsockopt(S, &SOL_SOCKET, &SO_REUSEADDR, pack("l", 1))';
acbd46
    if (!bind(S, pack('S n x12', $AF_INET, 5900 + $n))) {
acbd46
	close(S);
acbd46
	return 0;
acbd46
    }
acbd46
    close(S);
acbd46
acbd46
    if (-e "/tmp/.X$n-lock") {
acbd46
	warn "\nWarning: $host:$n is taken because of /tmp/.X$n-lock\n";
acbd46
	warn "Remove this file if there is no X server $host:$n\n";
acbd46
	return 0;
acbd46
    }
acbd46
acbd46
    if (-e "/tmp/.X11-unix/X$n") {
acbd46
	warn "\nWarning: $host:$n is taken because of /tmp/.X11-unix/X$n\n";
acbd46
	warn "Remove this file if there is no X server $host:$n\n";
acbd46
	return 0;
acbd46
    }
acbd46
acbd46
    if (-e "/usr/spool/sockets/X11/$n") {
acbd46
	warn("\nWarning: $host:$n is taken because of ".
acbd46
             "/usr/spool/sockets/X11/$n\n");
acbd46
	warn "Remove this file if there is no X server $host:$n\n";
acbd46
	return 0;
acbd46
    }
acbd46
acbd46
    return 1;
acbd46
}
acbd46
acbd46
acbd46
#
acbd46
# GetXDisplayDefaults uses xdpyinfo to find out the geometry, depth and pixel
acbd46
# format of the current X display being used.  If successful, it sets the
acbd46
# options as appropriate so that the X VNC server will use the same settings
acbd46
# (minus an allowance for window manager decorations on the geometry).  Using
acbd46
# the same depth and pixel format means that the VNC server won't have to
acbd46
# translate pixels when the desktop is being viewed on this X display (for
acbd46
# TrueColor displays anyway).
acbd46
#
acbd46
acbd46
sub GetXDisplayDefaults
acbd46
{
acbd46
    local (@lines, @matchlines, $width, $height, $defaultVisualId, $i,
acbd46
	   $red, $green, $blue);
acbd46
acbd46
    $wmDecorationWidth = 4;	# a guess at typical size for window manager
acbd46
    $wmDecorationHeight = 24;	# decoration size
acbd46
acbd46
    return if (!defined($ENV{DISPLAY}));
acbd46
acbd46
    @lines = `xdpyinfo 2>/dev/null`;
acbd46
acbd46
    return if ($? != 0);
acbd46
acbd46
    @matchlines = grep(/dimensions/, @lines);
acbd46
    if (@matchlines) {
acbd46
	($width, $height) = ($matchlines[0] =~ /(\d+)x(\d+) pixels/);
acbd46
acbd46
	$width -= $wmDecorationWidth;
acbd46
	$height -= $wmDecorationHeight;
acbd46
acbd46
	$geometry = "${width}x$height";
acbd46
    }
acbd46
acbd46
    @matchlines = grep(/default visual id/, @lines);
acbd46
    if (@matchlines) {
acbd46
	($defaultVisualId) = ($matchlines[0] =~ /id:\s+(\S+)/);
acbd46
acbd46
	for ($i = 0; $i < @lines; $i++) {
acbd46
	    if ($lines[$i] =~ /^\s*visual id:\s+$defaultVisualId$/) {
acbd46
		if (($lines[$i+1] !~ /TrueColor/) ||
acbd46
		    ($lines[$i+2] !~ /depth/) ||
acbd46
		    ($lines[$i+4] !~ /red, green, blue masks/))
acbd46
		{
acbd46
		    return;
acbd46
		}
acbd46
		last;
acbd46
	    }
acbd46
	}
acbd46
acbd46
	return if ($i >= @lines);
acbd46
acbd46
	($depth) = ($lines[$i+2] =~ /depth:\s+(\d+)/);
acbd46
	($red,$green,$blue)
acbd46
	    = ($lines[$i+4]
acbd46
	       =~ /masks:\s+0x([0-9a-f]+), 0x([0-9a-f]+), 0x([0-9a-f]+)/);
acbd46
acbd46
	$red = hex($red);
acbd46
	$green = hex($green);
acbd46
	$blue = hex($blue);
acbd46
acbd46
	if ($red > $blue) {
acbd46
	    $red = int(log($red) / log(2)) - int(log($green) / log(2));
acbd46
	    $green = int(log($green) / log(2)) - int(log($blue) / log(2));
acbd46
	    $blue = int(log($blue) / log(2)) + 1;
acbd46
	    $pixelformat = "rgb$red$green$blue";
acbd46
	} else {
acbd46
	    $blue = int(log($blue) / log(2)) - int(log($green) / log(2));
acbd46
	    $green = int(log($green) / log(2)) - int(log($red) / log(2));
acbd46
	    $red = int(log($red) / log(2)) + 1;
acbd46
	    $pixelformat = "bgr$blue$green$red";
acbd46
	}
acbd46
    }
acbd46
}
acbd46
acbd46
acbd46
#
acbd46
# quotedString returns a string which yields the original string when parsed
acbd46
# by a shell.
acbd46
#
acbd46
acbd46
sub quotedString
acbd46
{
acbd46
    local ($in) = @_;
acbd46
acbd46
    $in =~ s/\'/\'\"\'\"\'/g;
acbd46
acbd46
    return "'$in'";
acbd46
}
acbd46
acbd46
acbd46
#
acbd46
# removeSlashes turns slashes into underscores for use as a file name.
acbd46
#
acbd46
acbd46
sub removeSlashes
acbd46
{
acbd46
    local ($in) = @_;
acbd46
acbd46
    $in =~ s|/|_|g;
acbd46
acbd46
    return "$in";
acbd46
}
acbd46
acbd46
acbd46
#
acbd46
# Usage
acbd46
#
acbd46
acbd46
sub Usage
acbd46
{
acbd46
    die("\nusage: $prog [:<number>] [-name <desktop-name>] [-depth <depth>]\n".
acbd46
	"                 [-geometry <width>x<height>]\n".
acbd46
	"                 [-pixelformat rgbNNN|bgrNNN]\n".
acbd46
	"                 [-fp <font-path>]\n".
acbd46
	"                 [-cc <visual>]\n".            
acbd46
	"                 [-fg]\n".
acbd46
	"                 [-autokill]\n".
acbd46
	"                 [-noxstartup]\n".
acbd46
	"                 [-xstartup <file>]\n".
acbd46
	"                 <Xvnc-options>...\n\n".
acbd46
	"       $prog -kill <X-display>\n\n".
acbd46
	"       $prog -list\n\n");
acbd46
}
acbd46
acbd46
acbd46
#
acbd46
# List
acbd46
#
acbd46
acbd46
sub List
acbd46
{
acbd46
    opendir(dir, $vncUserDir);
acbd46
    my @filelist = readdir(dir);
acbd46
    closedir(dir);
acbd46
    print "\nTigerVNC server sessions:\n\n";
acbd46
    print "X DISPLAY #\tPROCESS ID\n";
acbd46
    foreach my $file (@filelist) {
acbd46
	if ($file =~ /$host:(\d+)$\.pid/) {
acbd46
	    chop($tmp_pid = `cat $vncUserDir/$file`);
acbd46
	    if (kill 0, $tmp_pid) {
acbd46
		print ":".$1."\t\t".`cat $vncUserDir/$file`;
acbd46
	    } else {
acbd46
		unlink ($vncUserDir . "/" . $file);
acbd46
	    }
acbd46
	}
acbd46
    }
acbd46
    exit;
acbd46
}
acbd46
acbd46
acbd46
#
acbd46
# Kill
acbd46
#
acbd46
acbd46
sub Kill
acbd46
{
acbd46
    $opt{'-kill'} =~ s/(:\d+)\.\d+$/$1/; # e.g. turn :1.0 into :1
acbd46
acbd46
    if ($opt{'-kill'} =~ /^:\d+$/) {
acbd46
	$pidFile = "$vncUserDir/$host$opt{'-kill'}.pid";
acbd46
    } else {
acbd46
	if ($opt{'-kill'} !~ /^$host:/) {
acbd46
	    die "\nCan't tell if $opt{'-kill'} is on $host\n".
acbd46
		"Use -kill :<number> instead\n\n";
acbd46
	}
acbd46
	$pidFile = "$vncUserDir/$opt{'-kill'}.pid";
acbd46
    }
acbd46
acbd46
    if (! -r $pidFile) {
acbd46
	die "\nCan't find file $pidFile\n".
acbd46
	    "You'll have to kill the Xvnc process manually\n\n";
acbd46
    }
acbd46
acbd46
    $SIG{'HUP'} = 'IGNORE';
acbd46
    chop($pid = `cat $pidFile`);
acbd46
    warn "Killing Xvnc process ID $pid\n";
acbd46
acbd46
    if (kill 0, $pid) {
acbd46
	system("kill $pid");
acbd46
	sleep(1);
acbd46
	if (kill 0, $pid) {
acbd46
	    print "Xvnc seems to be deadlocked.  Kill the process manually and then re-run\n";
acbd46
	    print "    ".$0." -kill ".$opt{'-kill'}."\n";
acbd46
	    print "to clean up the socket files.\n";
acbd46
	    exit
acbd46
	}
acbd46
acbd46
    } else {
acbd46
	warn "Xvnc process ID $pid already killed\n";
acbd46
	$opt{'-kill'} =~ s/://;
acbd46
acbd46
	if (-e "/tmp/.X11-unix/X$opt{'-kill'}") {
acbd46
	    print "Xvnc did not appear to shut down cleanly.";
acbd46
	    print " Removing /tmp/.X11-unix/X$opt{'-kill'}\n";
acbd46
	    unlink "/tmp/.X11-unix/X$opt{'-kill'}";
acbd46
	}
acbd46
	if (-e "/tmp/.X$opt{'-kill'}-lock") {
acbd46
	    print "Xvnc did not appear to shut down cleanly.";
acbd46
	    print " Removing /tmp/.X$opt{'-kill'}-lock\n";
acbd46
	    unlink "/tmp/.X$opt{'-kill'}-lock";
acbd46
	}
acbd46
    }
acbd46
acbd46
    unlink $pidFile;
acbd46
    exit;
acbd46
}
acbd46
acbd46
acbd46
#
acbd46
# ParseOptions takes a list of possible options and a boolean indicating
acbd46
# whether the option has a value following, and sets up an associative array
acbd46
# %opt of the values of the options given on the command line. It removes all
acbd46
# the arguments it uses from @ARGV and returns them in @optArgs.
acbd46
#
acbd46
acbd46
sub ParseOptions
acbd46
{
acbd46
    local (@optval) = @_;
acbd46
    local ($opt, @opts, %valFollows, @newargs);
acbd46
acbd46
    while (@optval) {
acbd46
	$opt = shift(@optval);
acbd46
	push(@opts,$opt);
acbd46
	$valFollows{$opt} = shift(@optval);
acbd46
    }
acbd46
acbd46
    @optArgs = ();
acbd46
    %opt = ();
acbd46
acbd46
    arg: while (defined($arg = shift(@ARGV))) {
acbd46
	foreach $opt (@opts) {
acbd46
	    if ($arg eq $opt) {
acbd46
		push(@optArgs, $arg);
acbd46
		if ($valFollows{$opt}) {
acbd46
		    if (@ARGV == 0) {
acbd46
			&Usage();
acbd46
		    }
acbd46
		    $opt{$opt} = shift(@ARGV);
acbd46
		    push(@optArgs, $opt{$opt});
acbd46
		} else {
acbd46
		    $opt{$opt} = 1;
acbd46
		}
acbd46
		next arg;
acbd46
	    }
acbd46
	}
acbd46
	push(@newargs,$arg);
acbd46
    }
acbd46
acbd46
    @ARGV = @newargs;
acbd46
}
acbd46
acbd46
acbd46
# Routine to make sure we're operating in a sane environment.
acbd46
sub SanityCheck
acbd46
{
acbd46
    local ($cmd);
acbd46
acbd46
    # Get the program name
acbd46
    ($prog) = ($0 =~ m|([^/]+)$|);
acbd46
acbd46
    #
acbd46
    # Check we have all the commands we'll need on the path.
acbd46
    #
acbd46
acbd46
 cmd:
acbd46
    foreach $cmd ("uname","xauth") {
acbd46
	for (split(/:/,$ENV{PATH})) {
acbd46
	    if (-x "$_/$cmd") {
acbd46
		next cmd;
acbd46
	    }
acbd46
	}
acbd46
	die "$prog: couldn't find \"$cmd\" on your PATH.\n";
acbd46
    }
acbd46
acbd46
    if($exedir eq "") {
acbd46
      cmd2:
acbd46
	foreach $cmd ("Xvnc","vncpasswd") {
acbd46
	    for (split(/:/,$ENV{PATH})) {
acbd46
		if (-x "$_/$cmd") {
acbd46
		    next cmd2;
acbd46
		}
acbd46
	    }
acbd46
	    die "$prog: couldn't find \"$cmd\" on your PATH.\n";
acbd46
	}
acbd46
    }
acbd46
    else {
acbd46
      cmd3:
acbd46
	foreach $cmd ($exedir."Xvnc",$exedir."vncpasswd") {
acbd46
	    for (split(/:/,$ENV{PATH})) {
acbd46
		if (-x "$cmd") {
acbd46
		    next cmd3;
acbd46
		}
acbd46
	    }
acbd46
	    die "$prog: couldn't find \"$cmd\".\n";
acbd46
	}
acbd46
    }
acbd46
acbd46
    if (!defined($ENV{HOME})) {
acbd46
	die "$prog: The HOME environment variable is not set.\n";
acbd46
    }
acbd46
acbd46
    #
acbd46
    # Find socket constants. 'use Socket' is a perl5-ism, so we wrap it in an
acbd46
    # eval, and if it fails we try 'require "sys/socket.ph"'.  If this fails,
acbd46
    # we just guess at the values.  If you find perl moaning here, just
acbd46
    # hard-code the values of AF_INET and SOCK_STREAM.  You can find these out
acbd46
    # for your platform by looking in /usr/include/sys/socket.h and related
acbd46
    # files.
acbd46
    #
acbd46
acbd46
    chop($os = `uname`);
acbd46
    chop($osrev = `uname -r`);
acbd46
acbd46
    eval 'use Socket';
acbd46
    if ($@) {
acbd46
	eval 'require "sys/socket.ph"';
acbd46
	if ($@) {
acbd46
	    if (($os eq "SunOS") && ($osrev !~ /^4/)) {
acbd46
		$AF_INET = 2;
acbd46
		$SOCK_STREAM = 2;
acbd46
	    } else {
acbd46
		$AF_INET = 2;
acbd46
		$SOCK_STREAM = 1;
acbd46
	    }
acbd46
	} else {
acbd46
	    $AF_INET = &AF_INET;
acbd46
	    $SOCK_STREAM = &SOCK_STREAM;
acbd46
	}
acbd46
    } else {
acbd46
	$AF_INET = &AF_INET;
acbd46
	$SOCK_STREAM = &SOCK_STREAM;
acbd46
    }
acbd46
} 
acbd46
acbd46
sub NotifyAboutDeprecation
acbd46
{
809922
    warn "\nWARNING: vncserver has been replaced by a systemd unit and is now considered deprecated and removed in upstream.\n";
acbd46
    warn "Please read /usr/share/doc/tigervnc/HOWTO.md for more information.\n";
acbd46
}