source: branches/htmlform/cgi-bin/search.cgi@ 504

Last change on this file since 504 was 502, checked in by Kris Deugau, 13 years ago

/branches/htmlform

Remove stale, unused cleanInput(), desanitize() subs in CommonWeb.pm
Quickly hack up search.cgi to remove printAndExit() from CommonWeb.pm
See #15, #26

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