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

Last change on this file since 826 was 826, checked in by Kris Deugau, 8 years ago

/trunk

Trim another bit of error dropping from search.cgi

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 19.1 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-06 16:26:16 +0000 (Wed, 06 Apr 2016) $
8# SVN revision $Rev: 826 $
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 # not sure which $sth I'm finishing here, but there it is.
258 $sth->finish;
259
260} elsif ($webvar{stype} eq 'n') {
261 # Node search.
262
263 my $sql = "SELECT $cols FROM searchme".
264 " WHERE cidr IN (SELECT block FROM noderef WHERE node_id=$webvar{node})";
265
266 # Find the offset for multipage results
267 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
268
269 # Find out how many rows the "core" query will return.
270 my $count = countRows($sql);
271
272 if ($count == 0) {
273 $page->param(errmsg => "No customers currently listed as connected through this node.");
274##fixme: still get the results table header
275 } else {
276 # Add the limit/offset clauses
277 $sql .= " order by cidr";
278 $sql .= " limit $RESULTS_PER_PAGE offset $offset" if $RESULTS_PER_PAGE != 0;
279 # And tell the user.
280 print "<div class=heading>Searching...............</div>\n";
281 queryResults($sql, $webvar{page}, $count);
282 }
283
284} else { # how script was called. General case is to show the search criteria page.
285
286# Generate table of types
287 $sth = $ip_dbh->prepare("select type,dispname from alloctypes where listorder <500 ".
288 "order by listorder");
289 $sth->execute;
290 my $i=0;
291 my @typelist;
292 while (my ($type,$dispname) = $sth->fetchrow_array) {
293 my %row = (
294 newrow => ($i % 4 == 0),
295 type => $type,
296 dispname => $dispname,
297 endrow => ($i++ % 4 == 3)
298 );
299 push @typelist, \%row;
300 }
301 $page->param(typelist => \@typelist);
302
303# Generate table of cities
304 $sth = $ip_dbh->prepare("select id,city from cities order by city");
305 $sth->execute;
306 $i=0;
307 my @citylist;
308 while (my ($id, $city) = $sth->fetchrow_array) {
309 my %row = (
310 newrow => ($i % 4 == 0),
311 id => $id,
312 city => $city,
313 endrow => ($i++ % 4 == 3)
314 );
315 push @citylist, \%row;
316 }
317 $page->param(citylist => \@citylist);
318
319}
320
321print $page->output;
322
323# Shut down and clean up.
324finish($ip_dbh);
325
326# We print the footer here, so we don't have to do it elsewhere.
327my $footer = HTML::Template->new(filename => "footer.tmpl", path => @templatepath);
328# include the admin tools link in the output?
329$footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/));
330
331print $footer->output;
332
333# We shouldn't need to directly execute any code below here; it's all subroutines.
334exit 0;
335
336
337# viewBy()
338# The quick search
339# Takes a category descriptor and a query string
340# Creates appropriate SQL to run the search and display the results
341# with queryResults()
342sub viewBy {
343 my ($category,$query) = @_;
344
345 # Local variables
346 my $sql;
347
348 # Calculate start point for LIMIT clause
349 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
350
351# Possible cases:
352# 1) Partial IP/subnet. Treated as "octet-prefix".
353# 2a) CIDR subnet. Exact match.
354# 2b) CIDR netmask. YMMV but it should be octet-prefix-with-netmask
355# (ie, all matches with the octet prefix *AND* that netmask)
356# 3) Customer ID. "Match-any-segment"
357# 4) Description. "Match-any-segment"
358# 5) Invalid data which might be interpretable as an IP or something, but
359# which probably shouldn't be for reasons of sanity.
360
361 if ($category eq 'all') {
362
363 $sql = "select $cols from searchme s JOIN allocations a ON s.master_id=a.id";
364 my $count = countRows($sql);
365 $sql .= " order by s.cidr limit $RESULTS_PER_PAGE offset $offset";
366 queryResults($sql, $webvar{page}, $count);
367
368 } elsif ($category eq 'cust') {
369
370##fixme: this and other quick-search areas; fix up page heading title similar to first grouping above
371 print qq(<div class="heading">Searching for Customer IDs containing '$query'</div><br>\n);
372
373 # Query for a customer ID. Note that we can't restrict to "numeric-only"
374 # as we have non-numeric custIDs in the legacy data. :/
375 $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%'";
376 my $count = countRows($sql);
377 $sql .= " order by s.cidr limit $RESULTS_PER_PAGE offset $offset";
378 queryResults($sql, $webvar{page}, $count);
379
380 } elsif ($category eq 'desc') {
381
382 print qq(<div class="heading">Searching for descriptions containing '$query'</div><br>\n);
383 # Query based on description (includes "name" from old DB).
384 $sql = "select $cols from searchme s JOIN allocations a ON s.master_id=a.id where s.description ilike '%$query%'".
385 " or s.custid ilike '%$query%'";
386 my $count = countRows($sql);
387 $sql .= " order by s.cidr limit $RESULTS_PER_PAGE offset $offset";
388 queryResults($sql, $webvar{page}, $count);
389
390 } elsif ($category =~ /ipblock/) {
391
392 # Query is for a partial IP, a CIDR block in some form, or a flat IP.
393 print qq(<div class="heading">Searching for IP-based matches on '$query'</div><br>\n);
394
395 $query =~ s/\s+//g;
396 if ($query =~ /\//) {
397 # 192.168.179/26 should show all /26 subnets in 192.168.179
398 my ($net,$maskbits) = split /\//, $query;
399 if ($query =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
400 # /0->/9 are silly to worry about right now. I don't think
401 # we'll be getting a class A anytime soon. <g>
402 $sql = "select $cols from searchme s JOIN allocations a ON s.master_id=a.id where s.cidr='$query'";
403 queryResults($sql, $webvar{page}, 1);
404 } else {
405 #print "Finding all blocks with netmask /$maskbits, leading octet(s) $net<br>\n";
406 # Partial match; beginning of subnet and maskbits are provided
407 $sql = "select $cols from searchme s JOIN allocations a ON s.master_id=a.id".
408 " where text(s.cidr) like '$net%' and text(s.cidr) like '%$maskbits'";
409 my $count = countRows($sql);
410 $sql .= " order by s.cidr limit $RESULTS_PER_PAGE offset $offset";
411 queryResults($sql, $webvar{page}, $count);
412 }
413 } elsif ($query =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
414 # Specific IP address match
415 #print "4-octet pattern found; finding netblock containing IP $query<br>\n";
416 my ($net,$ip) = ($query =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})/);
417 my $sfor = new NetAddr::IP $query;
418# $sth = $ip_dbh->prepare("select $cols from searchme s JOIN allocations a ON s.master_id=a.id where text(s.cidr) like '$net%'");
419#print "select $cols from searchme s JOIN allocations a ON s.master_id=a.id where text(s.cidr) like '$net%'";
420
421# $sth->execute;
422# while (my @data = $sth->fetchrow_array()) {
423# my $cidr = new NetAddr::IP $data[0];
424# if ($cidr->contains($sfor) || $cidr == $sfor) {
425#print "cidr: $data[0]\n";
426#print "<br>select $cols from searchme s JOIN allocations a ON s.master_id=a.id where s.cidr='$cidr' and s.type <> 'mm'";
427 queryResults(
428#"select $cols from searchme s JOIN allocations a ON s.master_id=a.id where s.cidr='$cidr' and s.type <> 'mm'",
429"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",
430 $webvar{page}, 1);
431#print $page->output;
432# }
433# }
434 } elsif ($query =~ /^(\d{1,3}\.){1,3}\d{1,3}\.?$/) {
435 #print "Finding matches with leading octet(s) $query<br>\n";
436 $sql = "SELECT $cols FROM searchme s JOIN allocations a ON s.master_id=a.id".
437 " WHERE text(s.cidr) LIKE '$query%'";
438 my $count = countRows($sql);
439 $sql .= " order by s.cidr limit $RESULTS_PER_PAGE offset $offset";
440 queryResults($sql, $webvar{page}, $count);
441 } else {
442 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
443 $page->param(errmsg => "Invalid query.");
444 }
445 } else {
446 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
447 $page->param(errmsg => "Invalid searchfor.");
448 }
449} # viewBy
450
451
452
453# queryResults()
454# Display search queries based on the passed SQL.
455# Takes SQL, page number (for multipage search results), and a total count.
456sub queryResults {
457 my ($sql, $pageNo, $rowCount) = @_;
458 my $offset = 0;
459 $offset = $1 if($sql =~ m/.*limit\s+(.*),.*/);
460
461 my $sth = $ip_dbh->prepare($sql);
462 $sth->execute();
463
464 $page->param(searchtitle => "Showing all netblock and static-IP allocations");
465
466 my $count = 0;
467 my @sresults;
468 while (my ($block, $custid, $type, $city, $desc, $id, $parent, $avail, $vrf) = $sth->fetchrow_array) {
469 my %row = (
470 rowclass => $count++ % 2,
471 vrf => $vrf,
472 issub => ($type =~ /^.r$/ ? 1 : 0),
473 ispool => ($type =~ /^.[pd]$/ ? 1 : 0),
474 basetype => ($type =~ /^.i/ ? 'i' : 'b'),
475 freeip => ($avail eq 'y'),
476 parent => $parent,
477 block => $block,
478 custid => $custid,
479 disptype => $disp_alloctypes{$type},
480 city => $city,
481 desc => $desc,
482 id => $id,
483 );
484 push @sresults, \%row;
485 }
486 $page->param(sresults => \@sresults);
487
488 # Have to think on this call, it's primarily to clean up unfetched rows from a select.
489 # In this context it's probably a good idea.
490 $sth->finish();
491
492 my $upper = $offset+$count;
493
494 $page->param(resfound => $rowCount);
495 $page->param(resstart => $offset+1);
496 $page->param(resstop => $upper);
497
498 # print the page thing..
499 if ($RESULTS_PER_PAGE > 0 && $rowCount > $RESULTS_PER_PAGE) {
500 $page->param(multipage => 1);
501 my $pages = ceil($rowCount/$RESULTS_PER_PAGE);
502 my @pagelist;
503 for (my $i = 1; $i <= $pages; $i++) {
504 my %row;
505 $row{pgnum} = $i;
506 if ($i == $pageNo) {
507 $row{thispage} = 1;
508 } else {
509 $row{stype} = $webvar{stype};
510 if ($webvar{stype} eq 'c') {
511 $row{extraopts} = "cidr=$webvar{cidr}&custid=$webvar{custid}&desc=$webvar{desc}&".
512 "notes=$webvar{notes}&which=$webvar{which}&alltypes=$webvar{alltypes}&".
513 "allcities=$webvar{allcities}&";
514 foreach my $key (keys %webvar) {
515 if ($key =~ /^(?:type|city)\[/ || $key =~ /exclude$/) {
516 $row{extraopts} .= "$key=$webvar{$key}&";
517 }
518 }
519 } else {
520 $row{extraopts} = "input=$webvar{input}&";
521 }
522 }
523 push @pagelist, \%row;
524 }
525 $page->param(pgnums => \@pagelist);
526 }
527
528} # queryResults
529
530
531
532# Return count of rows to be returned in a "real" query
533# with the passed SQL statement
534sub countRows {
535 # Note that the "as foo" is required
536 my $sth = $ip_dbh->prepare("select count(*) from ($_[0]) as foo");
537 $sth->execute();
538 my @a = $sth->fetchrow_array();
539 $sth->finish();
540 return $a[0];
541}
Note: See TracBrowser for help on using the repository browser.