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

Last change on this file since 941 was 935, checked in by Kris Deugau, 2 years ago

/trunk

Commit a few little cleanups to search.cgi, along with bringing the header
style in line with current practice

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