Allow dashes in hostnames for sudo passwords (RT #5785)
[mirror/userdir-ldap-cgi.git] / search.cgi
1 #!/usr/bin/perl
2
3 # $Id: search.cgi,v 1.14 2006/12/22 08:58:50 rmurray Exp $
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 # (c) 2006 Ryan Murray. Licensed under the GPL. <rmurray@debian.org>
7 # Copyright (c) 2008, 2011, 2013, 2015 Peter Palfrader
8
9 use lib '.';
10 use strict vars;
11 #use Apache::Registry;
12 use CGI;
13 use Util;
14 use URI::Escape;
15 use Net::LDAP qw(LDAP_SUCCESS LDAP_PROTOCOL_ERROR);
16
17 # Global settings...
18 my %config = &Util::ReadConfigFile;
19
20 my $query = new CGI;
21 my $id = $query->param('id');
22 my $authtoken = $query->param('authtoken');
23 my $dosearch = uri_escape($query->param('dosearch'));
24 my $searchdn = uri_escape($query->param('searchdn'));
25
26 my $ldap = undef;
27 my $password = undef;
28
29 if ($authtoken || $id) {
30   $password = Util::TouchAuthToken($authtoken, $id);
31 } else {
32   $password = '';
33   $id = '';
34   $authtoken = '';
35 }
36
37 my $proto = ($ENV{HTTPS} ? "https" : "http");
38
39 sub DieHandler {
40   $ldap->unbind if (defined($ldap));
41 }
42
43 #$SIG{__DIE__} = \&DieHandler;
44
45 if (!$dosearch) {
46   # No action yet, send back the search form...
47   &Util::HTMLSendHeader;
48   open (F, "<$config{websearchhtml}") || &Util::HTMLError($!);
49   while (<F>) {
50     s/~id~/$id/g;
51     s/~authtoken~/$authtoken/g;    
52     print;
53   }
54   close F;
55 } else {
56   # Go ahead and construct the search terms
57   my %searchdata = (
58     cn             => { fuzzy => 'cnfuzzy', formname => 'cn' }, # First name
59     mn             => { fuzzy => 'mnfuzzy', formname => 'mn' }, # Middle name
60     sn             => { fuzzy => 'snfuzzy', formname => 'sn' }, # Last name
61     email          => { fuzzy => 'emailfuzzy', formname => 'email' }, # email
62     uid            => { fuzzy => 'uidfuzzy', formname => 'uid' }, # Login name
63     ircnick        => { fuzzy => 'ircfuzzy', formname => 'ircnick' }, # IRC nickname
64     keyfingerprint => { fuzzy => 'fpfuzzy', formname => 'fingerprint' }, # PGP/GPG fingerprint
65     c              => { formname => 'country'}, # Country
66   );
67
68   # Do a little preprocessing - strip the spaces out of the fingerprint
69   my $temp = $query->param('fingerprint');
70   $temp =~ s/ //g; $query->param('fingerprint', $temp);
71
72   # go through %searchdata and pull out all the search criteria the user
73   # specified...
74   my $filter = "(objectclass=inetOrgPerson)(!(accountStatus=*))";
75   foreach (keys(%searchdata)) {
76     if ($query->param($searchdata{$_}{formname})) {    
77       if ($query->param($searchdata{$_}{fuzzy})) {
78         # fuzzy search
79         $filter .= "($_~=".$query->param($searchdata{$_}{formname}).")";
80       } else {
81         $filter .= "($_=".$query->param($searchdata{$_}{formname}).")";
82       }
83     }
84   }
85   
86   # Vacation is a special case, support it only when user is authenticated
87   $filter .= "(onvacation=*)" if ($query->param('vacation') && $authtoken && $id);
88
89   # AND all the search terms together
90   $filter = "(&$filter)";
91   
92   # Read in the result template...
93   my ($lineref, $dataspecref) = ParseResult($config{websearchresulthtml});
94
95   # Now, we are ready to connect to the LDAP server.
96   $ldap = Net::LDAP->new($config{ldaphost}) || &Util::HTMLError($!);
97   &Util::UpgradeConnection($ldap) unless $config{usessl} eq 'False';
98   my $auth = 0;
99   my $mesg;
100
101   if ($id && $password) {
102     $mesg = $ldap->bind("uid=$id,$config{basedn}", password => $password);
103     $mesg->sync;
104     $auth = ($mesg->code == LDAP_SUCCESS);
105   }
106
107   if (!$auth) { # Not authenticated - either the above failed, or no password supplied
108     $ldap->bind;
109   }
110
111 #  &Util::HTMLPrint("Searching in $config{basedn} for $filter...\n");
112   
113   $mesg = $ldap->search(base   => ($searchdn ? $searchdn : $config{basedn}),
114                         filter => ($searchdn ? "(uid=*)" : $filter));
115   $mesg->code && &Util::HTMLError($mesg->error);
116
117   my %outsub; # this hash will contain all the substitution tokens in the output
118   $outsub{count} = $mesg->count; # Count number of requests, also ensures we're done with the search
119   $outsub{auth} = $authtoken;
120   $outsub{authtoken} = $authtoken; # alias
121   $outsub{id} = $id;
122   $outsub{searchresults} = undef;
123   
124   my $entries = $mesg->as_struct; # entries contain a hashref to all the search results
125   my ($dn, $attr, $data); 
126
127   # Format the output....
128   foreach $dn (sort {$entries->{$a}->{sn}->[0] <=> $entries->{$b}->{sn}->[0]} keys(%$entries)) {
129     my $ok = 0;
130     # These are local variables.. i have enough global vars as it is... <sigh>
131     my ($ufdn, $login, $name, $icquin, $jabberjid, $email, $fingerprint,
132         $address, $latlong, $vacation, $created, $modified, $lastseen, $gender) = undef;
133
134     # Last seen information (Echelon)
135     $lastseen = &Util::FormatLastSeen($entries->{$dn}->{"activity-pgp"}->[0],
136                                       $entries->{$dn}->{"activity-from"}->[0]);
137
138     $data = $entries->{$dn};
139     for my $key (keys %{$data}) {
140       @{$data->{$key}} = map { CGI::escapeHTML($_); } @{$data->{$key}};
141     }
142     
143     $ufdn = $dn; # Net::LDAP does not have a dn2ufn function, but this is close enough :)
144     
145     # Assemble name, attach web page link if present.
146     $name = $data->{cn}->[0]." ".$data->{mn}->[0]." ".$data->{sn}->[0];
147     if (my $url = $data->{labeleduri}->[0]) {
148       $name = "<a href=\"$url\">$name</a>";
149     }
150     
151     # Add links to all email addresses
152     foreach (@{$data->{emailforward}}) {
153       $email .= "<br>" if ($email);
154       $email .= "<a href=\"mailto:$_\">$_</a>";
155     }
156
157     # ICQ 
158     if ($data->{icquin}->[0]) {
159       $icquin = sprintf("<a href=\"http://wwp.icq.com/%s\">%s</a>", $data->{icquin}->[0], $data->{icquin}->[0]);
160     }
161     
162     # Format PGP/GPG key fingerprints
163     my $fi;
164     foreach (@{$data->{keyfingerprint}}) {
165       $fingerprint .= "<br>" if ($fingerprint);
166       $fingerprint .= sprintf("%d:- <a href=\"fetchkey.cgi?fingerprint=%s\">%s</a>", ++$fi, $_, &Util::FormatFingerPrint($_));
167     }
168     
169     # Assemble addresses
170     $address = $data->{postaladdress}->[0] || "- unlisted -";
171     $address =~ s/\$/<br>/g;
172     $address .= "<br>".$data->{l}->[0]."<br>".&Util::LookupCountry($data->{c}->[0])."<br>".$data->{postalcode}->[0];
173
174     # Assemble latitude/longitude
175     $latlong  = $data->{latitude}->[0] || "none";
176     $latlong .= " / ";
177     $latlong .= $data->{longitude}->[0] || "none";    
178
179     # Gender
180     if ($data->{gender}->[0]) {
181         if ($data->{gender}->[0] == 1) {
182             $gender = $dataspecref->{male};
183         } elsif ($data->{gender}->[0] == 2) {
184             $gender = $dataspecref->{female};
185         } else {
186             $gender = $dataspecref->{unspecified};
187         }
188     } else {
189         $gender = $dataspecref->{unspecified};
190     }
191
192     # Modified/created time. TODO: maybe add is the name of the creator/modifier
193     $modified = &Util::FormatTimestamp($data->{modifytimestamp}->[0]);
194     $created =  &Util::FormatTimestamp($data->{createtimestamp}->[0]);
195
196     # Link in the debian login id 
197     $login = $data->{uid}->[0];
198     $login = "$login";
199     
200     # See if the user has a vacation message, non-public
201     $vacation = $data->{onvacation}->[0] if ($authtoken && $id);
202
203     # OK, now generate output... (i.e. put the output into the buffer )
204     $outsub{searchresults} .= '<table class="debform" border=2 cellpadding=2 cellspacing=0 bgcolor="#DDDDDD" width="80%">';
205     $outsub{searchresults} .= '<tr><th bgcolor="#44CCCC" colspan=2><font size=+1>'."$name</font> ";
206     $outsub{searchresults} .= "($ufdn)</th></tr>\n";
207     
208     if ($vacation) {
209       $outsub{searchresults} .= "<tr><td colspan=2 align=center><b>$vacation</b></td></tr>\n";
210     }
211
212     $outsub{searchresults} .= FormatEntry($dataspecref->{uid}, $login);
213     $outsub{searchresults} .= FormatEntry($dataspecref->{gender}, $gender);
214     if ($data->{ircnick}->[0]) {
215       $outsub{searchresults} .= FormatEntry($dataspecref->{ircnick}, $data->{ircnick}->[0]);
216     }
217     if ($data->{jabberjid}->[0]) {
218       $outsub{searchresults} .= FormatEntry($dataspecref->{jabberjid}, $data->{jabberjid}->[0]);
219     }
220     if ($icquin) {
221       $outsub{searchresults} .= FormatEntry($dataspecref->{icquin}, $icquin);
222     }
223     $outsub{searchresults} .= FormatEntry($dataspecref->{loginshell}, $data->{loginshell}->[0]);
224     $outsub{searchresults} .= FormatEntry($dataspecref->{fingerprint}, $fingerprint);
225     if ($data->{maildisablemessage}->[0]) {
226       $outsub{searchresults} .= FormatEntry($dataspecref->{maildisablemessage}, $data->{maildisablemessage}->[0]);
227     }
228
229     if ($auth) {
230       # Some data should only be available to authorized users...
231       if ($id eq $data->{uid}->[0]) {
232         $outsub{searchresults} .= FormatEntry($dataspecref->{email}, $email);
233       }
234       $outsub{searchresults} .= FormatEntry($dataspecref->{birthdate}, $data->{birthdate}->[0]);
235       $outsub{searchresults} .= FormatEntry($dataspecref->{address}, $address);
236       $outsub{searchresults} .= FormatEntry($dataspecref->{latlong}, $latlong);
237       $outsub{searchresults} .= FormatEntry($dataspecref->{phone}, $data->{telephonenumber}->[0] || "- unlisted -");
238       $outsub{searchresults} .= FormatEntry($dataspecref->{fax}, $data->{fascimiletelephonenumber}->[0] || "- unlisted -");
239       $outsub{searchresults} .= FormatEntry($dataspecref->{VoIP}, $data->{voip}->[0] || "- unlisted -");
240       $outsub{searchresults} .= FormatEntry($dataspecref->{lastseen}, $lastseen);
241 #     $outsub{searchresults} .= FormatEntry($dataspecref->{created}, $created);
242 #     $outsub{searchresults} .= FormatEntry($dataspecref->{modified}, $modified);
243     }
244     
245     $outsub{searchresults} .= "</table>";
246     
247     # If this is ourselves, present a link to do mods
248     if ($auth && ($id eq $data->{uid}->[0])) { #TODO: extract this string into a url for translation...
249       $outsub{searchresults} .= "<a href=\"$proto://$ENV{SERVER_NAME}/$config{webupdateurl}?id=$id;authtoken=$authtoken\">Edit my settings</a>\n";
250     }
251     
252     $outsub{searchresults} .= "<br><br><br>\n";
253   }
254   
255   # Finally, we can write the output... yuck...
256   &Util::HTMLSendHeader;
257   foreach (@$lineref) {
258     if (/<\?ifauth(.+?)\?>/) {
259       $_ = ($auth ? $1 : "");
260     } elsif (/<\?ifnoauth(.+?)\?>/) {
261       $_ = ($auth ? "" : $1);
262     }
263     s/~(.+?)~/$outsub{$1}/g;
264     print;
265   }
266
267   $ldap->unbind;
268 }
269
270 sub ParseResult {
271   # Reads the output html file and find out how the output should be named
272   # -- this gives us a way to do translations more easily
273   # Returns the contents of the template (w/o the searchresult portion) and
274   # the output specification
275   my $fn = shift;
276   my $insec = 0;
277   my @lines;
278   my %hash;
279   
280   open (F, "<$fn") || &Util::HTMLError("$fn: $!");
281   while (<F>) {
282     if (!$insec) {
283       if (/<\?searchresults/i) {
284         $insec = 1;
285         push(@lines, "~searchresults~\n"); # Leave token so we know where to put the result
286       } else {
287         push(@lines, $_);
288       }
289     } else {
290       if (/searchresults\?>/i) {
291         $insec = 0;
292       } else {
293         if (!/^\s*#/) {
294           s/^ *\(//; 
295           s/\) *$//; # remove leading/trailing () and spaces
296           chomp;
297           my ($desc, $attr) = split(/, /, $_, 2);
298           $hash{$attr} = $desc;
299         }
300       }
301     }
302   }
303   close F;
304   return (\@lines, \%hash);
305 }
306
307 sub FormatEntry {
308   my ($key, $val) = @_;
309   
310   return "<tr><td align=right><b>$key:</b></td><td>&nbsp;$val</td></tr>\n";
311 }
312
313 exit 0;