Merged from debian branch
[mirror/userdir-ldap.git] / ud-fingerserv
1 #!/usr/bin/perl
2 # $Id: ud-fingerserv,v 1.19 2004/11/18 19:10:57 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("fiqhvl:", \%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   'jabberjid' => 'Jabber ID',
34   'labeleduri' => 'URL'
35 );
36
37 my @summarykeys = ('cn', 'mn', 'sn', 'email', 'labeleduri', 'ircnick', 'icquin', 'jabberjid', 'keyfingerprint', 'key');
38
39 $SIG{__DIE__} = \&DieHandler;
40 $SIG{INT} = \&DieHandler;
41 $SIG{CHLD} = \&Reaper;
42
43 &help if (defined($opts{h}));
44
45 my $logfh;
46 unless ($opt{i} || $opt{f}) {
47   die "Need logfile unless running foreground\n" unless (defined($opt{l}));
48   open ($logfh, $opt{l}) or die "Can't open logfile: $!\n";
49 } else {
50   $logfh = \*STDOUT;
51 }
52
53 &log("Binding to LDAP server at $config{ldaphost}") if (defined($opts{v}));
54 my $ldap = Net::LDAP->new($config{ldaphost}) || die $1; 
55 $ldap->bind;
56
57 if (!$use_inetd) {
58
59   unless ($opts{f}) {
60     use POSIX 'setsid';
61     chdir '/' or die "Can't chdir to /: $!";
62     open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
63     open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!";
64     my $pid;
65     defined($pid = fork) or die "Can't fork: $!";
66     exit if $pid;
67     setsid or die "Can't start a new session: $!";
68     defined($pid = fork) or die "Can't fork: $!";
69     exit if $pid;
70     open STDERR, '>&STDOUT' or die "Can't dup stdout: $!";
71   }
72
73   &log("Binding to port 79") if (defined($opts{v}));
74   my $server = IO::Socket::INET->new(Proto => 'tcp', 
75                                      LocalPort => 'finger(79)',
76                                      Listen => SOMAXCONN,
77                                      Reuse => 1);
78
79   mydie "Cannot listen on finger port" unless $server;
80   &log("[Server listening for connections]");
81
82   my ($pid, $client, $hostinfo);
83
84   while ($client = $server->accept()) {
85     &log("Forking to handle client request") if (defined($opts{v}));
86     next if $pid = fork; # parent
87     mydie "fork: $!" unless defined $pid;
88   
89     # child
90     $client->autoflush(1);
91     my $hostinfo = gethostbyaddr($client->peeraddr, AF_INET);
92     &log(sprintf("[Connect from %s]", $hostinfo || $client->peerhost));
93     my $query = &readdata($client);
94     &ProcessQuery($client, $query) if (defined($query));
95     $client->close;
96     exit;
97   } continue {
98     $client->close;
99   }
100 } else { # inetd
101   &log("inetd mode");
102   my $sockaddr = getpeername(STDIN);
103   if ($sockaddr) {
104     my ($port, $addr) = unpack_sockaddr_in(getpeername(STDIN));
105     &log(sprintf("[Connect from %s (%s)]", gethostbyaddr($addr, AF_INET), inet_ntoa($addr)));
106   } else {
107     &log("[Connect via terminal]");
108   }
109   my $query = &readdata(\*STDIN);
110   &ProcessQuery(\*STDOUT, $query) if (defined($query));
111   exit;
112 }
113
114 $ldap->unbind;
115
116 sub DieHandler {
117   $ldap->unbind if (defined($ldap));
118   exit 0;
119 }
120
121 sub Reaper {
122   1 until (-1 == waitpid(-1, WNOHANG));
123   $SIG{CHLD} = \&Reaper;
124 }
125
126 sub ProcessQuery {
127   my $client = shift;
128   my $query = shift;
129   
130   my ($uid, $fields, $mesg, $entries, $dn, $key, $pid, $data);
131
132   $query =~ s/[^\/,0-9a-z]//gi; # be paranoid about input
133   my ($uid, $fields) = split(/\//, $query, 2);
134   
135   if (($uid eq "") || ($uid =~ /^help$/i)) {
136     &sendhelp($client);
137     return;
138   }
139   
140   &log("Looking up $uid at $config{basedn}, uid=$uid");
141
142   $mesg = $ldap->search(base  => $config{basedn}, filter => "uid=$uid");
143   $mesg->code && mydie $mesg->error;
144   $entries = $mesg->as_struct;
145
146   if ($mesg->count == 0) {
147     print $client "$uid not found at db.debian.org\n";
148     exit 0;
149   }
150
151   foreach $dn (sort {$entries->{$a}->{sn}->[0] <=> $entries->{$b}->{sn}->[0]} keys(%$entries)) {
152     $data = $entries->{$dn};
153
154     $data->{email}->[0] = sprintf("%s %s %s <%s>", $data->{cn}->[0],
155                                   $data->{mn}->[0], $data->{sn}->[0],
156                                   $data->{uid}->[0]."\@$config{emailappend}");
157                                   
158     $data->{email}->[0] =~ s/\s+/ /g;                             
159  
160     my @keyfingerprint = ();
161     for (my $i=0; $i <= $#{$data->{'keyfingerprint'}}; $i++) {
162       push (@keyfingerprint, $data->{keyfingerprint}->[$i]);
163       $data->{keyfingerprint}->[$i] = &Util::FormatFingerPrint($data->{keyfingerprint}->[$i]);
164       $data->{keyfingerprint}->[$i] =~ s,&nbsp;, ,;
165     }
166     print $client "$dn\n";
167     if (!$fields) {
168       push (@{$data->{key}}, sprintf ("finger %s/key\@db.debian.org", $uid));
169       foreach $key (@summarykeys) {
170         foreach (@{$data->{$key}}) {
171           print $client "$attrs{$key}: ";
172           print $client "$_\n";
173         }
174       }
175     } else {
176   #     print "$fields\n";
177       foreach $key (split(/,/, $fields)) {
178         if ($key eq 'key') {
179           foreach (@keyfingerprint) {
180             push (@{$data->{key}}, "\n".&Util::FetchKey($_), 0);
181           }
182         }
183         foreach (@{$data->{$key}}) {
184           print $client "$attrs{$key}: ";
185           print $client "$_\n";
186         }
187       }
188     }
189   }
190 }  
191
192 sub help {
193   print "fingerserv [-f | -l | -i | -q | -v | -h]\n";
194   print "-f = foreground; do not detach from tty\n";
195   print "-i = inetd mode; otherwise runs standalone\n";
196   print "-q = quiet mode; no output\n";
197   print "-v = verbose mode\n";
198   print "-h = this help message\n";
199   print "-l = log file.  Necessary if not using -f or -i\n";
200   exit 0;
201 }
202
203 sub log {
204   my $msg = shift;
205   return if (defined($opts{q}));
206   
207   my $time = localtime;
208   print $logfh "$time $msg\n";
209 }
210
211 sub mydie {
212   my $msg = shift;
213   log($msg);
214   exit 1;
215 }
216
217 sub readdata {
218   my $fh = shift;
219   my $in = undef;
220   my $out = undef;
221   my $bytesread = 0;
222   my $ret;
223
224   my $flags= fcntl($fh, F_GETFL, 0)
225      or mydie "Can't get flags for socket: $!\n";
226   fcntl($fh, F_SETFL, $flags | O_NONBLOCK)
227      or mydie "Can't make socket nonblocking: $!\n";
228                                                 
229   while (($bytesread < 1024) && ($out !~ /\n/)) {
230     $ret = sysread($fh, $in, 1024);
231     return undef if (!defined($ret) || ($ret == 0));
232     $bytesread += $ret;
233     $out .= $in;
234   }
235
236   $out =~ /(.*?)\n/;
237   return $1;
238 }
239
240 sub sendhelp {
241   my $client = shift;
242   
243   print $client "userdir-ldap finger daemon\n";
244   print $client "--------------------------\n";
245   print $client "finger <uid>[/<attributes>]\@db.debian.org\n";
246   print $client "  where uid is the user id of the user\n";
247   print $client "  the optional attributes parameter specifies what to return\n";
248   print $client "    if nothing is specified, all attributes are returned.\n";
249   print $client "    The following attributes are currently supported:\n";
250   foreach (@summarykeys) {
251     print $client "      $_ : $attrs{$_}\n";
252   }
253   print $client "    Multiple attributes can be separated by commas, like this:\n";
254   print $client "    finger tux/email,key\@db.debian.org\n";
255 }