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