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
Line 
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###
11# Copyright 2005-2010 - Kris Deugau
12
13use strict;
14use warnings;
15use CGI::Carp qw(fatalsToBrowser);
16use CGI::Simple;
17use HTML::Template;
18use DBI;
19use POSIX qw(ceil);
20use NetAddr::IP;
21
22# don't remove! required for GNU/FHS-ish install from tarball
23##uselib##
24
25use MyIPDB;
26
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
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
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;
67if ($ip_dbh) {
68 checkDBSanity($ip_dbh);
69 initIPDBGlobals($ip_dbh);
70}
71
72# Set up some globals
73$ENV{HTML_TEMPLATE_ROOT} = $thingroot."templates";
74
75my $page;
76if (!defined($webvar{stype})) {
77 $webvar{stype} = "<NULL>"; #shuts up the warnings.
78 $page = HTML::Template->new(filename => "search/compsearch.tmpl");
79} else {
80 $page = HTML::Template->new(filename => "search/sresults.tmpl");
81}
82
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;
87
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') {
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+$//;
105 if ($webvar{input} =~ /^\d+$/) {
106 # All-digits, new custID
107 $searchfor = "cust";
108 } elsif ($webvar{input} =~ /^[\d\.]+(\/\d{1,3})?$/) {
109 # IP addresses should only have numbers, digits, and maybe a slash+netmask
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
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
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 {
135 # sum-buddy tryn'a game the system. Match "all"
136 $sqlconcat = "INTERSECT";
137 }
138
139# We actually construct a monster SQL statement for all criteria.
140# Iff something has been entered, it will be used as a filter.
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.
143
144 # Columns actually returned. Slightly better than hardcoding it
145 # in each (sub)select
146 my $cols = "cidr,custid,type,city,description";
147
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
156 # First chunk of SQL. Filter on custid, description, and notes as necessary.
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}')";
161
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 .= "))";
170 }
171
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 }
186 }
187 chop $sql;
188 $sql .= "))";
189 }
190
191 ## CIDR query options.
192 $webvar{cidr} =~ s/\s+//; # Hates the nasty spaceseseses we does.
193 if ($webvar{cidr} eq '') { # We has a blank CIDR. Ignore it.
194 } elsif ($webvar{cidr} =~ /\//) {
195 # 192.168.179/26 should show all /26 subnets in 192.168.179
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 ".
201 "$webvar{cidrexclude} cidr<<='$webvar{cidr}')";
202 } else {
203 # Partial match; beginning of subnet and maskbits are provided
204 # Show any blocks with the leading octet(s) and that masklength
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");
208 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
209 "($condition))";
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 {
221 # do nothing.
222 ##fixme we'll ignore this to clear out the references to legacy code.
223 } # done with CIDR query options.
224
225 # Find the offset for multipage results
226 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
227
228 # Find out how many rows the "core" query will return.
229 my $count = countRows($sql);
230
231 if ($count == 0) {
232 $page->param(errmsg => "No matches found. Try eliminating one of the criteria,".
233 " or making one or more criteria more general.");
234 } else {
235 # Add the limit/offset clauses
236 $sql .= " order by cidr";
237 $sql .= " limit $RESULTS_PER_PAGE offset $offset" if $RESULTS_PER_PAGE != 0;
238 # And tell the user.
239 print "<div class=heading>Searching...............</div>\n";
240 queryResults($sql, $webvar{page}, $count);
241 }
242
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) {
256 $page->param(errmsg => "No customers currently listed as connected through this node.");
257##fixme: still get the results table header
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
267} else { # how script was called. General case is to show the search criteria page.
268
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;
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;
283 }
284 $page->param(typelist => \@typelist);
285
286# Generate table of cities
287 $sth = $ip_dbh->prepare("select id,city from cities order by city");
288 $sth->execute;
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;
299 }
300 $page->param(citylist => \@citylist);
301
302}
303
304print $page->output;
305
306# Shut down and clean up.
307finish($ip_dbh);
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
316# We shouldn't need to directly execute any code below here; it's all subroutines.
317exit 0;
318
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()
325sub viewBy {
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:
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"
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
344 my $cols = "cidr,custid,type,city,description";
345
346 if ($category eq 'all') {
347
348 $sql = "select $cols from searchme";
349 my $count = countRows($sql);
350 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
351 queryResults($sql, $webvar{page}, $count);
352
353 } elsif ($category eq 'cust') {
354
355##fixme: this and other quick-search areas; fix up page heading title similar to first grouping above
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. :/
360 $sql = "select $cols from searchme where custid ilike '%$query%' or description like '%$query%'";
361 my $count = countRows($sql);
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).
369 $sql = "select $cols from searchme where description ilike '%$query%'".
370 " or custid ilike '%$query%'";
371 my $count = countRows($sql);
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 =~ /\//) {
382 # 192.168.179/26 should show all /26 subnets in 192.168.179
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>
387 $sql = "select $cols from searchme where cidr='$query'";
388 queryResults($sql, $webvar{page}, 1);
389 } else {
390 #print "Finding all blocks with netmask /$maskbits, leading octet(s) $net<br>\n";
391 # Partial match; beginning of subnet and maskbits are provided
392 $sql = "select $cols from searchme where text(cidr) like '$net%' and ".
393 "text(cidr) like '%$maskbits'";
394 my $count = countRows($sql);
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
400 #print "4-octet pattern found; finding netblock containing IP $query<br>\n";
401 my ($net,$ip) = ($query =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})/);
402 my $sfor = new NetAddr::IP $query;
403 $sth = $ip_dbh->prepare("select $cols from searchme where text(cidr) like '$net%'");
404 $sth->execute;
405 while (my @data = $sth->fetchrow_array()) {
406 my $cidr = new NetAddr::IP $data[0];
407 if ($cidr->contains($sfor)) {
408 queryResults("select $cols from searchme where cidr='$cidr'", $webvar{page}, 1);
409 }
410 }
411 } elsif ($query =~ /^(\d{1,3}\.){1,3}\d{1,3}\.?$/) {
412 #print "Finding matches with leading octet(s) $query<br>\n";
413 $sql = "select $cols from searchme where text(cidr) like '$query%'";
414 my $count = countRows($sql);
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...
419 $page->param(errmsg => "Invalid query.");
420 }
421 } else {
422 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
423 $page->param(errmsg => "Invalid searchfor.");
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
452# queryResults()
453# Display search queries based on the passed SQL.
454# Takes SQL, page number (for multipage search results), and a total count.
455sub queryResults {
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
463 $page->param(searchtitle => "Showing all netblock and static-IP allocations");
464
465 my $count = 0;
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;
479 }
480 $page->param(sresults => \@sresults);
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
488 $page->param(resfound => $rowCount);
489 $page->param(resstart => $offset+1);
490 $page->param(resstop => $upper);
491
492 # print the page thing..
493 if ($RESULTS_PER_PAGE > 0 && $rowCount > $RESULTS_PER_PAGE) {
494 $page->param(multipage => 1);
495 my $pages = ceil($rowCount/$RESULTS_PER_PAGE);
496 my @pagelist;
497 for (my $i = 1; $i <= $pages; $i++) {
498 my %row;
499 $row{pgnum} = $i;
500 if ($i == $pageNo) {
501 $row{thispage} = 1;
502 } else {
503 $row{stype} = $webvar{stype};
504 if ($webvar{stype} eq 'c') {
505 $row{extraopts} = "cidr=$webvar{cidr}&custid=$webvar{custid}&desc=$webvar{desc}&".
506 "notes=$webvar{notes}&which=$webvar{which}&alltypes=$webvar{alltypes}&".
507 "allcities=$webvar{allcities}&";
508 foreach my $key (keys %webvar) {
509 if ($key =~ /^(?:type|city)\[/ || $key =~ /exclude$/) {
510 $row{extraopts} .= "$key=$webvar{$key}&";
511 }
512 }
513 } else {
514 $row{extraopts} = "input=$webvar{input}&";
515 }
516 }
517 push @pagelist, \%row;
518 }
519 $page->param(pgnums => \@pagelist);
520 }
521
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
537# Return count of rows to be returned in a "real" query
538# with the passed SQL statement
539sub countRows {
540 # Note that the "as foo" is required
541 my $sth = $ip_dbh->prepare("select count(*) from ($_[0]) as foo");
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.