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

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

/trunk

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