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

Last change on this file since 397 was 397, checked in by Kris Deugau, 14 years ago

/trunk

Merge basic node-tracking from r393:396 into trunk. See #13.

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