#!/usr/bin/perl

&ReadForm;

$certfile = $FIELDS{'certfile'};

# valid certtype values are: "ca", "server", "user", "email"
$certtype = $FIELDS{'certtype'};

open(CERT,"/usr/local/apache/cgi-bin/ssl/$certfile") || die &Error;
@certificate = <CERT>;
close(CERT);

print "Content-type: application/x-x509-$certtype-cert\n\n";
print @certificate;

##############################################################
#### Procedures
##############################################################

sub ReadForm
{
  if ($ENV{'REQUEST_METHOD'} eq 'GET')
  {
    @pairs = split(/&/, $ENV{'QUERY_STRING'});
  }
  elsif ($ENV{'REQUEST_METHOD'} eq 'POST')
  {
    read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
    @pairs = split(/&/, $buffer);
  }
  
  foreach $pair (@pairs)
  {
    ($name, $value) = split(/=/, $pair);

    $name =~ tr/+/ /;
    $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

    $value =~ s/<!--(.|\n)*-->//g;

    $FIELDS{$name} = $value;
  }
}

sub Error {
    print "Content-type: text/html\n\n";
    print "<p><p><center><h1>Can't open file</h1></center>\n";
}
