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

Last change on this file since 882 was 863, checked in by Kris Deugau, 9 years ago

/trunk

Remove an extraenous $sth->finish from search.cgi

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