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