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