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