Extend copyright statement
[pgp-tools.git] / keylookup / keylookup
1 #!/usr/bin/perl -w
2
3 # Copyright (c) 2000, 2002 Christian Kurz <shorty@debian.org>,
4 # Copyright (c) 2000, 2002, 2005 Peter Palfrader <peter@palfrader.org>
5 #
6 # $Id$
7 #
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2, or (at your option)
11 # any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software Foundation,
20 # Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 #
22 # Keylookup homepage: http://www.palfrader.org/keylookup/
23 # CVS, BTS: http://savannah.gnu.org/projects/keylookup/
24
25 delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV', 'PATH'};
26 $|=1; # Always flush buffers
27
28
29 use strict;
30 use IO::Socket;
31 use IPC::Open3;
32 use Getopt::Long;
33
34 my $version = '3.0 ($Id$)';
35
36 # Where to find GnuPG's options file.
37 # Full path to the dialog and whiptail executeable.
38 my $Dialog = '/usr/bin/dialog';
39 my $Whiptail = '/usr/bin/whiptail';
40
41 # Strings to use in the dialog|whiptail frontend
42 my $TITLE = 'Import Keys';
43 my $BACKTITLE = 'KeyLookup $Revision$';
44 my $INSTRUCTION = 'Select keys to import:';
45 #
46 my @TPUTCOL=('tput', 'cols');
47 my @TPUTROW=('tput', 'lines');
48 my $DEFAULTCOLS = 80;
49 my $DEFAULTROWS = 25;
50 # Size of the dialog boxes, will be set in calcDialogSize;
51 my $MAX_UID_FIELD_LEN;
52 my @DIALOGSIZE;
53 my @WHIPTAILSIZE;
54
55
56 # Was the keyserver overriden|given on the command line?
57 # This is used to find out wheter we need to instruct the user
58 # to give the keyserver option to GnuPG.
59 my $keyserverWasSetOnCmdLine = 0;
60
61
62 # Maps algorithm numbers to algorithm types as defined in RFC 2400.
63 my %ALGOS = (
64 1 => 'R', # RSA
65 2 => 'r', # RSA encrypt only (deprecated)
66 3 => 's', # RSA sign only (deprecated)
67 16 => 'g', # ElGamal encrypt only
68 20 => 'g', # ElGamal sign and encrypt (all OpenPGP implementations cryptographically broken, do not use. no longer part of OpenPGP)
69 17 => 'D' # DSA
70 );
71
72
73 # getHits receives all options as a parameter, calls fetchIT to
74 # query a keyserver, processes the output from the keyserver and
75 # stores it in a datastructure for later use.
76 sub getHits($) {
77 my $options = shift;
78
79 my $pid = open(KID, '-|');
80 defined ($pid) or die ("Cannot fork: $!\n");
81 unless ($pid) {
82 close (STDIN);
83 open (STDIN, "/dev/null") || die ("Cannot open /dev/null as stdin: $!\n");
84
85 # child
86 my @ops = ('gpg');
87 if ($options->{'keyserver'}) {
88 push @ops, '--keyserver='.$options->{'keyserver'};
89 };
90 push @ops, '--command-fd=0';
91 push @ops, '--batch';
92 push @ops, '--no-tty';
93 push @ops, '--with-colons';
94 push @ops, '--fixed-list-mode';
95 push @ops, '--search';
96 push @ops, $options->{'search'};
97 exec(@ops);
98 die ("Cannot exec GnuPG: $!\n");
99 };
100 my %keys;
101 my $currentKey;
102
103 while (<KID>) {
104 chomp;
105 my ($type, undef) = split /:/;
106 if ($type eq 'pub') {
107 my ($type, $keyid, $algo, $bits, $created, undef, $revoked) = split /:/;
108 $currentKey = { 'bits' => $bits,
109 'type' => (defined $ALGOS{$algo} ? $ALGOS{$algo} : '#'.$algo),
110 'keyid' => $keyid,
111 'created' => $created,
112 'revoked' => $revoked,
113 'uid' => []
114 };
115 $keys{ $keyid } = $currentKey;
116 } elsif (defined $currentKey && $type eq 'uid') {
117 my ($type, $name) = split /:/;
118 if ($currentKey->{'revoked'} eq 'r') {
119 $name .= ' [REVOKED]';
120 };
121 push @{ $currentKey->{'uid'} }, $name;
122 };
123 };
124 close KID;
125 waitpid $pid, 0;
126
127 return \%keys;
128 };
129
130 # returns the number of columns of the terminal
131 sub getCols {
132 my $pid;
133 return $DEFAULTCOLS unless (defined ($pid = open(KID, "-|")));
134 unless ($pid) {
135 exec (@TPUTCOL);
136 };
137 my $cols = <KID>;
138 close KID;
139 wait;
140 return (defined $cols) ? $cols : $DEFAULTCOLS;
141 };
142
143 # returns the number of lines of the terminal
144 sub getRows {
145 my $pid;
146 return $DEFAULTROWS unless (defined ($pid = open(KID, "-|")));
147 unless ($pid) {
148 exec (@TPUTROW);
149 };
150 my $rows = <KID>;
151 close KID;
152 wait;
153 return (defined $rows) ? $rows : $DEFAULTROWS;
154 };
155
156 # sets MAX_UID_FIELD_LEN, DIALOGSIZE, and WHIPTAILSIZE
157 sub calcDialogSize {
158 my $COLS = &getCols();
159 my $ROWS = &getRows();
160 $MAX_UID_FIELD_LEN = $COLS - 27;
161 @DIALOGSIZE = ($ROWS-7, $COLS-7, $ROWS-14);
162 @WHIPTAILSIZE = ($ROWS-7, $COLS-7, $ROWS-14);
163 }
164
165 sub prepareForDialog {
166 my $keys = shift;
167 my @keyargs = ();
168
169 for my $keyid (sort {- ($keys->{$a}->{'created'} <=> $keys->{$b}->{'created'})} keys %$keys) {
170 for (@{ $keys->{$keyid}->{'uid'} }) {
171 push @keyargs,
172 $keys->{$keyid}->{'keyid'},
173 length() <= $MAX_UID_FIELD_LEN ? $_ : substr($_, 0, $MAX_UID_FIELD_LEN-2) . '..',
174 'off';
175 };
176 my (undef,undef,undef,$mday,$mon,$year,undef,undef,undef) = localtime ($keys->{$keyid}->{'created'});
177 push @keyargs, $keys->{$keyid}->{'keyid'}, sprintf( "[created: %s-%s-%s]", $year+1900, $mon+1, $mday ), 'off';
178 push @keyargs, '-'x8, '-'x40, 'off';
179 };
180 pop @keyargs;
181 pop @keyargs;
182 pop @keyargs;
183
184 return \@keyargs;
185 };
186
187 sub prepareForTXT {
188 my $keys = shift;
189 my @lines = ();
190
191 for my $keyid (sort {- ($keys->{$a}->{'created'} <=> $keys->{$b}->{'created'})} keys %$keys) {
192 my (undef,undef,undef,$mday,$mon,$year,undef,undef,undef) = localtime ($keys->{$keyid}->{'created'});
193 push @lines, sprintf( "%s%s/%s %s-%s-%s\n",
194 $keys->{$keyid}->{'bits'},
195 $keys->{$keyid}->{'type'},
196 $keys->{$keyid}->{'keyid'},
197 $year+1900, $mon+1, $mday );
198 push @lines, map { ' 'x26 . $_ . "\n" } @{ $keys->{$keyid}->{'uid'} };
199 push @lines, "\n";
200 };
201
202 return \@lines;
203 };
204
205 sub callDialog {
206 my $args = shift;
207
208 # open(SAVEOUT, ">&STDOUT") || die ("Cannot save STDOUT: $!\n");
209 # open(SAVEIN , "<&STDIN" ) || die ("Cannot save STDIN: $!\n");
210
211 my $pid = open3( '<&STDIN', '>&STDOUT', \*ERRFH, @$args);
212
213 my %unique;
214 my @keys = grep { !$unique{$_}++ }
215 grep { /^[0-9A-Fa-f]{8}$/ }
216 map { s/\s//g; $_ } <ERRFH>;
217 wait;
218
219 # open(STDOUT, ">&SAVEOUT") || die "Cannot restore STDOUT: $!\n";
220 # open(STDIN , "<&SAVEIN") || die "Cannot restore STDIN: $!\n";
221
222 return \@keys;
223 };
224
225 sub selectKeys {
226 my $keys = shift;
227 my $options = shift;
228
229 my $frontend = $options->{'frontend'};
230 $frontend = 'dialog' unless (defined $frontend);
231
232 if ($frontend eq 'dialog') {
233 unless (-x $Dialog) {
234 warn("Dialog ($Dialog) not executeable/installed. Falling back to Whiptail\n");
235 $frontend = 'whiptail';
236 }
237 };
238 if ($frontend eq 'whiptail') {
239 unless (-x $Whiptail ) {
240 warn("Whiptail ($Whiptail) not executeable/installed. Falling back to plain\n");
241 $frontend = 'plain';
242 }
243 };
244
245 if ( $frontend eq 'dialog' ) {
246 calcDialogSize;
247 my @ARGS = (
248 $Dialog,
249 '--backtitle',
250 $BACKTITLE,
251 '--separate-output',
252 '--title',
253 $TITLE,
254 '--checklist',
255 $INSTRUCTION,
256 @DIALOGSIZE);
257 push @ARGS, @{&prepareForDialog($keys)};
258 return &callDialog( \@ARGS );
259 } elsif ( $frontend eq 'whiptail' ) {
260 calcDialogSize;
261 my @ARGS = (
262 $Whiptail,
263 '--backtitle',
264 $BACKTITLE,
265 '--separate-output',
266 '--title',
267 $TITLE,
268 '--checklist',
269 $INSTRUCTION,
270 @WHIPTAILSIZE,
271 '--');
272 push @ARGS, @{&prepareForDialog($keys)};
273 return &callDialog( \@ARGS );
274 } else {
275 print for (@{ &prepareForTXT( $keys ) });
276 if ($keyserverWasSetOnCmdLine) {
277 printf ("Now run gpg --keyserver %s --recv-keys <key ids>\n", $options->{'keyserver'});
278 } else {
279 print ("Now run gpg --recv-keys <key ids>\n");
280 };
281
282 ## If no frontend was selected, or selected frontend was plain,
283 ## exit successfully, otherwise with an exitcode != 0
284 exit (defined $options->{'frontend'} &&
285 $options->{'frontend'} ne "" &&
286 $options->{'frontend'} ne "plain");
287 };
288 };
289
290 sub importKeys {
291 my $keyids = shift;
292 my $options = shift;
293
294 my @args = ('gpg');
295 if ($options->{'keyserver'}) {
296 push @args, '--keyserver='.$options->{'keyserver'};
297 };
298 push @args, '--recv-keys';
299 for my $keyid (@$keyids) {
300 # untaint keyids
301 my ($cleanid) = $keyid =~ /^([a-zA-Z0-9]{8})$/;
302 warn ("keyid '$keyid' has unexpected format - skipping\n"), next
303 unless defined $cleanid;
304 push @args, $cleanid;
305 }
306
307 print "Calling GnuPG...\n";
308 exec (@args) || die "can't exec gnupg: $!\n"; # won't return
309 };
310
311
312 sub usage {
313 my $errorcode = shift;
314 print << 'EOF'
315 Syntax: keylookup [options] <searchstring>
316
317 Options:
318 --keyserver=<keyserver> Select keyserver
319 --frontend=<frontend> One of whiptail, dialog or plain
320 --importall Import all matched keys
321 --help print this message
322
323 EOF
324 ;
325 exit($errorcode);
326 };
327
328 sub version {
329 print "keylookup $version\nWritten by Christian Kurz and Peter Palfrader.\n";
330 exit(0);
331 };
332
333 my %options;
334 GetOptions( \%options,
335 'keyserver=s',
336 'frontend=s',
337 'importall',
338 'version',
339 'help') or
340 &usage(1);
341 &version(0) if ($options{'version'});
342 &usage(0) if ($options{'help'} || ( scalar(@ARGV) == 0));
343
344 ## Take all additional arguments to the program as a search target,
345 ## escape the string for use in URLs.
346 $options{'search'} = join ' ', @ARGV;
347 $options{'search'} =~ s/ ( [^A-Za-z0-9] )
348 / '%' . unpack("H2", $1)
349 /xeg;
350 my $keys = getHits( \%options );
351 my $keyids;
352
353 if ($options{'importall'}) {
354 my @allkeys = keys %$keys;
355 $keyids = \@allkeys;
356 } else {
357 $keyids = selectKeys($keys, \%options); # won't return if no interactive frontend
358 };
359 &importKeys($keyids, \%options) if (scalar @$keyids); # won't return
360