#!/usr/bin/perl -w
#
# dpkg-sig signs deb-files in a standard way
#
# (c) Andreas Barth <aba@not.so.argh.org> 2003
# (c) Marc Brockschmidt <marc@dch-faq.de> 2004
#
# This patched version is also compatible with signatures in 'debdelta' files,
# with deb files where data.tar is compressed by bzip2 or lzma,
# and with the file format of the '/usr/bin/ar' tool
# (that adds a trailing "/" to filenames in the headers).
# 
# (c) Andrea Mennucc <mennucc1@debian.org> 2009
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#    Upstream web site is http://dpkg-sig.turmzimmer.net/

=pod

=head1 NAME

B<dpkg-sig> - Debian package archive (.deb) signature generation and verification tool

=head1 DESCRIPTION

This is the description of the source code, trying to help people to understand
how B<dpkg-sig> works.

=head1 SYNOPSIS

=cut

use strict;
use Getopt::Long;
use Data::Dumper;
use IPC::Open2;
use IPC::Open3;
use File::Temp qw(tempdir);
use File::Copy qw(move);
use File::Basename qw(dirname basename);
$| = 1;

#Global variables (used for configuration and/or command line stuff) 
my ($sign, $list, $verify, $verify_role, $verify_exact, $client, $cache_pass,
    $pass_file, $key, $maintainer, $maintainer_pr, $verbose, %config, $tempdir,
    %part_cache, $check_v2_sig, $check_v3_sig, $batch, $gpgoptions, 
    $passphrase, $remote_dpkg_sig, %ssh_connections, $sign_changes, 
    $get_hashes, $sign_hashes, $write_signature, $help, $DEBUG, 
	$verify_pattern, $remote_ssh_port);

my @configfiles = qw(/etc/devscripts.conf ~/.devscripts);

my $DPKG_SIG_VERSION = 0.13;

&process_cli_options();

#If wanted, print only help and exit:
if ($help) { &help; exit; }

#In client mode, we wait for commands and STDIN, we don't need the rest:
if ($client) {
	print "Welcome. This is dpkg-sig in client mode. Protocol version 6\n";
	&read_cmds();
	exit;
}

#Only load Config::File if we're not in the client mode:
eval { require Config::File; import Config::File qw(read_config_file); };
_die($@) if $@;

$tempdir = tempdir("debsigs-ng.XXXXXX", CLEANUP => 1, TMPDIR => 1);


&load_config(@configfiles);

$remote_dpkg_sig ||= "dpkg-sig";

my @files = @ARGV;

if ($sign_hashes || $write_signature) {
	for (@files) {
		unless (/\.dpkg-sig-hashes$/) {
			die _die("$_: Make sure all files were generated by dpkg-sig --get-hashes file\n");
		}
	}
	
	for my $file (@files) {
		if ($sign_hashes) {
			print "Processing $file...\n";
			sign_hashes($file);
			print "Signed hashes in $file...\n";
		} else {
			print "Processing $file...\n";		
			my @done = write_signature($file);
			print "Added signature to $_\n" for (@done);
		}
	}
	exit;
}

if (grep { ! /(?:deb|debdelta|changes)$/ } @files) {
	die _die("We can only work on debs, debdeltas, or changes files.");
}

if ($sign) {
	if (length($sign) > 9) {
		die _die("The signing name '$sign' is too long.");
	} elsif ($sign !~ /^[a-z]+$/) {
		die _die("The signing name '$sign' is not valid. Please use only letters.");
	}
}

if ($verify_role) {
	$verify_pattern = "^_gpg".$verify_role."[0-9A-Z]?\$";
} elsif ($verify_exact) {
	$verify_pattern = "^_gpg$verify_exact";
} else {
	$verify_pattern = "^_gpg.+";
}


#The main loop:
for my $exp (@files) {
	my @globbed_files = glob_exp($exp);
	die _die("Cannot find $exp: no such file") if (! @globbed_files);
	for my $file (@globbed_files) {
		if (($file =~ /\.deb$/) || ($file =~ /\.debdelta$/)) { #Yay! That's easy!
			print "Processing $file...\n";
			if ($sign) {
				sign_deb($sign, $file);
				print "Signed deb $file\n" if ! $batch;
			} elsif ($verify || $verify_role || $verify_exact) {
				my @verify_output = verify_deb($file, $verify_pattern);
				print @verify_output;
				exit 2 if grep { /^BADSIG/ } @verify_output;
				exit 3 if grep { /^UNKNOWNSIG/ } @verify_output;
			} elsif ($list) {
				for (get_deb_parts($file)) {
					print "$1\n" if ($_->[0] =~ /_gpg(.+)/);
				}
			} elsif ($get_hashes) {
				write_deb_info($get_hashes, $file);
				unlink "$file.dpkg-sig-hashes";
				add_part_to_ar_archive ("$file.dpkg-sig-hashes", "deb\n$get_hashes\n$file ".get_file_md5sum($file)."\n" , "control");
				add_part_to_ar_archive ("$file.dpkg-sig-hashes", _read_file("$tempdir/digests"), "deb0");
			}
			
		} else {
			print "--- Processing changes file $file:\n";
			my $changes_signed = 0;
			my (%new_debs, $sums_control_data, @deb_md5sums, $maintainer_from_changes);


			#Get default from *changes:
			unless ($maintainer || $key) {
				$maintainer_from_changes = 1;
				chomp($maintainer = `grep ^Changed-By: $file | cut -d " " -f 2-`);
				$maintainer = quotemeta($maintainer);
			}

			if ($get_hashes) {
				unlink "$file.dpkg-sig-hashes";
				$sums_control_data = "changes $file\n$get_hashes\n";
			}

			for my $deb (get_debs_from_changes($file, \$changes_signed)) {
				print "Processing $deb...\n";
				
				if ($sign) {
					my $r = sign_deb($sign, $deb);
					$new_debs{$r->[2]} = $r;
					print "Signed deb $deb\n" if ! $batch;
				} elsif ($verify || $verify_role || $verify_exact) {
					my @verify_output = verify_deb($deb, $verify_pattern);
					print @verify_output;
					exit 2 if grep { /^BADSIG/ } @verify_output;
					exit 3 if grep { /^UNKNOWNSIG/ } @verify_output;
				} elsif ($list) {
					for (get_deb_parts($deb)) {
						print "$1\n" if ($_->[0] =~ /_gpg(.+)/);
					}
				} elsif ($get_hashes) {
					$sums_control_data .= $deb." ".get_file_md5sum($deb)."\n";
					write_deb_info($get_hashes, $deb);
					push @deb_md5sums, _read_file("$tempdir/digests");
				}
			}

			if ($sign) {
				correct_changes_file($file, \%new_debs);
				sign_control_files($file) if ($sign_changes ne "no" && ! ($sign_changes eq "auto" && ! $changes_signed));
			} elsif ($get_hashes) {
				add_part_to_ar_archive ("$file.dpkg-sig-hashes", $sums_control_data , "control");
				for (my $i=0; $i<@deb_md5sums; $i++) {
					add_part_to_ar_archive ("$file.dpkg-sig-hashes", $deb_md5sums[$i], "deb$i");
				}				
			}

			undef $maintainer if ($maintainer_from_changes);
		}
	}
}

#Clean our ssh connections:
for (values %ssh_connections) {
	my ($pid, $readerfh, $writerfh) = @$_;
	print $writerfh "quit\n";

	sleep 1;
	kill $pid;
}

exit;

=pod

=head2 I<\@file_info> = sign_deb (I<$signing_role>, I<$file>)

Does everything needed to add a signature to I<$file>:

=over 4

=item * Verifies existing signatures

=item * Creates the meta-data that is actually signed

=item * Calls gpg to sign the meta-data.

=item * Adds the signature to I<$file>

=back

Returns a reference to an array containing the new md5sum, the new size
and the name of the signed deb.

=cut

sub sign_deb {
	my ($sig_name, $file) = @_;

	#Check the existing signatures:
	my @verify = verify_deb($file, "^_gpg.+");
	if (grep { /^BADSIG/ } @verify) {
		print STDERR "Can't sign $file, some signatures are invalid:\n".(join "", grep { /^BADSIG/ } @verify)."\n";
		exit 2;
	}

	#This also chooses the right sig name:
	$sig_name = write_deb_info($sig_name, $file);

	sign_file ("$tempdir/digests", "$tempdir/digests.asc", "no_detach");

	#Read sig:
	my $sig = _read_file ($tempdir."/digests.asc");

	return add_sig_to_deb($file, $sig, $sig_name);
}

=pod

=head2 I<$signature_name> = write_deb_info (I<$signing_role>, I<$file>)

Creates a digests.asc file with the meta-data of I<$file> in dpkg-sig's tempdir:

=over 4

=item * Gets the needed information from I<$file>

=item * Chooses the name of the signature

=item * Writes a file in a RFC822-like format containing the meta-data

=back

Returns the name that should be used to add the file to the deb.

=cut

sub write_deb_info {
	my ($sig_name, $deb) = @_;

	#Get digests:
	my $digests = get_deb_digests($deb);

	#Get name for our new signature part of the archive
	$sig_name = get_sig_name($sig_name, $digests, $deb);

	#Create digests file
	unlink ($tempdir."/digests.asc");

	my $signer_name = $key || $maintainer;
	if ($signer_name =~ /^(0x)?[0-9A-F]{8}$/i) {
		my $uidline = (grep /^uid:/, qx/gpg --list-keys --with-colons --fixed-list-mode $signer_name/)[0];
		$signer_name = (split /:/, $uidline)[9] if defined $uidline;
		chomp($signer_name);
	}

	my @data;
	push @data, "Version: 4\n";
	push @data, "Signer: $signer_name\n";
	push @data, "Date: " . localtime() . "\n";
	push @data, "Role: $1\n" if $sig_name =~ /^_gpg(\S+?)[A-Z0-9]?$/;
	
	push @data, "Files: \n";
	for my $part_info (@$digests) {
		push @data, "\t" . join (" ", reverse @$part_info) . "\n";
	}

	_write_file("$tempdir/digests", @data);

	return $sig_name
}


=pod

=head2 sign_hashes (I<$file>)

Signs a .dpkg-sig-hashes I<$file> containing the digests of a deb/changes file:

=over 4

=item * Checks the .dpkg-sig-hashes file to see if it really was created by us

=item * Creates a new archive, containing the old control file

=item * Signs the digests and adds the clearsigned data to the the new archive

=item * Substitutes the old file by the new, signed one.

=back

=cut

sub sign_hashes {
	my ($file) = @_;

	unlink ($tempdir."/digests");			
	unlink ($tempdir."/digests.asc");
	unlink ($tempdir."/hashes.signed");

	#We don't need the control data, we just want to check if this is real
	#dpkg-sig generated hashes archiv:
	my $control = get_archive_part($file, "control");
	if ($control !~ /^(deb|changes)/) {
		die _die("$file seems not to be a dpkg-sig hash archive");
	}

	add_part_to_ar_archive($tempdir."/hashes.signed", $control, "control");

	#Now sign all hashes:
	my $num = 0;
	for (get_deb_parts($file)) {
		my $part_name = $_->[0];
		if ($part_name !~ /^(deb\d+|control)$/) {
			print STDERR "W: $file contains $part_name, which shouldn't happen in dpkg-sig hash archive\n";
		} elsif ($part_name =~ /^deb\d+/) {
			my $data = get_archive_part($file, $part_name);
			
			if ($data =~ /-----BEGIN PGP SIGNATURE-----/) {
				die _die("$file seems to be already signed!\n");
			}

			_write_file($tempdir."/digests", $data);
			sign_file("$tempdir/digests", "$tempdir/digests.asc", "no_detach");
			my $s_data = _read_file($tempdir."/digests.asc");

			add_part_to_ar_archive($tempdir."/hashes.signed", $s_data, "deb".$num++);
		}
	}

	move($tempdir."/hashes.signed", $file);
}

=pod

=head2 I<@changed_files> = write_signature (I<$file>)

Adds the signatures from a signed .dpkg-sig-hashes I<$file> to the signed debs:

=over 4

=item * Checks the .dpkg-sig-hashes file to see if it really was created by us

=item * Tries to find out where we find the debs that have sigs in the .dpkg-sig-hashes

=item * Checks if the debs were changed since they were signed

=item * Adds signatures from the .dpkg-sig-hashes file to the debs

=item * If needed, it corrects the changes file to reflect the new sizes/md5sums of the debs

=back

Returns the pathes of the debs that were changed.

=cut

sub write_signature {
	my ($file) = @_;
	my @done;

	unlink ($tempdir."/digests");
	unlink ($tempdir."/digests.asc");
	unlink ($tempdir."/hashes.signed");

	#Get control data:
	my @control = split (/\n/, get_archive_part($file, "control"));
	if ($control[0] !~ /^(deb|changes)/) {
		die _die("$file seems not to be a dpkg-sig hash archive");
	}
	chomp(my $sig_name = $control[1]);

	my ($num, %new_debs) = (0);
	for (get_ar_parts($file)) {
		my $part_name = $_->[0];
		if ($part_name !~ /^(deb\d+|control)$/) {
			print STDERR "W: $file contains $part_name, which shouldn't happen in dpkg-sig hash archive\n";
		} elsif ($part_name =~ /^deb\d+/) {
			my $sig = get_archive_part($file, $part_name);

			if ($sig !~ /-----BEGIN PGP SIGNATURE-----/) {
				die _die("$file seems to be unsigned!\n");
			}

			#deb$num is the detached sig for the deb named in control line $num + 1
			#Get the name and the md5sum:
			my ($name, $md5sum) = split / /, $control[$num + 2];

			my $path;
			
			#Try to find the deb in this dir:
			if (file_readable(basename($name)) && get_file_md5sum(basename($name)) eq $md5sum) {
				$path = basename($name);
			#Now try the path in the hashes file:
			} elsif (file_readable($name) && get_file_md5sum($name) eq $md5sum) {
				$path = $name;
			#Wrong md5sum
			} elsif (! (get_file_md5sum(basename($name)) eq $md5sum || get_file_md5sum($name) eq $md5sum)) {
				die _die("The md5sum for $name is wrong. Please use an archive of signed hashes of the version of the file existing now.");
			#We don't find the damn file!
			} else {
				die _die("Can't find $name. Please start dpkg-sig either in the dir with the debs to sign or in the dir where you got the hashes.");
			}

			push @done, $path;

			$sig_name = get_sig_name($sig_name, [get_deb_parts($path)], $path);
			my $r = add_sig_to_deb($path, $sig, $sig_name);
			$new_debs{$r->[2]} = $r;

			$num++;
		}
	}

	if ($control[0] =~ /^changes (.+)$/) {
		if (file_readable(basename($1))) {
			correct_changes_file(basename($1), \%new_debs);
			print "Corrected changes file ".basename($1)."\n";
		} elsif (file_readable($1)) {
			correct_changes_file($1, \%new_debs);
			print "Corrected changes file $1\n";			
		} else {
			print STDERR "Can't find changes file $1, so won't correct it.\n";
		}
	}

	return @done;
}

=pod

=head2 I<@output> = verify_deb (I<$deb>, I<$verify_pattern>)

Verifies all signatures in I<$deb> with names matching I<$verify_pattern>:

=over 4

=item * Gets the digests of all parts of I<$deb>.

=item * Skips all signatures that don't match I<$verify_pattern>.

=item * Writes the signatures to $tempdir/digests.asc.

=item * Calls a function to check if $tempdir/digests.asc is valid in the v4 format, then tries v3 and v2.

=back

Returns its output. This is needed to achieve a "silent" verification when signing a deb.

=cut

sub verify_deb {
	my ($deb, $verify_pattern) = @_;
	my @return;

	#Get MD5 sums:
	my $digests = get_deb_digests($deb);

	for (my $n=0;$n<@$digests;$n++) {
		my ($part_name, $size, $sha1sum, $md5sum) = @{@$digests[$n]};
		next if $part_name !~ /$verify_pattern/;
		
		unlink ($tempdir."/digests.asc");
		unlink ($tempdir."/digests");

		my $sig = get_archive_part($deb, $part_name);
		_write_file($tempdir."/digests.asc", $sig);

		my ($status, @info);

		if ($sig =~ /BEGIN PGP SIGNED MESSAGE/) {
			$status = verify_deb_sig_v4($part_name, $n, $digests, \@info, \@return);
		}
		if ($check_v3_sig && (!$status || $status eq "BAD")) {
			$status = verify_deb_sig_v3($part_name, $n, $digests, \@info, \@return);
		}
		if ($check_v2_sig && (!$status || $status eq "BAD")) {
			$status = verify_deb_sig_v2($part_name, $n, $digests, \@info, \@return);
		}

		if      ($status && $status eq "GOOD") {
			push @return, "GOODSIG $part_name $info[0] $info[2]\n";
		} elsif ($status && $status eq "UNKNOWN" && (! $batch || $batch >= 2)) {
			push @return, "UNKNOWNSIG $part_name $info[0]\n";
		} else {
			push @return, "BADSIG $part_name\n"
		}
	}

	return @return;
}

=pod

=head2 I<$verification_status> = verify_deb_sig_v4 (I<$part_name>, I<$part_number>, I<\@digests>, I<\@info>, I<\@return>)

Verifies if $tempdir/digests is a valid (version 4) signature for the deb described with I<\@digests>:

=over 4

=item * Calls gpg to verify the OpenPGP signature in $tempdir/digests.asc itself.

=item * Parses the signature to get the digests that were actually signed

=item * Compare the digests of the deb and those extracted from the signature to see if the deb was changed.

=item * Check that the name in the ar archive matches the "Role" field in the signature.

=item * DON'T check the Signer- and Date-Fiels.

=item * Check that at least the digests for control.tar.gz, data.tar.gz and debian-binary were signed.

=back

Returns if the the signature is good, by an unknown key, or bad.

=cut


sub verify_deb_sig_v4 {
	my ($part_name, $part_number, $digests, $info, $return) = @_;

	#Check signature:
	my @cmdline = qw(gpg --openpgp --decrypt --no-auto-check-trustdb --batch
	                     --no-tty --status-fd 1 2>&1);
	push @cmdline, "--output", "$tempdir/digests", "$tempdir/digests.asc";
	my $res=qx/@cmdline/;
	@$info = split(/ /, $1 ) if $res =~ /^\[GNUPG:\] VALIDSIG (.*)$/m;

	if ($res =~ /^\[GNUPG:\] NO_PUBKEY \S{8}(\S{8})/m) {
		$info->[0] = $1;
		return "UNKNOWN";
	}

	return "FORCE_BAD" unless $res =~ /^\[GNUPG:\] GOOD/m;

	#Now find out if the deb contains the data that was signed:
	open (FH, "<", "$tempdir/digests") || die "Can't open $tempdir/digests: $!";
	my (%data, $field_name);
	while (<FH>) {
		if (/^(\S+):\s*(.*)$/) {
			$field_name = lc($1);
			$data{$field_name} = $2 || "";
		} elsif (/^\s+(.+)$/ && $field_name) {
			$data{$field_name} .= ($data{$field_name} ? "\n" : "") . $1;
		}
	}
	close FH;

	if ($data{version} > 4) {
		push @$return, "$part_name: v$data{version} signature, dpkg-sig is too old to check it.\n";
		return "FORCE_BAD";
	}
	
	#for each file (and hashes) listed in the signature, check the computed hashes in the archive
	for my $file_info (split /\n/, $data{files}) {
		my ($md5sum, $sha1sum, $size, $name) = split /\s+/, $file_info;

		my $checked_something=0;		
		for my $member_info (@$digests) {
			if ($member_info->[0] eq $name) {
				$checked_something = 1;
				if ($member_info->[1] ne $size) {
					push @$return, "$part_name: ${name}'s size differs from signed size.\n" if $verbose;
					return "FORCE_BAD";
				} elsif ($member_info->[2] ne $sha1sum) {
					push @$return, "$part_name: ${name}'s sha1sum differs from signed size.\n" if $verbose;
					return "FORCE_BAD";
				} elsif ($member_info->[3] ne $md5sum) {
					push @$return, "$part_name: ${name}'s md5sum differs from signed size.\n" if $verbose;
					return "FORCE_BAD";
				}
			}
		}
		
		unless ($checked_something) {
			push @$return, "$part_name: ${name} signed, but not in the deb.\n" if $verbose;
			return "FORCE_BAD";
		}
	}
	
	#for each file contained in the archive, check that it is listed in the signature
	for my $member_info (@$digests) {
	    my $part_present=0;		
	    if ($member_info->[0] =~ /^_gpg/) {
		# ignore any member of the archive whose name starts with _gpg
	    } else {
		for  my $file_info (split /\n/, $data{files}) {
		    my ($md5sum, $sha1sum, $size, $name) = split /\s+/, $file_info;
		    if ($member_info->[0] eq $name) {
			$part_present = 1;
		    }
		}
		unless ($part_present) {
		    push @$return, "$part_name: " . $member_info->[0] . " in deb, but not signed.\n" if $verbose;
		    return "FORCE_BAD";
		}
	    }
	}

	$part_name =~ /^_gpg(\S+?)[A-Z0-9]?$/;
	if (($data{role} ne $1) &&  (($data{role} . "/") ne $1)) {
		push @$return, "$part_name: signature name and signed role differ.\n" if $verbose;
		return "FORCE_BAD";
	}

	return "GOOD";
}

=pod


=head2 I<$verification_status> = verify_deb_sig_v3 (I<$part_name>, I<$part_number>, I<\@digests>, I<\@info>, I<\@return>)

Verifies if $tempdir/digests is a valid (version 3) signature for the deb described with I<\@digests>:

=over 4

=item * Creates a file in $tempdir/digests that contains the signing role and the digests from the current deb.

=item * Calls gpg to verify that the detached OpenPGP signature in $tempdir/digests.asc is valid for $tempdir/digests.

=back

Returns if the the signature is good, by an unknown key, or bad.

=cut

sub verify_deb_sig_v3 {
	my ($part_name, $part_number, $digests, $info, $return) = @_;

	my @cmdline = qw(gpg --openpgp --verify --no-auto-check-trustdb --batch
	                     --no-tty --status-fd 1 2>&1);
	push @cmdline, "$tempdir/digests.asc", "$tempdir/digests";

	push @$return, "$part_name: Invalid v4 sig ... Trying v3\n" if $verbose;

	$part_name =~ s/^_gpg(\S+?)[A-Z0-9]?$/$1/;

	open (FH, ">", $tempdir."/digests") || die _die("Couldn't open $tempdir/digests: $!");
	print FH $part_name, "\n";
	print FH join "\n", map { $_->[3] . "  " . $_->[0] } @$digests[0..$part_number-1];
	print FH "\n";
	close FH;

	my $res=qx/@cmdline/;
	@$info = split(/ /, $1 ) if $res =~ /^\[GNUPG:\] VALIDSIG (.*)$/m;
	if ($res =~ /^\[GNUPG:\] NO_PUBKEY \S{8}(\S{8})/m) {
		$info->[0] = $1;
		return "UNKNOWN";
	}
	return "BAD" unless $res =~ /^\[GNUPG:\] GOOD/m;
	return "GOOD";
}

=pod

=head2 I<$verification_status> = verify_deb_sig_v2 (I<$part_name>, I<$part_number>, I<\@digests>, I<\@info>, I<\@return>)

Verifies if $tempdir/digests is a valid (version 2) signature for the deb described with I<\@digests>:

=over 4

=item * Creates a file in $tempdir/digests that contains the digests from the current deb.

=item * Calls gpg to verify that the detached OpenPGP signature in $tempdir/digests.asc is valid for $tempdir/digests.

=back


Returns if the the signature is good, by an unknown key, or bad.

=cut

sub verify_deb_sig_v2 {
	my ($part_name, $part_number, $digests, $info, $return) = @_;

	my @cmdline = qw(gpg --openpgp --verify --no-auto-check-trustdb --batch
	                     --no-tty --status-fd 1 2>&1);
	push @cmdline, "$tempdir/digests.asc", "$tempdir/digests";

	push @$return, "$part_name: Invalid v3 sig ... Trying v2\n" if $verbose;
	
	open (FH, ">", $tempdir."/digests") || die _die("Couldn't open $tempdir/digests: $!");
	print FH join "\n", map { $_->[3] . "  " . $_->[0] } @$digests[0..$part_number-1];
	print FH "\n";
	close FH;
	
	my $res= qx/@cmdline/;
	@$info = split(/ /, $1 ) if $res =~ /^\[GNUPG:\] VALIDSIG (.*)$/m;
	if ($res =~ /^\[GNUPG:\] NO_PUBKEY \S{8}(\S{8})/m) {
		$info->[0] = $1;
		return "UNKNOWN";
	}
	return "BAD" unless $res =~ /^\[GNUPG:\] GOOD/m;
	return "GOOD";
}

=pod

=head2 I<$sig_name> = get_sig_name (I<$sig_name>, I<\@parts>, I<$deb>)

Tries to find a filename for the signature. Receives the role and constructs
a name not already present in I<$deb>.

Returns the final name or dies if it wasn't possible to construct a name.

=cut

sub get_sig_name {
	my ($sig_name, $parts, $deb) = @_;

	$sig_name = "_gpg".$sig_name;
	if (grep { $_->[0] eq $sig_name } @$parts) {
		my $changed = 0;
		for my $ext (0..9, "A" .. "Z") {
			if (! grep { $_->[0] eq $sig_name.$ext} @$parts) {
				$sig_name .= $ext;
				++$changed;
				last;
			}
		}
		die _die("$deb: Couldn't get a name for the signature part") if ! $changed;
	}

	return $sig_name;
}

=pod

=head2 correct_changes_file (I<$changes>, I<\%new_deb_info>)

Receives a path to a changes file I<$changes> and a hash reference 
I<\%new_deb_info> containing new sizes and md5sums of debs in that changes
file. It'll parse the changes file, replace the old values by the new ones.
If the file is signed, the signature will be stripped (as it would be 
invalid anyway).

=cut

sub correct_changes_file {
	my ($changes, $new_deb_info) = @_;

	if ($changes =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($changes);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "correct_changes_file $file\n";
		
		my ($response, $t);
		$response = '';
		do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
		chomp($response);

		if ($response =~ /^300 /) {
			for (keys %$new_deb_info) {
				print $writerfh join (" ", @{$new_deb_info->{$_}}), "\n";
			}
			print $writerfh ".\n";
			
			$response = '';
			do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
			chomp($response);

			if ($response !~ /^200 /) {
				die _die("remote dpkg-sig on $host returned \"$response\"");
			}
		} else {
			die _die("remote dpkg-sig on $host seems to be weird. Can't parse \"$response\"");
		}
	} else {
		my ($new_changes, $in_files) = ('', 0);
		open (CHANGES, "+<", $changes) || die _die("$changes: Can't open file: $!");
		while (<CHANGES>) {
			if (/^-----BEGIN PGP SIGNED MESSAGE-----$/) { while (<CHANGES>) { last if /^\s*$/ }; next }

			if ($in_files) {
				chomp;				
				last if ! s/^ //;
				my ($md5sum, $size, $section, $priority, $file_name) = split / /, $_;
				if ($new_deb_info->{$file_name}) {
					$md5sum = $new_deb_info->{$file_name}->[0];
					$size   = $new_deb_info->{$file_name}->[1];
					chomp($md5sum);
				}
				$new_changes .= " " . join (" ", ($md5sum, $size, $section, $priority, $file_name)). "\n";
			} else {
				$new_changes .= $_;
			}

			$in_files = "yes" if /^Files:/;
		}
		
		seek(CHANGES, 0, 0)   || die _die("$changes: Can't rewind file: $!");
		truncate(CHANGES, 0)  || die _die("$changes: Can't truncate file: $!");

		print CHANGES $new_changes;
		close CHANGES;
	}
}

=pod

=head2 I<\@new_file_info> = add_part_to_ar_archive (I<$file>, I<$new_data>, I<$new_name>)

=head2 I<\@new_file_info> = add_sig_to_deb (I<$file>, I<$new_data>, I<$new_name>)

Adds I<$new_data> to I<$file> as new ar archiv part, using $new_name as 
filename. If I<$file> doesn't exist, a new ar archive is created. Returns
the new md5sum and size of I<$file>.

=cut

sub add_part_to_ar_archive { return add_sig_to_deb(@_); }
sub add_sig_to_deb {
	my ($deb, $sig, $sig_name) = @_;
	my ($new_md5sum, $new_file_size);

	if ($deb =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($deb);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "add_sig_to_deb $sig_name $file\n";

		my ($response, $t);
		$response = '';
		do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
		chomp($response);

		if ($response =~ /^300 /) {
			for (split /\n/, $sig) {
				s/^\./../g;
				print $writerfh $_, "\n";
			}
			print $writerfh ".\n";
			
			$response = '';
			do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
			chomp($response);

			if ($response !~ /^200 /) {
				die _die("remote dpkg-sig on $host returned \"$response\"");
			} else {
				
				$response = '';
				do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
				chomp($response);
				($new_md5sum, $new_file_size) = split (/ /, $response);
			}
		} else {
			die _die("remote dpkg-sig on $host seems to be weird. Can't parse \"$response\"");
		}

	} else {
		die _die("$deb: Arch member name $sig_name too long!") if (length($sig_name) > 14);

		my $new_part = sprintf("%-16s%-12s%-6s%-6s%-8s%-10s`\n%s",
		   $sig_name, time, 0, 0, 100644, length($sig), $sig . (length($sig)%2 ? "\n":""));

		if (!stat($deb)) {
			open (DEB, ">", (glob $deb)[0]) || die _die("Couldn't open ".(glob $deb)[0].": $!");
			print DEB "!<arch>\n";
		} else {
			open (DEB, ">>", (glob $deb)[0]) || die _die("Couldn't open ".(glob $deb)[0].": $!");
		}

		print DEB $new_part || die _die("Couldn write to $deb: $!");
		close DEB;

		$new_md5sum = get_file_md5sum($deb);

		$new_file_size = (stat($deb))[7];
	}

	return [$new_md5sum, $new_file_size, basename($deb)];
}

=pod

=head2 I<@parts> = get_ar_parts (I<$file>)

=head2 I<@parts> = get_deb_parts (I<$file>)

Parses I<$file> as ar archive and returns all filenames included in the archive.

=cut

sub get_ar_parts { get_deb_part(@_) }
sub get_deb_parts {
	my ($deb) = shift;

	my @parts;

	if ($deb =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($deb);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "get_deb_parts $file\n";

		my $response = <$readerfh>;
		chomp($response);
		if ($response !~ /^200 /) {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		} else {
			while (<$readerfh>) {
				last if (/^\.$/);
				s/^\.\././;
				chomp;
				push @parts, [$_];
			}
		}
	} else {
        open(DEB, "<", (glob $deb)[0]) || die _die("Couldn't open $deb: $!");
		
		if (read(DEB, $_, 8) != 8) {
			die _die("Couldn't open $deb: ar format b0rken [Couldn't read first 8 bytes]");
		} elsif ($_ ne "!<arch>\n") {
			die _die("Couldn't open $deb: ar format b0rken");
		}

		do {
			my $line = <DEB>;
			if ($line =~ /\S/) { #This should help with additional newlines
				#debian-binary   1075243548  0     0     100644  4         `
				my $name   = substr($line, 0, 16);
				$name =~ s/\s*//g;
				$name =~ s/\/$//; # the 'ar' tool adds a / at the end, this is compatible with dpkg-deb
				my $length = substr($line, 48, 10);
				$length =~ s/\s*//g;
				next if (!$name && $length && $length =~ /^\d+\s*$/);
				
				seek (DEB, $length, 1) or die _die("Couldn't read $name in $deb: File too short!");
				if ($length % 2) {
					seek (DEB, 1, 1) or die _die("Couldn't read $name in $deb: File too short!");
				}

				push @parts, [$name];
			}
		} while (!eof(DEB));
		close DEB;
	}

	return @parts;
}

=pod

=head2 I<@debs> = get_debs_from_changes (I<$file>, I<\$changes_signed>)

Parses I<$file> as Debian .changes file and returns all listed debs. The dirname
of I<$file> is prepended to the debs, which means that the returned URIs should
exist.
If I<$file> is signed, I<$changes_signed> is set to "yes".

=cut

sub get_debs_from_changes {
	my ($changes, $changes_signed) = @_;
	my $changes_path = dirname($changes);
	my @debs;

	if ($changes =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($changes);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "get_debs_from_changes $file\n";
		my $response = <$readerfh>;
		chomp($response);
		if ($response !~ /^200 /) {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		} else {
			$$changes_signed = "yes" if $response =~ /^200 ok debs in signed/;	
			while (<$readerfh>) {
				last if (/^\.$/);
				s/^\.\././;
				chomp;
				if (defined ($user)) {
					push @debs, "ssh://$user\@$host:$_";
				} else {
					push @debs, "ssh://$host:$_";
				}
			}
		}
	} else {
		open (CHANGES, "<", $changes) || die _die("$changes: Can't open file: $!");
		while (<CHANGES>) { 
			$$changes_signed = "yes" if /-----BEGIN PGP SIGNED MESSAGE-----/;
			last if /^Files:/
		}

		while (<CHANGES>) {
			chomp;
			if (/^ [^ ]+ \d+ [^ ]+ [^ ]+ (.+)$/) {
				push @debs, $changes_path."/".$1 if $1 =~ /^(.+\.deb)$/;
			} elsif (/^\s*$/) {
				last;
			} else {
				print STDERR "$changes corrupted\n";
			}
		}
		close CHANGES;
	}

	return @debs;
}

=pod

=head2 I<\@digests> = get_deb_digests (I<$deb>)

Parses I<$deb> and returns the meta-data of the included files. The read
data is piped to md5sums and sha1sums, which create the respective 
digests. The digests, the filename and the size are put in an anymous
array looking like this: [B<$name>, B<$size>, B<$sha1sum>, B<$md5sum>].
One of these arrays is pushed to I<@digests> for every file in I<$deb>.

=cut

sub get_deb_digests {
	my $deb = shift;
	my @digests;
	
	if ($deb =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($deb);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "get_deb_digests $file\n";

		my $response = <$readerfh>;
		chomp($response);
		if ($response !~ /^200 /) {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		} else {
			while (<$readerfh>) {
				last if (/^\.$/);
				s/^\.\././;
				chomp;
				my ($name, $size, $sha1sum, $md5sum) = split / /, $_;
				push @digests, [$name, $size, $sha1sum, $md5sum];
			}
		}
	} else {
        open(DEB, "<", (glob $deb)[0]) || die _die("Couldn't open $deb: $!");
		
		if (read(DEB, $_, 8) != 8) {
			die _die("Couldn't open $deb: ar format b0rken [Couldn't read first 8 bytes]");
		} elsif ($_ ne "!<arch>\n") {
			die _die("Couldn't open $deb: ar format b0rken");
		}

		do {
			my $line = <DEB>;
			if ($line =~ /\S/) { #This should help with additional newlines
				my ($name, $size, $md5sum, $sha1sum);
				
				#debian-binary   1075243548  0     0     100644  4         `
				   $name   = substr($line, 0, 16);
				   $name =~ s/\s*//g;
				   $name =~ s/\/$//; # the 'ar' tool adds a / at the end, this is compatible with dpkg-deb
				my $length = substr($line, 48, 10);
				   $length =~ s/\s*//g;
				next if ($name eq "" && $length && $length =~ /^\d+\s*$/);
				$size = $length;
			
				my ($part, $read_length, $md5sum_input, $md5sum_output, $sha1sum_input, $sha1sum_output);
				open2($md5sum_output, $md5sum_input, qq{md5sum});
				if (-x "/usr/bin/sha1sum") {
					open2($sha1sum_output, $sha1sum_input, qq{sha1sum});
				} elsif (-x "/usr/bin/gpg") { #We need this for woody *sigh*:
					open2($sha1sum_output, $sha1sum_input, qq{gpg --print-md sha1 | tr 'A-Z' 'a-z' | sed 's/ //g'});
				} else {
					die _die("Can't compute sha1sum, please install sha1sum or gpg");
				}

				do {
					$read_length = ($length > 4096) ? 4096 : $length;
					$length -= $read_length;
					if (read (DEB, $part, $read_length) != $read_length) {
						die _die("Couldn't read $name in $deb: File too short!");
					}					
					if ($read_length % 2 && read (DEB, $_, 1) != 1) {
						die _die("Couldn't read $name in $deb: File too short!");			
					}
					print $md5sum_input $part;
					print $sha1sum_input $part;
				} while ($length > 0);

				close $md5sum_input; close $sha1sum_input;
				($md5sum = <$md5sum_output>) =~ s/[\s\n\r-]//g;
				($sha1sum = <$sha1sum_output>) =~ s/[\s\n\r-]//g;

				push @digests, [$name, $size, $sha1sum, $md5sum];
			}
		} while (!eof(DEB));

		close DEB;
	}

	return \@digests;
}

=pod

=head2 I<$md5sum> = get_file_md5sum (I<$file>)

Returns the md5sum for I<$file>.

=cut

sub get_file_md5sum {
	my $file = shift;
	my $md5sum;

	if ($file =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($file);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		if ($prot_version < 5) {
			die _die("remote dpkg-sig on $host is too old and can't return the needed md5sum of a file.");
		}

		print $writerfh "get_file_md5sum $file\n";

		my ($response, $t);
		$response = '';
		do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
		chomp($response);

		if ($response =~ /^200 ok md5sum is (\S+)/) {
			$md5sum = $1;
		} else {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		}
	} else {
		chomp ($md5sum = `md5sum $file | cut -d " " -f 1`);
	}

	return $md5sum;
}

=pod

=head2 I<$part_data> = get_archive_part (I<$archive>, I<$part_name>)

Returns the content of I<$part_name> in the ar archive I<$archive>.

=cut

sub get_archive_part {
	my ($deb, $part_name) = @_;
	my $part = '';

	if ($deb =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($deb);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "get_archive_part $part_name $file\n";
		my $response = <$readerfh>;
		if ($response !~ /^200 /) {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		} else {
			while (<$readerfh>) {
				last if (/^\.$/);
				s/^\.\././;
				chomp;
				$part .= "$_\n";
			}
		}
	} else {
		open(DEB, "<", $deb) || die _die("Couldn't open $deb: $!");
		
		if (read(DEB, $_, 8) != 8) {
			die _die("Couldn't open $deb: ar format b0rken [Couldn't read first 8 bytes]");
		} elsif ($_ ne "!<arch>\n") {
			die _die("Couldn't open $deb: ar format b0rken");
		}

		while (!eof(DEB)) {
			my $line = <DEB>;
			#debian-binary   1075243548  0     0     100644  4         `
			my $name   = substr($line, 0, 16);
			my $length = substr($line, 48, 10);
			next if (!$name && $length && $length =~ /^\d+\s*$/);
			
			my $tmp_part;
			if (read (DEB, $tmp_part, $length) != $length) {
				die _die("Couldn't read $name in $deb: File too short!");
			}
			if ($length % 2 && read (DEB, $_, 1) != 1) {
				die _die("Couldn't read $name in $deb: File too short!");			
			}

			$name =~ s/\s*//g;
			$name =~ s/\/$//; # the 'ar' tool adds a / at the end, this is compatible with dpkg-deb

			if ($name eq $part_name) {
				$part = $tmp_part;
				last;
			}
		}

		close DEB;
	}

	return $part;
}

=pod

=head2 I<@file_data> = read_control_file (I<$file>)

Returns the content of I<$file> as array with one line per element. 

=cut

sub read_control_file {
	my $file = shift;
	my @file_data;

	die _die("This only returns debian control files (ending with .changes or dsc)") if $file !~ /\.(?:dsc|changes)$/;

	if ($file =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($file);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		if ($prot_version < 3) {
			die _die("remote dpkg-sig on $host is too old and can't return the needed control file data.");
		}

		print $writerfh "read_control_file $file\n";

		my $response = <$readerfh>;
		chomp($response);
		if ($response !~ /^200 /) {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		} else {
			while (<$readerfh>) {
				last if (/^\.$/);
				s/^\.\././;
				push @file_data, $_;
			}
		}
	
	} else {
		open (FH, $file) or die _die("Can't open $file: $!");
		@file_data = <FH>;
		close FH;
	}

	return @file_data;
}

=pod

=head2 I<@file_info> = write_control_file (I<$file>, I<\@data>)

Writes contents of I<\@data> to I<$file>. Returns new md5sum and size
of I<$file>.

=cut

sub write_control_file {
	my ($file, $data) = @_;
	my ($response, $t, $new_md5sum, $new_file_size);

	die _die("This only writes debian control files (ending with .changes or dsc)") if $file !~ /\.(?:dsc|changes)$/;

	if ($file =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($file);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		if ($prot_version < 3) {
			die _die("remote dpkg-sig on $host is too old and can't return the needed control file data.");
		}

		print $writerfh "write_control_file $file\n";

		$response = '';
		do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
		chomp($response);
		
		if ($response =~ /^300 /) {
			print $writerfh @$data;
			print $writerfh ".\n";

			$response = '';
			do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
			chomp($response);

			if ($response =~ /^200 .+New md5sum, size: ([^ ]+) (\d+)/) {
				$new_md5sum = $1;
				$new_file_size = $2;
			} else {
				die _die("remote dpkg-sig on $host returned \"$response\"");
			}
		} else {
			die _die("remote dpkg-sig on $host seems to be weird. Can't parse \"$response\"");
		}	
	} else {
		_write_file($file, @$data);

		chomp ($new_md5sum = `md5sum $file | cut -d " " -f 1`);
		$new_file_size = (stat($file))[7];
	}

	return ($new_md5sum, $new_file_size);
}

=pod

=head2 I<@files> = glob_exp (I<$exp>)

Returns the result of globbing I<$exp> as array.

=cut

sub glob_exp {
	my $exp = shift;
	my @files;
	
	if ($exp =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($exp);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "glob_exp $file\n";
		my $response = <$readerfh>;
		if ($response !~ /^200 /) {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		} else {
			while (<$readerfh>) {
				last if (/^\.$/);
				s/^\.\././;
				chomp;
				if (defined ($user)) {
					push @files, "ssh://$user\@$host:$_";
				} else {
					push @files, "ssh://$host:$_";
				}
			}
		}
	} else {
		push @files, glob($exp);
	}

	return @files;
}

=pod

=head2 I<$file_readable> = file_readable (I<$file>)

Returns a true value if I<$file> is readable.

=cut

sub file_readable {
	my $file = shift;

	if ($file =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($file);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);


		if ($prot_version < 4) {
			print "W: remote dpkg-sig on $host is too old and can't return the needed data. .dsc not signed";
			return 0;
		}

		print $writerfh "file_readable $file\n";

		my ($response, $t);
		$response = '';
		do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
		chomp($response);

		if ($response =~ /^200 /) {
			return 1;
		} elsif ($response =~ /^400 /) {
			return 0;
		} else {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		}
	} else {
		return -r $file;
	}
}

=pod

=head2 I<@ssh_uri_parts> = split_ssh_uri (I<$uri>)

Splits an ssh URI $uri into a B<$user>, B<$host> and B<$path> part.

=cut

sub split_ssh_uri {
	my ($uri) = @_;

	my ($user, $host, $path);
	
	#ssh://$USER@$HOST:$PATH

	if ($uri =~ m!^ssh://(?:([^@\s]+)@)?(\S+):(.+)!) {
		($user, $host, $path) = ($1, $2, $3);
		$user ||= undef;
		
		die _die("$uri: Please specify at least a host to connect to.") if !$host;
		die _die("$uri: Please specify a path on the remote host.") if !$path;	
	} else {
		die _die("$uri is no ssh uri!");
	}

	return ($user, $host, $path);
}

=pod

=head2 I<@ssh_connection_info> = get_ssh_connection (I<$user>, I<$host>)

Opens a ssh connection to I<$host> as user I<$user>, directly calling 
B<dpkg-sig>. It checks if the remote B<dpkg-sig> is compatible to the
current version and returns the B<$pid>, the Read-Filehandle B<$readerfh>
and the Write-Filehandle B<$writerfh>.

=cut

sub get_ssh_connection {
	my ($user, $host) = @_;

	my $connection_id = (defined ($user))?"$user\@$host":$host;

	$remote_ssh_port ||= "";
	$remote_ssh_port =~ s/^\s*(\d+)\s*$/-p $&/;
	if (! $ssh_connections{$connection_id} ) {
		my ($readerfh, $writerfh);
		die _die("No ssh installed, we need it to connect to the remote host.") if (not `which ssh`);
		
		my $pid = open2($readerfh, $writerfh, qq{ssh $remote_ssh_port $connection_id '$remote_dpkg_sig --client $DEBUG 2>/dev/null || echo "No dpkg-sig available"' 2>&1});
		
		my $response = <$readerfh>;
		if ($response && $response !~ /protocol version/i) {
			if ($response && $response =~ /No dpkg-sig available/) {
				die _die("No $remote_dpkg_sig on remote host installed.");
			} else {
				if ($response) {
					die _die("ssh returned $response");
				} else {
					die _die("Some problem with the ssh connection $connection_id occured");
				}
			}
		}
		
		if ($response !~ /protocol version (\d+)$/i || $1 < 6) {
			die _die("dpkg-sig on $host is too old (we need protocol version 6)");
		}
		
		$ssh_connections{$connection_id} = [$pid, $readerfh, $writerfh, $1];
	}

	return (@{$ssh_connections{$connection_id}}[1,2,3]);
}

=pod

=head2 sign_control_files (I<$changes_file>)

This works like debsign:

=over 4

=item Checks if a .dsc exists.

=item If the .dsc should be signed, it tries to do so..

=item Writes the new .dsc with the new signature.

=item Reads I<$changes_file> and puts in the new size/md5sum of the .dsc.

=item Signs I<$changes_file> and write the signed copy back.

=cut

sub sign_control_files {
	my $file = shift;
	my $sign_dsc = $sign_changes =~ /full$/ ? 1 : 0;
	my ($dsc, $new_dsc_md5sum, $new_dsc_size);
	    $dsc = "$1.dsc" if ($file =~ /^(.+)_[^ _]+.changes/ && file_readable("$1.dsc"));

	#Clean the tempdir:
	unlink ($tempdir."/dsc.unsigned");
	unlink ($tempdir."/dsc.signed");
	unlink ($tempdir."/changes.unsigned");
	unlink ($tempdir."/changes.signed");

	if ($sign_dsc && $dsc) {
		open (DSC, ">", $tempdir."/dsc.unsigned") || die _die("Can't open $tempdir/dsc.unsigned: $!");
		my @data = read_control_file($dsc);
		for (my $i=0;$i<@data;$i++) {
			if ($data[$i] =~ /^-----BEGIN PGP SIGNED MESSAGE-----$/) {
				if ($sign_changes eq "force_full") { 
					$sign_dsc = 1;
				} elsif (! $batch) {
					print "The .dsc file is already signed.\nWould you like to use the current signature? [Yn] ";
					chomp(my $answer = lc(<STDIN>));
					$sign_dsc = 0 unless ($answer eq "n" || $answer eq "no");
				} else {
					$sign_dsc = 0;
				}
				while(defined $data[$i]) { last if $data[$i++] =~ /^\s*$/ }
			} elsif ($data[$i] =~ /^\s*$/) {
				last;
			}
			print DSC $data[$i];
		}
		print DSC "\n";
		close DSC;

		if ($sign_dsc) {
			#Sign it:
			sign_file($tempdir."/dsc.unsigned",$tempdir."/dsc.signed", "no_detach") if $sign_dsc;

			#Read and write them to the fitting location:
			open (DSC, $tempdir."/dsc.signed") || die _die("Can't open $tempdir/dsc.signed: $!");
			@data = <DSC>;
			close DSC;
			($new_dsc_md5sum, $new_dsc_size) = write_control_file($dsc, \@data);
			print "Signed .dsc $dsc\n" unless $batch;
		}
	}
	
	#Now the changes file:
	open (CHANGES, ">", $tempdir."/changes.unsigned") || die _die("Can't open $tempdir/changes.unsigned: $!");
	my $basename_dsc = basename($dsc) if $dsc;
	for (read_control_file($file), "\n") {
		#If we've changed the .dsc file, we have to use the new values in the .changes:
		if ($basename_dsc && $new_dsc_md5sum && $new_dsc_size && $_ =~ /\Q$basename_dsc\E$/) {
			 s/^ [^ ]+ \d+ (.+)$/ $new_dsc_md5sum $new_dsc_size $1/;
		}
		print CHANGES $_;
	}
	close CHANGES;

	sign_file($tempdir."/changes.unsigned",$tempdir."/changes.signed", "no_detach");
	
	my @data;
	open (CHANGES, $tempdir."/changes.signed") || die _die("Can't open $tempdir/changes.signed: $!");
	@data = <CHANGES>;
	close CHANGES;
	write_control_file($file, \@data);
	print "Signed .changes $file\n" unless $batch;	
}


=pod

=head2 sign_file (I<$in_file>, I<$out_file>, I<$no_detach>)

Signs I<$in_file> with gpg and puts the detached signature in I<$out_file>.

If I<$no_detach> is true, I<$out_file> is a clearsigned copy of I<$in_file>.

=cut

sub sign_file {
	my ($in_file, $out_file, $no_detach) = @_;

	my @cmdline = ("gpg", "--openpgp", "--armor", "--output", $out_file);
	if ($no_detach) {
		push @cmdline, "--clearsign";
	} else {
		push @cmdline, "--detach-sign";
	}

	if ($key) {
		push (@cmdline, "--default-key", "'$key'");
		print "Default key: $key\n" if $verbose;
	} elsif ($maintainer) {
		push (@cmdline, "--default-key", "'$maintainer'");
	}

	if ($pass_file) {
		push (@cmdline, "--no-tty", "--batch", "--passphrase-fd", "42", "42<$pass_file");
		print "Using passphrase from $pass_file\n" if $verbose;
	} elsif ($passphrase) {
		push (@cmdline, "--no-tty", "--batch", "--passphrase-fd", "0");
		print "Using cached passphrase\n" if $verbose;
	}

	push (@cmdline, $gpgoptions) if $gpgoptions;

	print "Signing $in_file with key ".($key || "of $maintainer")."\n" if $verbose;		
	push (@cmdline, $in_file, "2>&1");
	open (GPG, "| ".join " ", @cmdline) || die _die("Signing failed: $!");
	print GPG $passphrase, "\n" if $passphrase;
	close GPG;
	die _die("Signing failed. Error code: $?") if $?;
}

sub read_cmds {
	$DEBUG && (open (LOG, ">", "/tmp/dpkg-sig.log") || die _die("Couldn't open log: $!"));
	$DEBUG && select LOG; $|=1; 
	$DEBUG && select STDOUT;
	
	sub send { print STDOUT @_; $DEBUG && print LOG "Sent: ", @_; }
	sub read { $_ = <STDIN>; $DEBUG && print LOG "Received: ", $_; return $_ } ;

	while ($_ = &read()) {
		chomp;

		if (/^get_deb_digests (.+)$/) {
			my $r = eval { get_deb_digests ($1) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send ("500 error: $@\n");
			} else {
				&send("200 ok digests for $1 follow\n");
				&send(join (" ", @$_), "\n") for @$r;
				&send(".\n");
			}

		} elsif (/^get_deb_parts (.+)$/) {
			my @r = eval { get_deb_parts ($1) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send ("500 error: $@\n");
			} else {
				&send("200 ok parts of $1 follow\n");
				&send($_->[0] . "\n") for @r;
				&send(".\n");
			}

		} elsif (/^get_archive_part ([^ ]+) (.+)$/) {
			my $r = eval { get_archive_part ($2, $1) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: $@\n");
			} else {
				&send("200 ok part $1 of $2 follows\n");
				for (split (/\n/, $r)) {
					s/^\./../;
					&send("$_\n");
				}
				&send(".\n");
			}

		} elsif (/^read_control_file (.+)$/) {
			my @r = eval { read_control_file ($1) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: $@\n");
			} else {
				&send("200 ok file $1 follows\n");
				for (@r) {
					s/^\./../;
					&send("$_");
				}
				&send(".\n");
			}

		} elsif (/^get_debs_from_changes (.+)$/) {
			my $changes_signed = 0;
			my @r = eval { get_debs_from_changes ($1, \$changes_signed) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: $@\n");		
			} else {
				if ($changes_signed) {
					&send("200 ok debs in signed $1 follow\n");	
				} else {
					&send("200 ok debs in $1 follow\n");
				}
				for (@r) {
					s/^\./../;			
					&send("$_\n");
				}
				&send(".\n");
			}

		} elsif (/^glob_exp (.+)$/) {
			my @r = eval { glob_exp ($1) };		
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: $@\n");		
			} else {
				&send("200 ok files matching \"$1\" follow\n");	
				for (@r) {
					s/^\./../;			
					&send("$_\n");
				}
				&send(".\n");
			}

		} elsif (/^file_readable (.+)$/) {
			my $r = eval { file_readable ($1) };		
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: $@\n");		
			} else {
				if ($r) {
					&send("200 ok file readable\n");
				} else {
					&send("400 not ok file not readable\n");
				}
			}

		} elsif (/^get_file_md5sum (.+)$/) {
			my $r = eval { get_file_md5sum ($1) };		
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: $@\n");		
			} else {
				&send("200 ok md5sum is $r\n");
			}


		} elsif (/^add_sig_to_deb ([^ ]+) (.+)$/) {
			my ($sig_name, $deb, $sig) = ($1, $2, '');
			&send("300 ok waiting for data\n");
			while ($_ = &read()) {		
				last if (/^\.$/);
				s/^\.\././;
				$sig .= $_;
			}
			my $r = eval { add_sig_to_deb ($deb, $sig, $sig_name) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: ");
				&send($@, "\n");
			} else {
				&send("200 ok added sig to $deb. New data follows\n");
				&send(join (" ", @$r), "\n");
			}

		} elsif (/^correct_changes_file (.+)$/) {
			my ($changes, $new_changes_data) = ($1, {});
			&send("300 ok waiting for data\n");
			while ($_ = &read()) {	
				last if (/^\.$/);
				s/^\.\././;
				chomp;
				my ($md5sum, $size, $name) = split (/ /, $_, 3);
				$new_changes_data->{$name} = [$md5sum, $size, $name];
			}
			my $r = eval { correct_changes_file ($changes, $new_changes_data) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: ");
				&send($@, "\n");
			} else {
				&send("200 ok $changes corrected\n");
			}

		} elsif (/^write_control_file (.+)$/) {
			my ($file, @data) = ($1, ());
			
			&send("300 ok waiting for data\n");
			while ($_ = &read()) {	
				last if (/^\.$/);
				s/^\.\././;
				push @data, $_;
			}
			my @r = eval { write_control_file ($file, \@data) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: ");
				&send($@, "\n");
			} else {
				&send("200 ok $file written. New md5sum, size: $r[0] $r[1]\n");
			}

		} elsif (/^quit\s*$/) {
			&send("200 ok Bye!\n");
			exit;

		} else {
			&send("501 unknown command ".(split / /, $_)[0]."\n");
		}
	}
	$DEBUG && close LOG;
}

sub process_cli_options {
	exit 1 unless GetOptions("sign|s=s" => \$sign,
	                         "list|l|t" => \$list,
	                         "verify|check|c" => \$verify,
	                         "verify-role=s" => \$verify_role,
	                         "verify-exact=s" => \$verify_exact,
	                         "get-hashes=s" => \$get_hashes,
	                         "sign-hashes" => \$sign_hashes,
	                         "write-signature" => \$write_signature,
	                         "client" => \$client,
	                         "help"   => \$help,
	                         #Options:
	                         "default-key|k=s" => \$key,
	                         "cache-passphrase|p" => \$cache_pass,
	                         "passphrase-file|f=s" => \$pass_file,
	                         "m=s" => \$maintainer,
	                         "e=s" => \$maintainer_pr,
	                         "verbose|v+" => \$verbose,
	                         "also-v2-sig" => \$check_v2_sig,
	                         "also-v3-sig" => \$check_v2_sig,
	                         "sign-changes|a:s" => \$sign_changes,
	                         "batch:i" => \$batch,
	                         "gpg-options|g=s" => \$gpgoptions,
	                         "remote-dpkg-sig|r=s" => \$remote_dpkg_sig,
							 "remote-ssh-port|o=i" => \$remote_ssh_port,
	                        );
	$check_v2_sig = ($check_v2_sig && $check_v2_sig eq "false"?0:"yes");
	$check_v3_sig = ($check_v3_sig && $check_v3_sig eq "false"?0:"yes");
	
	die _die('Please use only one of --sign, --list, --verify[-role|-exact], --get-hashes, --write-signature, --help and --client!')
	  if (! !$sign + ! !$list + ! !$verify + ! !$verify_role + ! !$verify_exact + ! !$client + ! !$get_hashes + ! !$sign_hashes + ! !$write_signature + ! ! $help> 1);
	
	$maintainer_pr && ($maintainer = $maintainer_pr);
	if (!$sign && !$list && !$verify && !$verify_role && !$verify_exact &&
	  !$client && !$get_hashes && !$sign_hashes && !$write_signature && 
	  !$help) {
		if (@ARGV) {
			$verify = 1;
			print "I: No action requested, verifying files.\n";
		} else {
			$help = 1;
		}
	}
}

sub load_config {
	my @configfiles = @_;

	for my $configfile (@configfiles) {
		$configfile = (glob($configfile))[0];
		
		if ($configfile && -r $configfile) {
			%config = %{read_config_file($configfile) || {}};
		}
	}

	($maintainer = ($config{'DEBSIGN_MAINT'} || "")) =~ s/^"(.+)"$/$1/ if ! $maintainer;
	($key        = ($config{'DPKGSIG_KEYID'} || $config{'DEBSIGN_KEYID'} || "")) =~ s/^"(.+)"$/$1/ if ! $key;
	($cache_pass = ($config{'DPKGSIG_CACHE_PASS'} || "")) =~ s/^"(.+)"$/$1/ if ! $cache_pass;
	($sign_changes=($config{'DPKGSIG_SIGN_CHANGES'} ||""))=~ s/^"(.+)"$/$1/ if ! $sign_changes;

	if (! $sign_changes) {
		$sign_changes = "auto";
	} elsif (! grep {$sign_changes eq $_} qw(no auto yes full force_full)) {
		if ($sign_changes =~ /(?:deb|changes)$/) {
			push @files, $sign_changes;
			$sign_changes = "yes";		
		} else {
			print "W: Unrecognized argument to --sign-changes, using \"auto\": $sign_changes\n";
			$sign_changes = "auto";		
		}
	}

	if ($sign && $cache_pass && ! $pass_file) {
		eval { require Term::ReadKey; };
		if ($@) {
			print STDERR "Couldn't load Term::ReadKey. Please install. Passphrase caching disabled.\n";
		} else {
			my $passphrase_valid = 0;
			while (! $passphrase_valid) {
				print "The passphrase for ".($key || "your default key").": ";
				Term::ReadKey::ReadMode("noecho");
				chomp($passphrase = Term::ReadKey::ReadLine(0));
				Term::ReadKey::ReadMode("restore");
				print "\n";

				#Try to use the key:
				open (TMP, ">", $tempdir . '/tmp-file') or die "Can't open $tempdir/tmp-file: $!";
				print TMP "Foobar";
				close TMP;

				my $error;
				eval {
					my  @sign_cmd = ("gpg", "--clearsign");
					push @sign_cmd, ("--default-key", $key) if $key;
					push @sign_cmd, ("--no-tty", "--batch", "--passphrase-fd", "0");
					push @sign_cmd, $gpgoptions if $gpgoptions;
					push @sign_cmd, "$tempdir/tmp-file";
					my ($write_handle, $read_handle);
					open3 ($write_handle, $read_handle, undef, @sign_cmd) || die _die("Signing failed: $!");
					print $write_handle $passphrase, "\n";
					close $write_handle;
					$error = join "", <$read_handle>;
					close $read_handle;
				};

				if ($error && $error =~ /^gpg:.+bad passphrase\n/) {
					$passphrase_valid = 0;
					print STDERR "Wrong passphrase for " . (($key)?"key $key":"default key") . "!\n";
				} else {
					$passphrase_valid = 1;
				}
			}
		}
	}
}

sub help {
	print <<EOH;
Short usage:
 If not stated otherwise, all commands have one or more .deb or .changes
 files as argument. In the case of .changes files, dpkg-sig will work on
 all .deb files named in there. 

 -s,--sign <SIGNING_NAME>         Sign files 
 -c,--verify                      Verify signatures on files
 -l,--list                        List signatures on files
  
    --get-hashes                  Get hashes file for files
    --sign-hashes <HASHES_FILE>   Sign hashes file
    --write-hashes <HASHES_FILE>  Write sigs from signed hashes file

Options:
 -m,-e <MAINTAINER_NAME>          Specify maintainer name to use when signing
 -k <KEYID>                       Specify keyid to use when signing
 -v,--verbose                     Makes dpkg-sig more verbose
    --also-v2-sig                 Verify sigs from dpkg-sig 0.2 and earlier
    --also-v3-sig                 Verify sigs from dpkg-sig 0.3-0.10
 -a,--sign-changes <no|auto|yes|full|force_full>
       Tells whether also sign the changes and dsc-files. The default is auto.

 -g,--gpgoptions <GPG_OPTIONS>    DANGEROUS: Specify custom gpg options.
 -p,--cache-passphrase            INSECURE: Caches gpg passphrase in dpkg-sig
 -f,--passphrase-file <FILE>      INSECURE: Let gpg use passphrase from <FILE>
EOH
}

sub _die {
	chomp(my $msg = shift || "No error msg given! This is a bug, hurt the author!");
	my $i = 0;
	
	while ($_ = (caller($i++))[3]) {
		if ($_ && $_ eq "(eval)") {
			return $msg;
		}
	}
	
	my $code = shift || 1;
	my $line = (caller)[2];
	print STDERR "E: $msg\n";
	exit $code;
}

sub _read_file {
	my $file = shift;
	my $content;
	
	open (FH, $file) or die _die "Can't open $file: $!";
	$content = join "", <FH>;
	close FH;

	return $content;
}

sub _write_file {
	my $file = shift;
	my @content = @_;
	
	open (FH, ">", $file) or die _die "Can't open $file for writing: $!";
	print FH @content;
	close FH;
}

=pod

=head1 AUTHOR

B<dpkg-sig> and this manpage were written by Andreas Barth und Marc 
Brockschmidt. They are Copyright (C) 2003, 2004 by them and released 
under the GNU General Public Licence version 2 or later; there is NO
WARRANTY.  See F</usr/share/doc/dpkg-sig/copyright> and 
F</usr/share/common-licenses/GPL> for details.

=cut

# vim:set shiftwidth=4:
# vim:set tabstop=4:
# vim:set noet:
# vim:set shiftround:
