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

Last change on this file since 906 was 906, checked in by Kris Deugau, 7 years ago

/trunk

Bulk addition of "add 'the directory the script is in' to @INC" for Perls
that have dropped '.' from @INC

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