Don't check each and every key but save the user some time
[mirror/userdir-ldap.git] / ud-fingerserv
1 #!/usr/bin/perl
2 # $Id: ud-fingerserv,v 1.18 2004/11/18 16:49:15 joey Exp $
3
4 # (c) 1999 Randolph Chung. Licensed under the GPL. <tausq@debian.org>
5 # (c) 2004 Martin Schulze. Licensed under the GPL. <joey@debian.org>
6
7 use lib '/var/www/userdir-ldap/';
8 #use lib '/home/randolph/projects/userdir-ldap/web';
9 use strict vars;
10 use IO::Handle;
11 use IO::Socket;
12 use POSIX qw(:sys_wait_h);
13 use Getopt::Std;
14 use Util;
15 use Net::LDAP qw(:all);
16
17 # Global settings...
18 my %config = &Util::ReadConfigFile;
19 my %opts;
20 getopts("iqhv", \%opts);
21 my $use_inetd = $config{use_inetd} || $opts{i}; 
22 $| = 1;
23
24 my %attrs = (
25   'cn' => 'First name',
26   'mn' => 'Middle name',
27   'sn' => 'Last name',
28   'email' => 'Email',
29   'keyfingerprint' => 'Fingerprint',
30   'key' => 'Key block',
31   'ircnick' => 'IRC nickname',
32   'icquin' => 'ICQ UIN',
33   'labeleduri' => 'URL'
34 );
35
36 my @summarykeys = ('cn', 'mn', 'sn', 'email', 'labeleduri', 'ircnick', 'icquin', 'keyfingerprint', 'key');
37
38 $SIG{__DIE__} = \&DieHandler;
39 $SIG{INT} = \&DieHandler;
40 $SIG{CHLD} = \&Reaper;
41
42 &help if (defined($opts{h}));
43 #my $logfh = STDOUT; #TODO
44
45 &log("Binding to LDAP server at $config{ldaphost}") if (defined($opts{v}));
46 my $ldap = Net::LDAP->new($config{ldaphost}) || die $1; 
47 $ldap->bind;
48
49 if (!$use_inetd) {
50   &log("Binding to port 79") if (defined($opts{v}));
51   my $server = IO::Socket::INET->new(Proto => 'tcp', 
52                                      LocalPort => 'finger(79)',
53                                      Listen => SOMAXCONN,
54                                      Reuse => 1);
55
56   die "Cannot listen on finger port" unless $server;
57   &log("[Server listening for connections]");
58
59   my ($pid, $client, $hostinfo);
60
61   while ($client = $server->accept()) {
62     &log("Forking to handle client request") if (defined($opts{v}));
63     next if $pid = fork; # parent
64     die "fork: $!" unless defined $pid;
65   
66     # child
67     $client->autoflush(1);
68     my $hostinfo = gethostbyaddr($client->peeraddr, AF_INET);
69     &log(sprintf("[Connect from %s]", $hostinfo || $client->peerhost));
70     my $query = &readdata($client);
71     &ProcessQuery($client, $query) if (defined($query));
72     $client->close;
73     exit;
74   } continue {
75     $client->close;
76   }
77 } else { # inetd
78   &log("inetd mode");
79   my $sockaddr = getpeername(STDIN);
80   if ($sockaddr) {
81     my ($port, $addr) = unpack_sockaddr_in(getpeername(STDIN));
82     &log(sprintf("[Connect from %s (%s)]", gethostbyaddr($addr, AF_INET), inet_ntoa($addr)));
83   } else {
84     &log("[Connect via terminal]");
85   }
86   my $query = &readdata(\*STDIN);
87   &ProcessQuery(\*STDOUT, $query) if (defined($query));
88   exit;
89 }
90
91 $ldap->unbind;
92
93 sub DieHandler {
94   $ldap->unbind if (defined($ldap));
95   exit 0;
96 }
97
98 sub Reaper {
99   1 until (-1 == waitpid(-1, WNOHANG));
100   $SIG{CHLD} = \&Reaper;
101 }
102
103 sub ProcessQuery {
104   my $client = shift;
105   my $query = shift;
106   
107   my ($uid, $fields, $mesg, $entries, $dn, $key, $pid, $data);
108
109   $query =~ s/[^\/,0-9a-z]//gi; # be paranoid about input
110   my ($uid, $fields) = split(/\//, $query, 2);
111   
112   if (($uid eq "") || ($uid =~ /^help$/i)) {
113     &sendhelp($client);
114     return;
115   }
116   
117   &log("Looking up $uid at $config{basedn}, uid=$uid");
118
119   $mesg = $ldap->search(base  => $config{basedn}, filter => "uid=$uid");
120   $mesg->code && die $mesg->error;
121   $entries = $mesg->as_struct;
122
123   if ($mesg->count == 0) {
124     print $client "$uid not found at db.debian.org\n";
125     exit 0;
126   }
127
128   foreach $dn (sort {$entries->{$a}->{sn}->[0] <=> $entries->{$b}->{sn}->[0]} keys(%$entries)) {
129     $data = $entries->{$dn};
130
131     $data->{email}->[0] = sprintf("%s %s %s <%s>", $data->{cn}->[0],
132                                   $data->{mn}->[0], $data->{sn}->[0],
133                                   $data->{uid}->[0]."\@$config{emailappend}");
134                                   
135     $data->{email}->[0] =~ s/\s+/ /g;                             
136  
137     my @keyfingerprint = ();
138     for (my $i=0; $i <= $#{$data->{'keyfingerprint'}}; $i++) {
139       push (@keyfingerprint, $data->{keyfingerprint}->[$i]);
140       $data->{keyfingerprint}->[$i] = &Util::FormatFingerPrint($data->{keyfingerprint}->[$i]);
141       $data->{keyfingerprint}->[$i] =~ s,&nbsp;, ,;
142     }
143     print $client "$dn\n";
144     if (!$fields) {
145       push (@{$data->{key}}, sprintf ("finger %s/key\@db.debian.org", $uid));
146       foreach $key (@summarykeys) {
147         foreach (@{$data->{$key}}) {
148           print $client "$attrs{$key}: ";
149           print $client "$_\n";
150         }
151       }
152     } else {
153   #     print "$fields\n";
154       foreach $key (split(/,/, $fields)) {
155         if ($key eq 'key') {
156           foreach (@keyfingerprint) {
157             push (@{$data->{key}}, "\n".&Util::FetchKey($_), 0);
158           }
159         }
160         foreach (@{$data->{$key}}) {
161           print $client "$attrs{$key}: ";
162           print $client "$_\n";
163         }
164       }
165     }
166   }
167 }  
168
169 sub help {
170   print "fingerserv [-i | -q | -v | -h]\n";
171   print "-i = inetd mode; otherwise runs standalone\n";
172   print "-q = quiet mode; no output\n";
173   print "-v = verbose mode\n";
174   print "-h = this help message\n";
175   exit 0;
176 }
177
178 sub log {
179   my $msg = shift;
180   return if (defined($opts{q}));
181   
182   my $time = localtime;
183   print STDERR "$time $msg\n";
184 }
185
186 sub readdata {
187   my $fh = shift;
188   my $in = undef;
189   my $out = undef;
190   my $bytesread = 0;
191   my $ret;
192
193   my $flags= fcntl($fh, F_GETFL, 0)
194      or die "Can't get flags for socket: $!\n";
195   fcntl($fh, F_SETFL, $flags | O_NONBLOCK)
196      or die "Can't make socket nonblocking: $!\n";
197                                                 
198   while (($bytesread < 1024) && ($out !~ /\n/)) {
199     $ret = sysread($fh, $in, 1024);
200     return undef if (!defined($ret) || ($ret == 0));
201     $bytesread += $ret;
202     $out .= $in;
203   }
204
205   $out =~ /(.*?)\n/;
206   return $1;
207 }
208
209 sub sendhelp {
210   my $client = shift;
211   
212   print $client "userdir-ldap finger daemon\n";
213   print $client "--------------------------\n";
214   print $client "finger <uid>[/<attributes>]\@db.debian.org\n";
215   print $client "  where uid is the user id of the user\n";
216   print $client "  the optional attributes parameter specifies what to return\n";
217   print $client "    if nothing is specified, all attributes are returned.\n";
218   print $client "    The following attributes are currently supported:\n";
219   foreach (@summarykeys) {
220     print $client "      $_ : $attrs{$_}\n";
221   }
222   print $client "    Multiple attributes can be separated by commas, like this:\n";
223   print $client "    finger tux/email,key\@db.debian.org\n";
224 }