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

Last change on this file since 521 was 521, checked in by Kris Deugau, 12 years ago

/trunk

Patch up search.cgi so that it at least provides results and doesn't
spew errors all over the place. See #31, #4 (sort of).

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 17.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: 2012-10-19 20:38:06 +0000 (Fri, 19 Oct 2012) $
8# SVN revision $Rev: 521 $
9# Last update by $Author: kdeugau $
10###
[417]11# Copyright 2005-2010 - Kris Deugau
[197]12
13use strict;
14use warnings;
15use CGI::Carp qw(fatalsToBrowser);
[517]16use CGI::Simple;
17use HTML::Template;
[197]18use DBI;
19use POSIX qw(ceil);
20use NetAddr::IP;
21
[417]22# don't remove! required for GNU/FHS-ish install from tarball
23##uselib##
[197]24
[417]25use MyIPDB;
26
[439]27# Don't formally need a username or syslog here. syslog left active for debugging.
28use Sys::Syslog;
29openlog "IPDBsearch","pid","$IPDB::syslog_facility";
30
31# ... but we do *use* the username on ACLs now.
32# Collect the username from HTTP auth. If undefined, we're in
33# a test environment, or called without a username.
34my $authuser;
35if (!defined($ENV{'REMOTE_USER'})) {
36 $authuser = '__temptest';
37} else {
38 $authuser = $ENV{'REMOTE_USER'};
39}
40
[517]41# Global variables
42my $RESULTS_PER_PAGE = 25;
43
44# anyone got a better name? :P
45my $thingroot = $ENV{SCRIPT_FILENAME};
46$thingroot =~ s|cgi-bin/search.cgi||;
47
48# Set up the CGI object...
49my $q = new CGI::Simple;
50# ... and get query-string params as well as POST params if necessary
51$q->parse_query_string;
52
53# Convenience; saves changing all references to %webvar
54##fixme: tweak for handling <select multiple='y' size=3> (list with multiple selection)
55my %webvar = $q->Vars;
56
57if (defined($webvar{rpp})) {
58 ($RESULTS_PER_PAGE) = ($webvar{rpp} =~ /(\d+)/);
59}
60
[197]61# Why not a global DB handle? (And a global statement handle, as well...)
62# Use the connectDB function, otherwise we end up confusing ourselves
63my $ip_dbh;
64my $sth;
65my $errstr;
66($ip_dbh,$errstr) = connectDB_My;
[517]67if ($ip_dbh) {
68 checkDBSanity($ip_dbh);
69 initIPDBGlobals($ip_dbh);
[197]70}
71
[517]72# Set up some globals
73$ENV{HTML_TEMPLATE_ROOT} = $thingroot."templates";
[197]74
[517]75my $page;
[197]76if (!defined($webvar{stype})) {
77 $webvar{stype} = "<NULL>"; #shuts up the warnings.
[517]78 $page = HTML::Template->new(filename => "search/compsearch.tmpl");
79} else {
80 $page = HTML::Template->new(filename => "search/sresults.tmpl");
[197]81}
82
[517]83my $header = HTML::Template->new(filename => "header.tmpl");
84$header->param(version => $IPDB::VERSION);
85$header->param(addperm => $IPDBacl{$authuser} =~ /a/);
86print "Content-type: text/html\n\n", $header->output;
[197]87
[517]88# Handle the DB error first
89if (!$ip_dbh) {
90 $page = HTML::Template->new(filename => "dberr.tmpl");
91 $page->param(errmsg => $errstr);
92} elsif ($webvar{stype} eq 'q') {
[197]93 # Quick search.
94
95 if (!$webvar{input}) {
96 # No search term. Display everything.
97 viewBy('all', '');
98 } else {
99 # Search term entered. Display matches.
100 # We should really sanitize $webvar{input}, no?
101 my $searchfor;
102 # Chew up leading and trailing whitespace
103 $webvar{input} =~ s/^\s+//;
104 $webvar{input} =~ s/\s+$//;
[285]105 if ($webvar{input} =~ /^\d+$/) {
106 # All-digits, new custID
107 $searchfor = "cust";
108 } elsif ($webvar{input} =~ /^[\d\.]+(\/\d{1,3})?$/) {
[201]109 # IP addresses should only have numbers, digits, and maybe a slash+netmask
[197]110 $searchfor = "ipblock";
111 } else {
112 # Anything else.
113 $searchfor = "desc";
114 }
115 viewBy($searchfor, $webvar{input});
116 }
117
118} elsif ($webvar{stype} eq 'c') {
119 # Complex search.
120
[201]121 # Several major cases, and a whole raft of individual cases.
122 # -> Show all types means we do not need to limit records retrieved by type
123 # -> Show all cities means we do not need to limit records retrieved by city
124 # Individual cases are for the CIDR/IP, CustID, Description, Notes, and individual type
125 # requests.
126
[207]127 my $sqlconcat;
128 if ($webvar{which} eq 'all') {
129 # Must match *all* specified criteria. ## use INTERSECT or EXCEPT
130 $sqlconcat = "INTERSECT";
131 } elsif ($webvar{which} eq 'any') {
132 # Match on any specified criteria ## use UNION
133 $sqlconcat = "UNION";
134 } else {
[517]135 # sum-buddy tryn'a game the system. Match "all"
136 $sqlconcat = "INTERSECT";
[207]137 }
[197]138
[202]139# We actually construct a monster SQL statement for all criteria.
140# Iff something has been entered, it will be used as a filter.
[208]141# Iff something has NOT been entered, we still include it but in
142# such a way that it does not actually filter anything out.
[201]143
[207]144 # Columns actually returned. Slightly better than hardcoding it
145 # in each (sub)select
146 my $cols = "cidr,custid,type,city,description";
[201]147
[521]148 # hack fix for undefined variables
149 $webvar{custid} = '' if !$webvar{custid};
150 $webvar{desc} = '' if !$webvar{desc};
151 $webvar{notes} = '' if !$webvar{notes};
152 $webvar{custexclude} = '' if !$webvar{custexclude};
153 $webvar{descexclude} = '' if !$webvar{descexclude};
154 $webvar{notesexclude} = '' if !$webvar{notesexclude};
155
[207]156 # First chunk of SQL. Filter on custid, description, and notes as necessary.
[521]157 my $sql = qq(SELECT $cols FROM searchme\n);
158 $sql .= " WHERE $webvar{custexclude} (custid ~ '$webvar{custid}')\n";
159 $sql .= " $sqlconcat (select $cols from searchme where $webvar{descexclude} description ~ '$webvar{desc}')\n";
160 $sql .= " $sqlconcat (select $cols from searchme where $webvar{notesexclude} notes ~ '$webvar{notes}')";
[201]161
[207]162 # If we're not supposed to search for all types, search for the selected types.
163 if ($webvar{alltypes} ne 'on') {
164 $sql .= " $sqlconcat (select $cols from searchme where $webvar{typeexclude} type in (";
165 foreach my $key (keys %webvar) {
166 $sql .= "'$1'," if $key =~ /type\[(..)\]/;
167 }
168 chop $sql;
169 $sql .= "))";
[201]170 }
171
[207]172 # If we're not supposed to search for all cities, search for the selected cities.
173 # This could be vastly improved with proper foreign keys in the database.
174 if ($webvar{allcities} ne 'on') {
175 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cityexclude} city in (";
176 $sth = $ip_dbh->prepare("select city from cities where id=?");
177 foreach my $key (keys %webvar) {
178 if ($key =~ /city\[(\d+)\]/) {
179 $sth->execute($1);
180 my $city;
181 $sth->bind_columns(\$city);
182 $sth->fetch;
183 $city =~ s/'/''/;
184 $sql .= "'$city',";
185 }
[201]186 }
[207]187 chop $sql;
188 $sql .= "))";
[201]189 }
190
[207]191 ## CIDR query options.
192 $webvar{cidr} =~ s/\s+//; # Hates the nasty spaceseseses we does.
[351]193 if ($webvar{cidr} eq '') { # We has a blank CIDR. Ignore it.
[285]194 } elsif ($webvar{cidr} =~ /\//) {
[427]195 # 192.168.179/26 should show all /26 subnets in 192.168.179
[207]196 my ($net,$maskbits) = split /\//, $webvar{cidr};
197 if ($webvar{cidr} =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
198 # /0->/9 are silly to worry about right now. I don't think
199 # we'll be getting a class A anytime soon. <g>
200 $sql .= " $sqlconcat (select $cols from searchme where ".
[351]201 "$webvar{cidrexclude} cidr<<='$webvar{cidr}')";
[207]202 } else {
203 # Partial match; beginning of subnet and maskbits are provided
204 # Show any blocks with the leading octet(s) and that masklength
[351]205 # Need some more magic for bare /nn searches:
206 my $condition = ($net eq '' ?
207 "masklen(cidr)=$maskbits" : "text(cidr) like '$net%' and masklen(cidr)=$maskbits");
[207]208 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
[351]209 "($condition))";
[207]210 }
211 } elsif ($webvar{cidr} =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
212 # Specific IP address match. Will show either a single netblock,
213 # or a static pool plus an IP.
214 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
215 "cidr >>= '$webvar{cidr}')";
216 } elsif ($webvar{cidr} =~ /^\d{1,3}(\.(\d{1,3}(\.(\d{1,3}\.?)?)?)?)?$/) {
217 # Leading octets in CIDR
218 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
219 "text(cidr) like '$webvar{cidr}%')";
220 } else {
[517]221 # do nothing.
222 ##fixme we'll ignore this to clear out the references to legacy code.
[207]223 } # done with CIDR query options.
[201]224
[207]225 # Find the offset for multipage results
226 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
[201]227
[207]228 # Find out how many rows the "core" query will return.
229 my $count = countRows($sql);
[201]230
[207]231 if ($count == 0) {
[517]232 $page->param(errmsg => "No matches found. Try eliminating one of the criteria,".
233 " or making one or more criteria more general.");
[207]234 } else {
235 # Add the limit/offset clauses
[370]236 $sql .= " order by cidr";
237 $sql .= " limit $RESULTS_PER_PAGE offset $offset" if $RESULTS_PER_PAGE != 0;
[207]238 # And tell the user.
239 print "<div class=heading>Searching...............</div>\n";
240 queryResults($sql, $webvar{page}, $count);
241 }
[201]242
[397]243} elsif ($webvar{stype} eq 'n') {
244 # Node search.
245
246 my $sql = "SELECT cidr,custid,type,city,description FROM searchme".
247 " WHERE cidr IN (SELECT block FROM noderef WHERE node_id=$webvar{node})";
248
249 # Find the offset for multipage results
250 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
251
252 # Find out how many rows the "core" query will return.
253 my $count = countRows($sql);
254
255 if ($count == 0) {
[517]256 $page->param(errmsg => "No customers currently listed as connected through this node.");
257##fixme: still get the results table header
[397]258 } else {
259 # Add the limit/offset clauses
260 $sql .= " order by cidr";
261 $sql .= " limit $RESULTS_PER_PAGE offset $offset" if $RESULTS_PER_PAGE != 0;
262 # And tell the user.
263 print "<div class=heading>Searching...............</div>\n";
264 queryResults($sql, $webvar{page}, $count);
265 }
266
[207]267} else { # how script was called. General case is to show the search criteria page.
[201]268
[197]269# Generate table of types
270 $sth = $ip_dbh->prepare("select type,dispname from alloctypes where listorder <500 ".
271 "order by listorder");
272 $sth->execute;
273 my $i=0;
[517]274 my @typelist;
275 while (my ($type,$dispname) = $sth->fetchrow_array) {
276 my %row = (
277 newrow => ($i % 4 == 0),
278 type => $type,
279 dispname => $dispname,
280 endrow => ($i++ % 4 == 3)
281 );
282 push @typelist, \%row;
[197]283 }
[517]284 $page->param(typelist => \@typelist);
[197]285
286# Generate table of cities
287 $sth = $ip_dbh->prepare("select id,city from cities order by city");
288 $sth->execute;
[517]289 $i=0;
290 my @citylist;
291 while (my ($id, $city) = $sth->fetchrow_array) {
292 my %row = (
293 newrow => ($i % 4 == 0),
294 id => $id,
295 city => $city,
296 endrow => ($i++ % 4 == 3)
297 );
298 push @citylist, \%row;
[197]299 }
[517]300 $page->param(citylist => \@citylist);
[197]301
302}
303
[517]304print $page->output;
305
[197]306# Shut down and clean up.
307finish($ip_dbh);
[517]308
309# We print the footer here, so we don't have to do it elsewhere.
310my $footer = HTML::Template->new(filename => "footer.tmpl");
311# include the admin tools link in the output?
312$footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/));
313
314print $footer->output;
315
[197]316# We shouldn't need to directly execute any code below here; it's all subroutines.
317exit 0;
318
[207]319
320# viewBy()
321# The quick search
322# Takes a category descriptor and a query string
323# Creates appropriate SQL to run the search and display the results
324# with queryResults()
[520]325sub viewBy {
[197]326 my ($category,$query) = @_;
327
328 # Local variables
329 my $sql;
330
331 # Calculate start point for LIMIT clause
332 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
333
334# Possible cases:
[207]335# 1) Partial IP/subnet. Treated as "octet-prefix".
336# 2a) CIDR subnet. Exact match.
337# 2b) CIDR netmask. YMMV but it should be octet-prefix-with-netmask
338# (ie, all matches with the octet prefix *AND* that netmask)
339# 3) Customer ID. "Match-any-segment"
340# 4) Description. "Match-any-segment"
[197]341# 5) Invalid data which might be interpretable as an IP or something, but
342# which probably shouldn't be for reasons of sanity.
343
[371]344 my $cols = "cidr,custid,type,city,description";
345
[197]346 if ($category eq 'all') {
347
[371]348 $sql = "select $cols from searchme";
[202]349 my $count = countRows($sql);
[197]350 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
351 queryResults($sql, $webvar{page}, $count);
352
353 } elsif ($category eq 'cust') {
354
[517]355##fixme: this and other quick-search areas; fix up page heading title similar to first grouping above
[197]356 print qq(<div class="heading">Searching for Customer IDs containing '$query'</div><br>\n);
357
358 # Query for a customer ID. Note that we can't restrict to "numeric-only"
359 # as we have non-numeric custIDs in the legacy data. :/
[455]360 $sql = "select $cols from searchme where custid ilike '%$query%' or description like '%$query%'";
[202]361 my $count = countRows($sql);
[197]362 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
363 queryResults($sql, $webvar{page}, $count);
364
365 } elsif ($category eq 'desc') {
366
367 print qq(<div class="heading">Searching for descriptions containing '$query'</div><br>\n);
368 # Query based on description (includes "name" from old DB).
[371]369 $sql = "select $cols from searchme where description ilike '%$query%'".
[285]370 " or custid ilike '%$query%'";
[202]371 my $count = countRows($sql);
[197]372 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
373 queryResults($sql, $webvar{page}, $count);
374
375 } elsif ($category =~ /ipblock/) {
376
377 # Query is for a partial IP, a CIDR block in some form, or a flat IP.
378 print qq(<div class="heading">Searching for IP-based matches on '$query'</div><br>\n);
379
380 $query =~ s/\s+//g;
381 if ($query =~ /\//) {
[427]382 # 192.168.179/26 should show all /26 subnets in 192.168.179
[197]383 my ($net,$maskbits) = split /\//, $query;
384 if ($query =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
385 # /0->/9 are silly to worry about right now. I don't think
386 # we'll be getting a class A anytime soon. <g>
[371]387 $sql = "select $cols from searchme where cidr='$query'";
[197]388 queryResults($sql, $webvar{page}, 1);
389 } else {
[289]390 #print "Finding all blocks with netmask /$maskbits, leading octet(s) $net<br>\n";
[197]391 # Partial match; beginning of subnet and maskbits are provided
[371]392 $sql = "select $cols from searchme where text(cidr) like '$net%' and ".
[197]393 "text(cidr) like '%$maskbits'";
[202]394 my $count = countRows($sql);
[197]395 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
396 queryResults($sql, $webvar{page}, $count);
397 }
398 } elsif ($query =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
399 # Specific IP address match
[289]400 #print "4-octet pattern found; finding netblock containing IP $query<br>\n";
[197]401 my ($net,$ip) = ($query =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})/);
402 my $sfor = new NetAddr::IP $query;
[371]403 $sth = $ip_dbh->prepare("select $cols from searchme where text(cidr) like '$net%'");
[197]404 $sth->execute;
405 while (my @data = $sth->fetchrow_array()) {
406 my $cidr = new NetAddr::IP $data[0];
407 if ($cidr->contains($sfor)) {
[371]408 queryResults("select $cols from searchme where cidr='$cidr'", $webvar{page}, 1);
[197]409 }
410 }
[202]411 } elsif ($query =~ /^(\d{1,3}\.){1,3}\d{1,3}\.?$/) {
[289]412 #print "Finding matches with leading octet(s) $query<br>\n";
[371]413 $sql = "select $cols from searchme where text(cidr) like '$query%'";
[202]414 my $count = countRows($sql);
[197]415 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
416 queryResults($sql, $webvar{page}, $count);
417 } else {
418 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
[517]419 $page->param(errmsg => "Invalid query.");
[197]420 }
421 } else {
422 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
[517]423 $page->param(errmsg => "Invalid searchfor.");
[197]424 }
425} # viewBy
426
427
428# args are: a reference to an array with the row to be printed and the
429# class(stylesheet) to use for formatting.
430# if ommitting the class - call the sub as &printRow(\@array)
431sub printRow {
432 my ($rowRef,$class) = @_;
433
434 if (!$class) {
435 print "<tr>\n";
436 } else {
437 print "<tr class=\"$class\">\n";
438 }
439
440ELEMENT: foreach my $element (@$rowRef) {
441 if (!defined($element)) {
442 print "<td></td>\n";
443 next ELEMENT;
444 }
445 $element =~ s|\n|</br>|g;
446 print "<td>$element</td>\n";
447 }
448 print "</tr>";
449} # printRow
450
451
[207]452# queryResults()
453# Display search queries based on the passed SQL.
454# Takes SQL, page number (for multipage search results), and a total count.
[520]455sub queryResults {
[197]456 my ($sql, $pageNo, $rowCount) = @_;
457 my $offset = 0;
458 $offset = $1 if($sql =~ m/.*limit\s+(.*),.*/);
459
460 my $sth = $ip_dbh->prepare($sql);
461 $sth->execute();
462
[517]463 $page->param(searchtitle => "Showing all netblock and static-IP allocations");
464
[197]465 my $count = 0;
[517]466 my @sresults;
467 while (my ($block, $custid, $type, $city, $desc) = $sth->fetchrow_array) {
468 my %row = (
469 rowclass => $count++ % 2,
470 issub => ($type =~ /^.r$/ ? 1 : 0),
471 block => $block,
472 ispool => ($type =~ /^.[pd]$/ ? 1 : 0),
473 custid => $custid,
474 disptype => $disp_alloctypes{$type},
475 city => $city,
476 desc => $desc
477 );
478 push @sresults, \%row;
[197]479 }
[517]480 $page->param(sresults => \@sresults);
[197]481
482 # Have to think on this call, it's primarily to clean up unfetched rows from a select.
483 # In this context it's probably a good idea.
484 $sth->finish();
485
486 my $upper = $offset+$count;
487
[517]488 $page->param(resfound => $rowCount);
489 $page->param(resstart => $offset+1);
490 $page->param(resstop => $upper);
491
[197]492 # print the page thing..
[370]493 if ($RESULTS_PER_PAGE > 0 && $rowCount > $RESULTS_PER_PAGE) {
[517]494 $page->param(multipage => 1);
[197]495 my $pages = ceil($rowCount/$RESULTS_PER_PAGE);
[517]496 my @pagelist;
[197]497 for (my $i = 1; $i <= $pages; $i++) {
[517]498 my %row;
499 $row{pgnum} = $i;
[197]500 if ($i == $pageNo) {
[517]501 $row{thispage} = 1;
[197]502 } else {
[517]503 $row{stype} = $webvar{stype};
[202]504 if ($webvar{stype} eq 'c') {
[517]505 $row{extraopts} = "cidr=$webvar{cidr}&custid=$webvar{custid}&desc=$webvar{desc}&".
[202]506 "notes=$webvar{notes}&which=$webvar{which}&alltypes=$webvar{alltypes}&".
507 "allcities=$webvar{allcities}&";
508 foreach my $key (keys %webvar) {
[351]509 if ($key =~ /^(?:type|city)\[/ || $key =~ /exclude$/) {
[517]510 $row{extraopts} .= "$key=$webvar{$key}&";
[202]511 }
512 }
513 } else {
[517]514 $row{extraopts} = "input=$webvar{input}&";
[202]515 }
[197]516 }
[517]517 push @pagelist, \%row;
[197]518 }
[517]519 $page->param(pgnums => \@pagelist);
[197]520 }
[517]521
[197]522} # queryResults
523
524
525# Prints table headings. Accepts any number of arguments;
526# each argument is a table heading.
527sub startTable {
528 print qq(<center><table width="98%" cellspacing="0" class="center"><tr>);
529
530 foreach(@_) {
531 print qq(<td class="heading">$_</td>);
532 }
533 print "</tr>\n";
534} # startTable
535
536
[202]537# Return count of rows to be returned in a "real" query
538# with the passed SQL statement
[520]539sub countRows {
[202]540 # Note that the "as foo" is required
541 my $sth = $ip_dbh->prepare("select count(*) from ($_[0]) as foo");
[197]542 $sth->execute();
543 my @a = $sth->fetchrow_array();
544 $sth->finish();
545 return $a[0];
546}
Note: See TracBrowser for help on using the repository browser.