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