source: trunk/cgi-bin/search.cgi@ 360

Last change on this file since 360 was 351, checked in by Kris Deugau, 18 years ago

/trunk

Backport bugfixes from r303, r307, r309, r318, r319, and r323
(search.cgi)

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 15.8 KB
RevLine 
[197]1#!/usr/bin/perl
2# ipdb/cgi-bin/search.cgi
3# Started splitting search functions (quick and otherwise) from
4# main IPDB interface 03/11/2005
5###
6# SVN revision info
7# $Date: 2006-10-06 16:23:39 +0000 (Fri, 06 Oct 2006) $
8# SVN revision $Rev: 351 $
9# Last update by $Author: kdeugau $
10###
[320]11# Copyright 2005,2006 Kris Deugau
[197]12
13use strict;
14use warnings;
15use CGI::Carp qw(fatalsToBrowser);
16use DBI;
17use CommonWeb qw(:ALL);
18use MyIPDB;
19use POSIX qw(ceil);
20use NetAddr::IP;
21
22# Don't need a username or syslog here. syslog left active for debugging.
23use Sys::Syslog;
24openlog "IPDBsearch","pid","local2";
25
26# Why not a global DB handle? (And a global statement handle, as well...)
27# Use the connectDB function, otherwise we end up confusing ourselves
28my $ip_dbh;
29my $sth;
30my $errstr;
31($ip_dbh,$errstr) = connectDB_My;
32if (!$ip_dbh) {
33 printAndExit("Failed to connect to database: $errstr\n");
34}
35checkDBSanity($ip_dbh);
36initIPDBGlobals($ip_dbh);
37
38# Global variables
[351]39my $RESULTS_PER_PAGE = 25;
[197]40my %webvar = parse_post();
41cleanInput(\%webvar);
42
43if (!defined($webvar{stype})) {
44 $webvar{stype} = "<NULL>"; #shuts up the warnings.
45}
46
47printHeader('Searching...');
48
49if ($webvar{stype} eq 'q') {
50 # Quick search.
51
52 if (!$webvar{input}) {
53 # No search term. Display everything.
54 viewBy('all', '');
55 } else {
56 # Search term entered. Display matches.
57 # We should really sanitize $webvar{input}, no?
58 my $searchfor;
59 # Chew up leading and trailing whitespace
60 $webvar{input} =~ s/^\s+//;
61 $webvar{input} =~ s/\s+$//;
[285]62 if ($webvar{input} =~ /^\d+$/) {
63 # All-digits, new custID
64 $searchfor = "cust";
65 } elsif ($webvar{input} =~ /^[\d\.]+(\/\d{1,3})?$/) {
[201]66 # IP addresses should only have numbers, digits, and maybe a slash+netmask
[197]67 $searchfor = "ipblock";
68 } else {
69 # Anything else.
70 $searchfor = "desc";
71 }
72 viewBy($searchfor, $webvar{input});
73 }
74
75} elsif ($webvar{stype} eq 'c') {
76 # Complex search.
77
[201]78 # Several major cases, and a whole raft of individual cases.
79 # -> Show all types means we do not need to limit records retrieved by type
80 # -> Show all cities means we do not need to limit records retrieved by city
81 # Individual cases are for the CIDR/IP, CustID, Description, Notes, and individual type
82 # requests.
83
[207]84 my $sqlconcat;
85 if ($webvar{which} eq 'all') {
86 # Must match *all* specified criteria. ## use INTERSECT or EXCEPT
87 $sqlconcat = "INTERSECT";
88 } elsif ($webvar{which} eq 'any') {
89 # Match on any specified criteria ## use UNION
90 $sqlconcat = "UNION";
91 } else {
92 # We can't get here. PTHBTT!
93 printAndExit "PTHBTT!! Your search has been rejected due to Microsoft excuse #4432: ".
94 "Not enough mana";
95 }
[197]96
[202]97# We actually construct a monster SQL statement for all criteria.
98# Iff something has been entered, it will be used as a filter.
[208]99# Iff something has NOT been entered, we still include it but in
100# such a way that it does not actually filter anything out.
[201]101
[207]102 # Columns actually returned. Slightly better than hardcoding it
103 # in each (sub)select
104 my $cols = "cidr,custid,type,city,description";
[201]105
[207]106 # First chunk of SQL. Filter on custid, description, and notes as necessary.
[351]107 my $sql = "(select $cols from searchme where".
108 " $webvar{custexclude} (custid ilike '%$webvar{custid}%'".
109 " OR $webvar{custexclude} oldcustid ilike '%$webvar{custid}%'))".
[201]110 " $sqlconcat (select $cols from searchme where $webvar{descexclude} description ilike '%$webvar{desc}%')".
111 " $sqlconcat (select $cols from searchme where $webvar{notesexclude} notes ilike '%$webvar{notes}%')";
112
[207]113 # If we're not supposed to search for all types, search for the selected types.
114 if ($webvar{alltypes} ne 'on') {
115 $sql .= " $sqlconcat (select $cols from searchme where $webvar{typeexclude} type in (";
116 foreach my $key (keys %webvar) {
117 $sql .= "'$1'," if $key =~ /type\[(..)\]/;
118 }
119 chop $sql;
120 $sql .= "))";
[201]121 }
122
[207]123 # If we're not supposed to search for all cities, search for the selected cities.
124 # This could be vastly improved with proper foreign keys in the database.
125 if ($webvar{allcities} ne 'on') {
126 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cityexclude} city in (";
127 $sth = $ip_dbh->prepare("select city from cities where id=?");
128 foreach my $key (keys %webvar) {
129 if ($key =~ /city\[(\d+)\]/) {
130 $sth->execute($1);
131 my $city;
132 $sth->bind_columns(\$city);
133 $sth->fetch;
134 $city =~ s/'/''/;
135 $sql .= "'$city',";
136 }
[201]137 }
[207]138 chop $sql;
139 $sql .= "))";
[201]140 }
141
[207]142 ## CIDR query options.
143 $webvar{cidr} =~ s/\s+//; # Hates the nasty spaceseseses we does.
[351]144 if ($webvar{cidr} eq '') { # We has a blank CIDR. Ignore it.
[285]145 } elsif ($webvar{cidr} =~ /\//) {
[207]146 # 209.91.179/26 should show all /26 subnets in 209.91.179
147 my ($net,$maskbits) = split /\//, $webvar{cidr};
148 if ($webvar{cidr} =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
149 # /0->/9 are silly to worry about right now. I don't think
150 # we'll be getting a class A anytime soon. <g>
151 $sql .= " $sqlconcat (select $cols from searchme where ".
[351]152 "$webvar{cidrexclude} cidr<<='$webvar{cidr}')";
[207]153 } else {
154 # Partial match; beginning of subnet and maskbits are provided
155 # Show any blocks with the leading octet(s) and that masklength
[351]156 # Need some more magic for bare /nn searches:
157 my $condition = ($net eq '' ?
158 "masklen(cidr)=$maskbits" : "text(cidr) like '$net%' and masklen(cidr)=$maskbits");
[207]159 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
[351]160 "($condition))";
[207]161 }
162 } elsif ($webvar{cidr} =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
163 # Specific IP address match. Will show either a single netblock,
164 # or a static pool plus an IP.
165 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
166 "cidr >>= '$webvar{cidr}')";
167 } elsif ($webvar{cidr} =~ /^\d{1,3}(\.(\d{1,3}(\.(\d{1,3}\.?)?)?)?)?$/) {
168 # Leading octets in CIDR
169 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
170 "text(cidr) like '$webvar{cidr}%')";
171 } else {
172 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
173 printAndExit("Invalid netblock query.");
174 } # done with CIDR query options.
[201]175
[207]176 # Find the offset for multipage results
177 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
[201]178
[207]179 # Find out how many rows the "core" query will return.
180 my $count = countRows($sql);
[201]181
[207]182 if ($count == 0) {
183 printError "No matches found. Try eliminating one of the criteria,".
184 " or making one or more criteria more general.";
185 } else {
186 # Add the limit/offset clauses
187 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
188 # And tell the user.
189 print "<div class=heading>Searching...............</div>\n";
190 queryResults($sql, $webvar{page}, $count);
191 }
[201]192
[207]193} else { # how script was called. General case is to show the search criteria page.
[201]194
[197]195 # Display search page. We have to do this here, because otherwise
196 # we can't retrieve data from the database for the types and cities. >:(
197 my $html;
198 open HTML,"<../compsearch.html";
199 $html = join('',<HTML>);
200 close HTML;
201
202# Generate table of types
203 my $typetable = "<table class=regular cellspacing=0>\n<tr>";
204 $sth = $ip_dbh->prepare("select type,dispname from alloctypes where listorder <500 ".
205 "order by listorder");
206 $sth->execute;
207 my $i=0;
208 while (my @data = $sth->fetchrow_array) {
209 $typetable .= "<td><input type=checkbox name=type[$data[0]]>$data[1]</td>";
210 $i++;
211 $typetable .= "</tr>\n<tr>"
212 if ($i % 4 == 0);
213 }
214 if ($i %4 == 0) {
215 $typetable =~ s/<tr>$//;
216 } else {
217 $typetable .= "</tr>\n";
218 }
219 $typetable .= "</table>\n";
220
221# Generate table of cities
222 my $citytable = "<table class=regular cellspacing=0>\n<tr>";
223 $sth = $ip_dbh->prepare("select id,city from cities order by city");
224 $sth->execute;
225 my $i=0;
226 while (my @data = $sth->fetchrow_array) {
227 $citytable .= "<td><input type=checkbox name=city[$data[0]]>$data[1]</td>";
228 $i++;
229 $citytable .= "</tr>\n<tr>"
230 if ($i % 5 == 0);
231 }
232 if ($i %5 == 0) {
233 $citytable =~ s/<tr>$//;
234 } else {
235 $citytable .= "</tr>\n";
236 }
237 $citytable .= "</table>\n";
238
239 $html =~ s/\$\$TYPELIST\$\$/$typetable/;
240 $html =~ s/\$\$CITYLIST\$\$/$citytable/;
241
242 print $html;
243}
244
245# Shut down and clean up.
246finish($ip_dbh);
247printFooter;
248# We shouldn't need to directly execute any code below here; it's all subroutines.
249exit 0;
250
[207]251
252# viewBy()
253# The quick search
254# Takes a category descriptor and a query string
255# Creates appropriate SQL to run the search and display the results
256# with queryResults()
[197]257sub viewBy($$) {
258 my ($category,$query) = @_;
259
260 # Local variables
261 my $sql;
262
263 # Calculate start point for LIMIT clause
264 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
265
266# Possible cases:
[207]267# 1) Partial IP/subnet. Treated as "octet-prefix".
268# 2a) CIDR subnet. Exact match.
269# 2b) CIDR netmask. YMMV but it should be octet-prefix-with-netmask
270# (ie, all matches with the octet prefix *AND* that netmask)
271# 3) Customer ID. "Match-any-segment"
272# 4) Description. "Match-any-segment"
[197]273# 5) Invalid data which might be interpretable as an IP or something, but
274# which probably shouldn't be for reasons of sanity.
275
276 if ($category eq 'all') {
277
278 print qq(<div class="heading">Showing all netblock and static-IP allocations</div><br>\n);
279 $sql = "select * from searchme";
[202]280 my $count = countRows($sql);
[197]281 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
282 queryResults($sql, $webvar{page}, $count);
283
284 } elsif ($category eq 'cust') {
285
286 print qq(<div class="heading">Searching for Customer IDs containing '$query'</div><br>\n);
287
288 # Query for a customer ID. Note that we can't restrict to "numeric-only"
289 # as we have non-numeric custIDs in the legacy data. :/
[320]290 $sql = "select * from searchme where custid ilike '%$query%' or oldcustid ilike '%$query%'";
[202]291 my $count = countRows($sql);
[197]292 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
293 queryResults($sql, $webvar{page}, $count);
294
295 } elsif ($category eq 'desc') {
296
297 print qq(<div class="heading">Searching for descriptions containing '$query'</div><br>\n);
298 # Query based on description (includes "name" from old DB).
[285]299 $sql = "select * from searchme where description ilike '%$query%'".
300 " or custid ilike '%$query%'";
[202]301 my $count = countRows($sql);
[197]302 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
303 queryResults($sql, $webvar{page}, $count);
304
305 } elsif ($category =~ /ipblock/) {
306
307 # Query is for a partial IP, a CIDR block in some form, or a flat IP.
308 print qq(<div class="heading">Searching for IP-based matches on '$query'</div><br>\n);
309
310 $query =~ s/\s+//g;
311 if ($query =~ /\//) {
312 # 209.91.179/26 should show all /26 subnets in 209.91.179
313 my ($net,$maskbits) = split /\//, $query;
314 if ($query =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
315 # /0->/9 are silly to worry about right now. I don't think
316 # we'll be getting a class A anytime soon. <g>
317 $sql = "select * from searchme where cidr='$query'";
318 queryResults($sql, $webvar{page}, 1);
319 } else {
[289]320 #print "Finding all blocks with netmask /$maskbits, leading octet(s) $net<br>\n";
[197]321 # Partial match; beginning of subnet and maskbits are provided
322 $sql = "select * from searchme where text(cidr) like '$net%' and ".
323 "text(cidr) like '%$maskbits'";
[202]324 my $count = countRows($sql);
[197]325 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
326 queryResults($sql, $webvar{page}, $count);
327 }
328 } elsif ($query =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
329 # Specific IP address match
[289]330 #print "4-octet pattern found; finding netblock containing IP $query<br>\n";
[197]331 my ($net,$ip) = ($query =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})/);
332 my $sfor = new NetAddr::IP $query;
333 $sth = $ip_dbh->prepare("select * from searchme where text(cidr) like '$net%'");
334 $sth->execute;
335 while (my @data = $sth->fetchrow_array()) {
336 my $cidr = new NetAddr::IP $data[0];
337 if ($cidr->contains($sfor)) {
338 queryResults("select * from searchme where cidr='$cidr'", $webvar{page}, 1);
339 }
340 }
[202]341 } elsif ($query =~ /^(\d{1,3}\.){1,3}\d{1,3}\.?$/) {
[289]342 #print "Finding matches with leading octet(s) $query<br>\n";
[197]343 $sql = "select * from searchme where text(cidr) like '$query%'";
[202]344 my $count = countRows($sql);
[197]345 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
346 queryResults($sql, $webvar{page}, $count);
347 } else {
348 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
349 printError("Invalid query.");
350 }
351 } else {
352 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
353 printError("Invalid searchfor.");
354 }
355} # viewBy
356
357
358# args are: a reference to an array with the row to be printed and the
359# class(stylesheet) to use for formatting.
360# if ommitting the class - call the sub as &printRow(\@array)
361sub printRow {
362 my ($rowRef,$class) = @_;
363
364 if (!$class) {
365 print "<tr>\n";
366 } else {
367 print "<tr class=\"$class\">\n";
368 }
369
370ELEMENT: foreach my $element (@$rowRef) {
371 if (!defined($element)) {
372 print "<td></td>\n";
373 next ELEMENT;
374 }
375 $element =~ s|\n|</br>|g;
376 print "<td>$element</td>\n";
377 }
378 print "</tr>";
379} # printRow
380
381
[207]382# queryResults()
383# Display search queries based on the passed SQL.
384# Takes SQL, page number (for multipage search results), and a total count.
[197]385sub queryResults($$$) {
386 my ($sql, $pageNo, $rowCount) = @_;
387 my $offset = 0;
388 $offset = $1 if($sql =~ m/.*limit\s+(.*),.*/);
389
390 my $sth = $ip_dbh->prepare($sql);
391 $sth->execute();
392
393 startTable('Allocation','CustID','Type','City','Description/Name');
394 my $count = 0;
395
396 while (my @data = $sth->fetchrow_array) {
[202]397
[197]398 # cidr,custid,type,city,description,notes
[202]399 # Another bit of HairyPerl(TM) to prefix subblocks with "Sub"
400 my @row = (($data[2] =~ /^.r$/ ? 'Sub ' : '').
401 qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
[197]402 $data[1], $disp_alloctypes{$data[2]}, $data[3], $data[4]);
403 # Allow listing of pool if desired/required.
404 if ($data[2] =~ /^.[pd]$/) {
405 $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
406 "&pool=$data[0]\">List IPs</a>";
407 }
408 printRow(\@row, 'color1', 1) if ($count%2==0);
409 printRow(\@row, 'color2', 1) if ($count%2!=0);
410 $count++;
411 }
412
413 # Have to think on this call, it's primarily to clean up unfetched rows from a select.
414 # In this context it's probably a good idea.
415 $sth->finish();
416
417 my $upper = $offset+$count;
[202]418 print "<tr><td colspan=10 bgcolor=white class=regular>Records found: $rowCount<br><i>Displaying: ".($offset+1)." - $upper</i></td></tr>\n";
[197]419 print "</table></center>\n";
420
421 # print the page thing..
422 if ($rowCount > $RESULTS_PER_PAGE) {
423 my $pages = ceil($rowCount/$RESULTS_PER_PAGE);
424 print qq(<div class="center"> Page: );
425 for (my $i = 1; $i <= $pages; $i++) {
426 if ($i == $pageNo) {
427 print "<b>$i&nbsp;</b>\n";
428 } else {
[202]429 print qq(<a href="/ip/cgi-bin/search.cgi?page=$i&stype=$webvar{stype}&);
430 if ($webvar{stype} eq 'c') {
431 print "cidr=$webvar{cidr}&custid=$webvar{custid}&desc=$webvar{desc}&".
432 "notes=$webvar{notes}&which=$webvar{which}&alltypes=$webvar{alltypes}&".
433 "allcities=$webvar{allcities}&";
434 foreach my $key (keys %webvar) {
[351]435 if ($key =~ /^(?:type|city)\[/ || $key =~ /exclude$/) {
[202]436 print "$key=$webvar{$key}&";
437 }
438 }
439 } else {
440 print "input=$webvar{input}&";
441 }
442 print qq(">$i</a>&nbsp;\n);
[197]443 }
444 }
445 print "</div>";
446 }
447} # queryResults
448
449
450# Prints table headings. Accepts any number of arguments;
451# each argument is a table heading.
452sub startTable {
453 print qq(<center><table width="98%" cellspacing="0" class="center"><tr>);
454
455 foreach(@_) {
456 print qq(<td class="heading">$_</td>);
457 }
458 print "</tr>\n";
459} # startTable
460
461
[202]462# Return count of rows to be returned in a "real" query
463# with the passed SQL statement
[197]464sub countRows($) {
[202]465 # Note that the "as foo" is required
466 my $sth = $ip_dbh->prepare("select count(*) from ($_[0]) as foo");
[197]467 $sth->execute();
468 my @a = $sth->fetchrow_array();
469 $sth->finish();
470 return $a[0];
471}
Note: See TracBrowser for help on using the repository browser.