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