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