#!/usr/bin/perl -w -T

# Note: In theory, all this can be done by 'pveproxy' daemon. But som API call
# still have blocking code, so we use a separate daemon to avoid that the console
# get blocked.

$ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';

delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};  

use strict;
use English;
use Getopt::Long;
use PVE::SafeSyslog;
use PVE::APIDaemon;

my $pidfile = "/var/run/pveproxy/spiceproxy.pid";
my $lockfile = "/var/lock/spiceproxy.lck";

my $opt_debug;

initlog ('spiceproxy');

if (!GetOptions ('debug' => \$opt_debug)) {
    die "usage: $0 [--debug]\n";
}

$SIG{'__WARN__'} = sub {
    my $err = $@;
    my $t = $_[0];
    chomp $t;
    syslog('warning', "WARNING: %s", $t);
    $@ = $err;
};

$0 = "spiceproxy";

my $gid = getgrnam('www-data') || die "getgrnam failed - $!\n";
POSIX::setgid($gid) || die "setgid $gid failed - $!\n";
$EGID = "$gid $gid"; # this calls setgroups
my $uid = getpwnam('www-data') || die "getpwnam failed - $!\n";
POSIX::setuid($uid) || die "setuid $uid failed - $!\n";

# just to be sure
die "detected strange uid/gid\n" if !($UID == $uid && $EUID == $uid && $GID eq "$gid $gid" && $EGID eq "$gid $gid");

# we use same ALLOW/DENY/POLICY as pveproxy
my $proxyconf = PVE::APIDaemon::read_proxy_config();

my $cpid;
my $daemon;
eval {
    $daemon = PVE::APIDaemon->new(
	port => 3128, 
	keep_alive => 0,
	max_workers => 1, # do we need more?
	max_conn => 500,
	lockfile => $lockfile,
	debug => $opt_debug,
	spiceproxy => 1,
	logfile => '/var/log/pveproxy/access.log',
	allow_from => $proxyconf->{ALLOW_FROM},
	deny_from => $proxyconf->{DENY_FROM},
	policy => $proxyconf->{POLICY},
    );
};

my $err = $@;

if ($err) {
    syslog ('err' , "unable to start server: $err");
    print STDERR $err;
    exit (-1);
}

if ($opt_debug || !($cpid = fork ())) {

    $SIG{PIPE} = 'IGNORE';
    $SIG{INT} = 'IGNORE' if !$opt_debug;

    $SIG{TERM} = $SIG{QUIT} = sub { 
	syslog ('info' , "server closing");

	$SIG{INT} = 'DEFAULT';

	unlink "$pidfile";

	exit (0);
    };

    syslog ('info' , "starting server");

    if (!$opt_debug) {
	# redirect STDIN/STDOUT/SDTERR to /dev/null
	open STDIN,  '</dev/null' || die "can't read /dev/null  [$!]";
	open STDOUT, '>/dev/null' || die "can't write /dev/null [$!]";
	open STDERR, '>&STDOUT' || die "can't open STDERR to STDOUT [$!]";
    }

    POSIX::setsid(); 
    
    eval {
	$daemon->start_server();
    };
    my $err = $@;

    if ($err) {
	syslog ('err' , "unexpected server error: $err");
	print STDERR $err if $opt_debug;
	exit (-1);
    }

} else {

    open (PIDFILE, ">$pidfile") || 
	die "cant write '$pidfile' - $! :ERROR";
    print PIDFILE "$cpid\n";
    close (PIDFILE) || 
	die "cant write '$pidfile' - $! :ERROR";
}

exit (0);

__END__

=head1 NAME
                                          
spiceproxy - SPICE proxy server for Proxmox VE

=head1 SYNOPSIS

spiceproxy [--debug]

=head1 DESCRIPTION

SPICE proxy server for Proxmox VE. Listens on port 3128.

=head1 Host based access control

It is possible to configure apache2 like access control lists. Values are read 
from file /etc/default/pveproxy (see 'pveproxy' for details).

=head1 FILES

 /etc/default/pveproxy

=head1 COPYRIGHT AND DISCLAIMER

 Copyright (C) 2007-2013 Proxmox Server Solutions GmbH

 This program is free software: you can redistribute it and/or modify it
 under the terms of the GNU Affero General Public License as published
 by the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public
 License along with this program.  If not, see
 <http://www.gnu.org/licenses/>.

