#!/usr/bin/perl
## scep.pl - CGI script for the OpenXPKI SCEP server
##
## Written by Alexander Klink for the OpenXPKI project
## Copyright (c) 2006 by The OpenXPKI project
## $Revision$

use strict;
use warnings;
use CGI qw( -debug );
use Config::Std;
use NetAddr::IP;
use Data::Dumper;

require OpenXPKI::Client::SCEP;
my $query = new CGI;

# Configuration via Config::Std;
# set config file in the line below
# TODO: depending on performance, change into a simple
#       include and use perl syntax in config file.
my $configfile = 'scep.cfg' || die('Could not read config file');
read_config $configfile => my %config;
my $socket  = $config{global}{socket};
my $realm   = $config{global}{realm};
my $iprange = $config{global}{iprange};

my $allowed_range = new NetAddr::IP $iprange; # the allowed IP range
					      # from the config file
my $requesting_host = new NetAddr::IP $ENV{'REMOTE_ADDR'}; # the host

# Check if requesting host is allowed to talk to us
if (!$requesting_host->within($allowed_range)) {
# TODO: better response?
    print "Content-Type: text/plain\n\nGo away\n";
    die("Unauthorized access from $requesting_host");
}
else {
    # Fetch SCEP message from CGI (cf. Section 3.1 of the SCEP draft)
    # http://www.ietf.org/internet-drafts/draft-nourse-scep-13.txt
    my $operation = $query->param('operation');
    my $message   = $query->param('message');
    
    # OpenXPKI::Client::SCEP does the actual work
    my $scep_client = OpenXPKI::Client::SCEP->new(
        {
        SERVICE    => 'SCEP',
        REALM      => $realm,
        SOCKETFILE => $socket,
        OPERATION  => $operation,
        MESSAGE    => $message,
        });
    my $result = $scep_client->send_request();
    print $result;
}

