source: branches/stable/cgi-bin/search.cgi@ 564

Last change on this file since 564 was 507, checked in by Kris Deugau, 13 years ago

/branches/stable

Make the fixed web path at least configurable in one place rather
than completely hardcoded across many files.
Update initial database tabledef SQL
Bump version

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 17.5 KB
RevLine 
[197]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: 2011-11-15 23:08:14 +0000 (Tue, 15 Nov 2011) $
[291]8# SVN revision $Rev: 507 $
[197]9# Last update by $Author: kdeugau $
10###
[507]11# Copyright 2005-2011 - Kris Deugau
[197]12
13use strict;
14use warnings;
15use CGI::Carp qw(fatalsToBrowser);
16use DBI;
17use CommonWeb qw(:ALL);
18use POSIX qw(ceil);
19use NetAddr::IP;
20
[445]21# don't remove! required for GNU/FHS-ish install from tarball
22##uselib##
23
24use MyIPDB;
25
26# Don't formally need a username or syslog here. syslog left active for debugging.
[197]27use Sys::Syslog;
[445]28openlog "IPDBsearch","pid","$IPDB::syslog_facility";
[197]29
[445]30# ... but we do *use* the username on ACLs now.
31# Collect the username from HTTP auth. If undefined, we're in
32# a test environment, or called without a username.
33my $authuser;
34if (!defined($ENV{'REMOTE_USER'})) {
35 $authuser = '__temptest';
36} else {
37 $authuser = $ENV{'REMOTE_USER'};
38}
39
[197]40# Why not a global DB handle? (And a global statement handle, as well...)
41# Use the connectDB function, otherwise we end up confusing ourselves
42my $ip_dbh;
43my $sth;
44my $errstr;
45($ip_dbh,$errstr) = connectDB_My;
46if (!$ip_dbh) {
47 printAndExit("Failed to connect to database: $errstr\n");
48}
49checkDBSanity($ip_dbh);
50initIPDBGlobals($ip_dbh);
51
52# Global variables
[303]53my $RESULTS_PER_PAGE = 25;
[197]54my %webvar = parse_post();
55cleanInput(\%webvar);
56
[357]57if (defined($webvar{rpp})) {
58 ($RESULTS_PER_PAGE) = ($webvar{rpp} =~ /(\d+)/);
59}
60
[197]61if (!defined($webvar{stype})) {
62 $webvar{stype} = "<NULL>"; #shuts up the warnings.
63}
64
[445]65# Headerize! Make sure we replace the $$EXTRA0$$ bit as needed.
[507]66printHeader('', $IPDB::webpath, ($IPDBacl{$authuser} =~ /a/ ?
67 '<td align=right><a href="'.$IPDB::webpath.'/cgi-bin/main.cgi?action=assign">Add new assignment</a></td>' : ''
[445]68 ));
[197]69
70if ($webvar{stype} eq 'q') {
71 # Quick search.
72
73 if (!$webvar{input}) {
74 # No search term. Display everything.
75 viewBy('all', '');
76 } else {
77 # Search term entered. Display matches.
78 # We should really sanitize $webvar{input}, no?
79 my $searchfor;
80 # Chew up leading and trailing whitespace
81 $webvar{input} =~ s/^\s+//;
82 $webvar{input} =~ s/\s+$//;
[286]83 if ($webvar{input} =~ /^\d+$/) {
84 # All-digits, new custID
85 $searchfor = "cust";
86 } elsif ($webvar{input} =~ /^[\d\.]+(\/\d{1,3})?$/) {
[201]87 # IP addresses should only have numbers, digits, and maybe a slash+netmask
[197]88 $searchfor = "ipblock";
89 } else {
90 # Anything else.
91 $searchfor = "desc";
92 }
93 viewBy($searchfor, $webvar{input});
94 }
95
96} elsif ($webvar{stype} eq 'c') {
97 # Complex search.
98
[201]99 # Several major cases, and a whole raft of individual cases.
100 # -> Show all types means we do not need to limit records retrieved by type
101 # -> Show all cities means we do not need to limit records retrieved by city
102 # Individual cases are for the CIDR/IP, CustID, Description, Notes, and individual type
103 # requests.
104
[207]105 my $sqlconcat;
106 if ($webvar{which} eq 'all') {
107 # Must match *all* specified criteria. ## use INTERSECT or EXCEPT
108 $sqlconcat = "INTERSECT";
109 } elsif ($webvar{which} eq 'any') {
110 # Match on any specified criteria ## use UNION
111 $sqlconcat = "UNION";
112 } else {
113 # We can't get here. PTHBTT!
114 printAndExit "PTHBTT!! Your search has been rejected due to Microsoft excuse #4432: ".
115 "Not enough mana";
116 }
[197]117
[202]118# We actually construct a monster SQL statement for all criteria.
119# Iff something has been entered, it will be used as a filter.
[208]120# Iff something has NOT been entered, we still include it but in
121# such a way that it does not actually filter anything out.
[201]122
[207]123 # Columns actually returned. Slightly better than hardcoding it
124 # in each (sub)select
125 my $cols = "cidr,custid,type,city,description";
[201]126
[207]127 # First chunk of SQL. Filter on custid, description, and notes as necessary.
[323]128 my $sql = "(select $cols from searchme where".
129 " $webvar{custexclude} (custid ilike '%$webvar{custid}%'".
130 " OR $webvar{custexclude} oldcustid ilike '%$webvar{custid}%'))".
[201]131 " $sqlconcat (select $cols from searchme where $webvar{descexclude} description ilike '%$webvar{desc}%')".
132 " $sqlconcat (select $cols from searchme where $webvar{notesexclude} notes ilike '%$webvar{notes}%')";
133
[207]134 # If we're not supposed to search for all types, search for the selected types.
135 if ($webvar{alltypes} ne 'on') {
136 $sql .= " $sqlconcat (select $cols from searchme where $webvar{typeexclude} type in (";
137 foreach my $key (keys %webvar) {
138 $sql .= "'$1'," if $key =~ /type\[(..)\]/;
139 }
140 chop $sql;
141 $sql .= "))";
[201]142 }
143
[207]144 # If we're not supposed to search for all cities, search for the selected cities.
145 # This could be vastly improved with proper foreign keys in the database.
146 if ($webvar{allcities} ne 'on') {
147 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cityexclude} city in (";
148 $sth = $ip_dbh->prepare("select city from cities where id=?");
149 foreach my $key (keys %webvar) {
150 if ($key =~ /city\[(\d+)\]/) {
151 $sth->execute($1);
152 my $city;
153 $sth->bind_columns(\$city);
154 $sth->fetch;
155 $city =~ s/'/''/;
156 $sql .= "'$city',";
157 }
[201]158 }
[207]159 chop $sql;
160 $sql .= "))";
[201]161 }
162
[207]163 ## CIDR query options.
164 $webvar{cidr} =~ s/\s+//; # Hates the nasty spaceseseses we does.
[307]165 if ($webvar{cidr} eq '') { # We has a blank CIDR. Ignore it.
[286]166 } elsif ($webvar{cidr} =~ /\//) {
[445]167 # 192.168.179/26 should show all /26 subnets in 192.168.179
[207]168 my ($net,$maskbits) = split /\//, $webvar{cidr};
169 if ($webvar{cidr} =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
170 # /0->/9 are silly to worry about right now. I don't think
171 # we'll be getting a class A anytime soon. <g>
172 $sql .= " $sqlconcat (select $cols from searchme where ".
[309]173 "$webvar{cidrexclude} cidr<<='$webvar{cidr}')";
[207]174 } else {
175 # Partial match; beginning of subnet and maskbits are provided
176 # Show any blocks with the leading octet(s) and that masklength
[307]177 # Need some more magic for bare /nn searches:
178 my $condition = ($net eq '' ?
179 "masklen(cidr)=$maskbits" : "text(cidr) like '$net%' and masklen(cidr)=$maskbits");
[207]180 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
[307]181 "($condition))";
[207]182 }
183 } elsif ($webvar{cidr} =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
184 # Specific IP address match. Will show either a single netblock,
185 # or a static pool plus an IP.
186 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
187 "cidr >>= '$webvar{cidr}')";
188 } elsif ($webvar{cidr} =~ /^\d{1,3}(\.(\d{1,3}(\.(\d{1,3}\.?)?)?)?)?$/) {
189 # Leading octets in CIDR
190 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
191 "text(cidr) like '$webvar{cidr}%')";
192 } else {
193 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
194 printAndExit("Invalid netblock query.");
195 } # done with CIDR query options.
[201]196
[207]197 # Find the offset for multipage results
198 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
[201]199
[207]200 # Find out how many rows the "core" query will return.
201 my $count = countRows($sql);
[201]202
[207]203 if ($count == 0) {
204 printError "No matches found. Try eliminating one of the criteria,".
205 " or making one or more criteria more general.";
206 } else {
207 # Add the limit/offset clauses
[357]208 $sql .= " order by cidr";
209 $sql .= " limit $RESULTS_PER_PAGE offset $offset" if $RESULTS_PER_PAGE != 0;
[207]210 # And tell the user.
211 print "<div class=heading>Searching...............</div>\n";
212 queryResults($sql, $webvar{page}, $count);
213 }
[201]214
[395]215} elsif ($webvar{stype} eq 'n') {
216 # Node search.
217
218 my $sql = "SELECT cidr,custid,type,city,description FROM searchme".
219 " WHERE cidr IN (SELECT block FROM noderef WHERE node_id=$webvar{node})";
220
221 # Find the offset for multipage results
222 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
223
224 # Find out how many rows the "core" query will return.
225 my $count = countRows($sql);
226
227 if ($count == 0) {
228 printError "No customers currently listed as connected through this node.";
229 } else {
230 # Add the limit/offset clauses
231 $sql .= " order by cidr";
232 $sql .= " limit $RESULTS_PER_PAGE offset $offset" if $RESULTS_PER_PAGE != 0;
233 # And tell the user.
234 print "<div class=heading>Searching...............</div>\n";
235 queryResults($sql, $webvar{page}, $count);
236 }
237
[207]238} else { # how script was called. General case is to show the search criteria page.
[201]239
[197]240 # Display search page. We have to do this here, because otherwise
241 # we can't retrieve data from the database for the types and cities. >:(
242 my $html;
243 open HTML,"<../compsearch.html";
244 $html = join('',<HTML>);
245 close HTML;
[507]246 $html =~ s/\$\$WEBPATH\$\$/$IPDB::webpath/g;
[197]247
248# Generate table of types
249 my $typetable = "<table class=regular cellspacing=0>\n<tr>";
250 $sth = $ip_dbh->prepare("select type,dispname from alloctypes where listorder <500 ".
251 "order by listorder");
252 $sth->execute;
253 my $i=0;
254 while (my @data = $sth->fetchrow_array) {
255 $typetable .= "<td><input type=checkbox name=type[$data[0]]>$data[1]</td>";
256 $i++;
257 $typetable .= "</tr>\n<tr>"
258 if ($i % 4 == 0);
259 }
260 if ($i %4 == 0) {
261 $typetable =~ s/<tr>$//;
262 } else {
263 $typetable .= "</tr>\n";
264 }
265 $typetable .= "</table>\n";
266
267# Generate table of cities
268 my $citytable = "<table class=regular cellspacing=0>\n<tr>";
269 $sth = $ip_dbh->prepare("select id,city from cities order by city");
270 $sth->execute;
271 my $i=0;
272 while (my @data = $sth->fetchrow_array) {
273 $citytable .= "<td><input type=checkbox name=city[$data[0]]>$data[1]</td>";
274 $i++;
275 $citytable .= "</tr>\n<tr>"
276 if ($i % 5 == 0);
277 }
278 if ($i %5 == 0) {
279 $citytable =~ s/<tr>$//;
280 } else {
281 $citytable .= "</tr>\n";
282 }
283 $citytable .= "</table>\n";
284
285 $html =~ s/\$\$TYPELIST\$\$/$typetable/;
286 $html =~ s/\$\$CITYLIST\$\$/$citytable/;
287
288 print $html;
289}
290
291# Shut down and clean up.
292finish($ip_dbh);
293printFooter;
294# We shouldn't need to directly execute any code below here; it's all subroutines.
295exit 0;
296
[207]297
298# viewBy()
299# The quick search
300# Takes a category descriptor and a query string
301# Creates appropriate SQL to run the search and display the results
302# with queryResults()
[197]303sub viewBy($$) {
304 my ($category,$query) = @_;
305
306 # Local variables
307 my $sql;
308
309 # Calculate start point for LIMIT clause
310 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
311
312# Possible cases:
[207]313# 1) Partial IP/subnet. Treated as "octet-prefix".
314# 2a) CIDR subnet. Exact match.
315# 2b) CIDR netmask. YMMV but it should be octet-prefix-with-netmask
316# (ie, all matches with the octet prefix *AND* that netmask)
317# 3) Customer ID. "Match-any-segment"
318# 4) Description. "Match-any-segment"
[197]319# 5) Invalid data which might be interpretable as an IP or something, but
320# which probably shouldn't be for reasons of sanity.
321
[361]322 my $cols = "cidr,custid,type,city,description";
323
[197]324 if ($category eq 'all') {
325
326 print qq(<div class="heading">Showing all netblock and static-IP allocations</div><br>\n);
[361]327 $sql = "select $cols from searchme";
[202]328 my $count = countRows($sql);
[197]329 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
330 queryResults($sql, $webvar{page}, $count);
331
332 } elsif ($category eq 'cust') {
333
334 print qq(<div class="heading">Searching for Customer IDs containing '$query'</div><br>\n);
335
336 # Query for a customer ID. Note that we can't restrict to "numeric-only"
337 # as we have non-numeric custIDs in the legacy data. :/
[389]338 $sql = "select $cols from searchme where custid ilike '%$query%' or oldcustid ilike '%$query%' or description like '%$query%'";
[202]339 my $count = countRows($sql);
[197]340 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
341 queryResults($sql, $webvar{page}, $count);
342
343 } elsif ($category eq 'desc') {
344
345 print qq(<div class="heading">Searching for descriptions containing '$query'</div><br>\n);
346 # Query based on description (includes "name" from old DB).
[361]347 $sql = "select $cols from searchme where description ilike '%$query%'".
[286]348 " or custid ilike '%$query%'";
[202]349 my $count = countRows($sql);
[197]350 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
351 queryResults($sql, $webvar{page}, $count);
352
353 } elsif ($category =~ /ipblock/) {
354
355 # Query is for a partial IP, a CIDR block in some form, or a flat IP.
356 print qq(<div class="heading">Searching for IP-based matches on '$query'</div><br>\n);
357
358 $query =~ s/\s+//g;
359 if ($query =~ /\//) {
[445]360 # 192.168.179/26 should show all /26 subnets in 192.168.179
[197]361 my ($net,$maskbits) = split /\//, $query;
362 if ($query =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
363 # /0->/9 are silly to worry about right now. I don't think
364 # we'll be getting a class A anytime soon. <g>
[361]365 $sql = "select $cols from searchme where cidr='$query'";
[197]366 queryResults($sql, $webvar{page}, 1);
367 } else {
[288]368 #print "Finding all blocks with netmask /$maskbits, leading octet(s) $net<br>\n";
[197]369 # Partial match; beginning of subnet and maskbits are provided
[361]370 $sql = "select $cols from searchme where text(cidr) like '$net%' and ".
[197]371 "text(cidr) like '%$maskbits'";
[202]372 my $count = countRows($sql);
[197]373 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
374 queryResults($sql, $webvar{page}, $count);
375 }
376 } elsif ($query =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
377 # Specific IP address match
[288]378 #print "4-octet pattern found; finding netblock containing IP $query<br>\n";
[197]379 my ($net,$ip) = ($query =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})/);
380 my $sfor = new NetAddr::IP $query;
[361]381 $sth = $ip_dbh->prepare("select $cols from searchme where text(cidr) like '$net%'");
[197]382 $sth->execute;
383 while (my @data = $sth->fetchrow_array()) {
384 my $cidr = new NetAddr::IP $data[0];
385 if ($cidr->contains($sfor)) {
[361]386 queryResults("select $cols from searchme where cidr='$cidr'", $webvar{page}, 1);
[197]387 }
388 }
[202]389 } elsif ($query =~ /^(\d{1,3}\.){1,3}\d{1,3}\.?$/) {
[288]390 #print "Finding matches with leading octet(s) $query<br>\n";
[361]391 $sql = "select $cols from searchme where text(cidr) like '$query%'";
[202]392 my $count = countRows($sql);
[197]393 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
394 queryResults($sql, $webvar{page}, $count);
395 } else {
396 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
397 printError("Invalid query.");
398 }
399 } else {
400 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
401 printError("Invalid searchfor.");
402 }
403} # viewBy
404
405
406# args are: a reference to an array with the row to be printed and the
407# class(stylesheet) to use for formatting.
408# if ommitting the class - call the sub as &printRow(\@array)
409sub printRow {
410 my ($rowRef,$class) = @_;
411
412 if (!$class) {
413 print "<tr>\n";
414 } else {
415 print "<tr class=\"$class\">\n";
416 }
417
418ELEMENT: foreach my $element (@$rowRef) {
419 if (!defined($element)) {
420 print "<td></td>\n";
421 next ELEMENT;
422 }
423 $element =~ s|\n|</br>|g;
424 print "<td>$element</td>\n";
425 }
426 print "</tr>";
427} # printRow
428
429
[207]430# queryResults()
431# Display search queries based on the passed SQL.
432# Takes SQL, page number (for multipage search results), and a total count.
[197]433sub queryResults($$$) {
434 my ($sql, $pageNo, $rowCount) = @_;
435 my $offset = 0;
436 $offset = $1 if($sql =~ m/.*limit\s+(.*),.*/);
437
438 my $sth = $ip_dbh->prepare($sql);
439 $sth->execute();
440
441 startTable('Allocation','CustID','Type','City','Description/Name');
442 my $count = 0;
443
444 while (my @data = $sth->fetchrow_array) {
[202]445
[197]446 # cidr,custid,type,city,description,notes
[202]447 # Another bit of HairyPerl(TM) to prefix subblocks with "Sub"
448 my @row = (($data[2] =~ /^.r$/ ? 'Sub ' : '').
[507]449 qq(<a href="$IPDB::webpath/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
[197]450 $data[1], $disp_alloctypes{$data[2]}, $data[3], $data[4]);
451 # Allow listing of pool if desired/required.
452 if ($data[2] =~ /^.[pd]$/) {
[507]453 $row[0] .= ' &nbsp; <a href="'.$IPDB::webpath.'/cgi-bin/main.cgi?action=listpool'.
[197]454 "&pool=$data[0]\">List IPs</a>";
455 }
456 printRow(\@row, 'color1', 1) if ($count%2==0);
457 printRow(\@row, 'color2', 1) if ($count%2!=0);
458 $count++;
459 }
460
461 # Have to think on this call, it's primarily to clean up unfetched rows from a select.
462 # In this context it's probably a good idea.
463 $sth->finish();
464
465 my $upper = $offset+$count;
[202]466 print "<tr><td colspan=10 bgcolor=white class=regular>Records found: $rowCount<br><i>Displaying: ".($offset+1)." - $upper</i></td></tr>\n";
[197]467 print "</table></center>\n";
468
469 # print the page thing..
[357]470 if ($RESULTS_PER_PAGE > 0 && $rowCount > $RESULTS_PER_PAGE) {
[197]471 my $pages = ceil($rowCount/$RESULTS_PER_PAGE);
472 print qq(<div class="center"> Page: );
473 for (my $i = 1; $i <= $pages; $i++) {
474 if ($i == $pageNo) {
475 print "<b>$i&nbsp;</b>\n";
476 } else {
[507]477 print qq(<a href="$IPDB::webpath/cgi-bin/search.cgi?page=$i&stype=$webvar{stype}&);
[202]478 if ($webvar{stype} eq 'c') {
479 print "cidr=$webvar{cidr}&custid=$webvar{custid}&desc=$webvar{desc}&".
480 "notes=$webvar{notes}&which=$webvar{which}&alltypes=$webvar{alltypes}&".
481 "allcities=$webvar{allcities}&";
482 foreach my $key (keys %webvar) {
[309]483 if ($key =~ /^(?:type|city)\[/ || $key =~ /exclude$/) {
[202]484 print "$key=$webvar{$key}&";
485 }
486 }
487 } else {
488 print "input=$webvar{input}&";
489 }
490 print qq(">$i</a>&nbsp;\n);
[197]491 }
492 }
493 print "</div>";
494 }
495} # queryResults
496
497
498# Prints table headings. Accepts any number of arguments;
499# each argument is a table heading.
500sub startTable {
501 print qq(<center><table width="98%" cellspacing="0" class="center"><tr>);
502
503 foreach(@_) {
504 print qq(<td class="heading">$_</td>);
505 }
506 print "</tr>\n";
507} # startTable
508
509
[202]510# Return count of rows to be returned in a "real" query
511# with the passed SQL statement
[197]512sub countRows($) {
[202]513 # Note that the "as foo" is required
514 my $sth = $ip_dbh->prepare("select count(*) from ($_[0]) as foo");
[197]515 $sth->execute();
516 my @a = $sth->fetchrow_array();
517 $sth->finish();
518 return $a[0];
519}
Note: See TracBrowser for help on using the repository browser.