Identifier/WhoisCache.pm untested

filter: Statementstmt 0.0% 0 / 319 Branchbran 0.0% 0 / 76 Conditioncond 0.0% 0 / 24 MC/DCmcdc 0.0% 0 / 14 Subroutinesub 0.0% 0 / 34 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 482 CC 38 SCAR 38.5
CC
38
Cov
0%
run
156.0
fetch_whois_rec
90.0
find_in_cache
42.0
CRAP 47.0
1 #!/usr/bin/perl
2 #===============================================================================
3 # PODNAME: Net::IP::Identifier::WhoisCache
4 # ABSTRACT: Run whois, cache result in a database
5 #
6 # AUTHOR: Reid Augustin (REID)
7 # EMAIL: reid@hellosix.com
8 # CREATED: Sat May 2 15:51:45 PDT 2015
9 #===============================================================================
10  
11 use 5.002;
12 use strict;
13 use warnings;
14  
15 {
16 package Local::DBRecord; # a single database record
17 use Moo;
18 use namespace::clean;
19 use overload '""' => \&print;
20  
21 has id => ( is => 'rw' ); # index (INTEGER PRIMARY KEY)
22 has range_str => ( is => 'rw' ); # range as string
23 has entity => ( is => 'rw' ); # name associated with this WHOIS record
24 has result => ( is => 'rw' ); # command result to STDOUT
25 has fetch_time => ( is => 'rw' ); # when WHOIS was last run
26 has first_high => ( is => 'rw' ); # upper 64 its of first IP
27 has first_low => ( is => 'rw' ); # lower 64 its of first IP
28 has last_high => ( is => 'rw' ); # upper 64 its of last IP
29 has last_low => ( is => 'rw' ); # lower 64 its of last IP
30  
31 sub print {
32 my ($self) = @_;
33  
34 return $self->result;
35 }
36 }
37  
38 package Net::IP::Identifier::WhoisCache;
39 use File::Spec;
40 use Getopt::Long qw(:config pass_through);
41 use Try::Tiny;
42 use Carp;
43 use DBI;
44 use IPC::Run qw( new_chunker );
45 use Math::BigInt;
46 use Net::IP; # for IP_IDENTICAL, OVERLAP, etc
47 use Net::IP::Identifier::Net;
48 use Net::IP::Identifier::Regex;
49 use Net::IP::Identifier::WhoisParser;
50 use Moo;
51 use namespace::clean;
52  
53 our $VERSION = '0.111'; # VERSION
54  
55 our @request_columns = (
56 {request_str => 'TEXT NOT NULL PRIMARY KEY',},
57 {whois_id => 'INTEGER NOT NULL', },
58 );
59 my @whois_columns = (
60 {id => 'INTEGER PRIMARY KEY', },
61 {range_str => 'TEXT NOT NULL', },
62 {entity => 'TEXT NOT NULL', },
63 {result => 'TEXT NOT NULL', },
64 {fetch_time => 'UNSIGNED BIG INT', },
65 {first_high => 'UNSIGNED BIG INT', },
66 {first_low => 'UNSIGNED BIG INT', },
67 {last_high => 'UNSIGNED BIG INT', },
68 {last_low => 'UNSIGNED BIG INT', },
69 );
70  
71  
72 # DB field indices:
73 for my $ii (0 .. $#request_columns) {
74 my ($sub_name) = keys %{$request_columns[$ii]};
75 eval "sub $sub_name { $ii };"; ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
76 }
77 for my $ii (0 .. $#whois_columns) {
78 my ($sub_name) = keys %{$whois_columns[$ii]};
79 eval "sub $sub_name { $ii };"; ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
80 }
81  
82 has verbose => ( # verbose mode
83 is => 'rw',
84 );
85 has db_filename => ( # default sqlite database file name
86 is => 'rw',
87 default => "$ENV{HOME}/.whois_cache.sqlite",
88 );
89 has db => ( # database object
90 is => 'lazy',
91 default => sub {
92 my ($self) = @_;
93  
94 my $db = DBI->connect( # connect to your database, create if needed
95 'dbi:SQLite:dbname=' . $self->db_filename, # DSN: dbi, driver, database file
96 '', # no user
97 '', # no password
98 {
99 AutoCommit => 1,
100 RaiseError => 1, # complain if something goes wrong
101 },
102 );
103 $self->_db_schema($db); # make sure table exists
104 return $db;
105 },
106 );
107 has request_table_name => (
108 is => 'lazy',
109 default => sub { 'request_cache' },
110 );
111 has whois_table_name => (
112 is => 'lazy',
113 default => sub { 'whois_cache' },
114 );
115 has parse_failed => ( # error message when parsing WHOIS result fails
116 is => 'rw',
117 );
118 has timeout => ( # seconds before command timeout
119 is => 'rw',
120 default => sub { 30 }, # seconds
121 );
122 has stale_timeout => ( # time until cached record is considered stale
123 is => 'rw',
124 default => sub { 60 * 60 * 24 * 30 }, # 30 days
125 );
126 has _try_ripe => ( # sigh, jwhois might not do this for IPv6, do it by hand
127 is => 'rw',
128 );
129 has force_cache_miss => (
130 is => 'rw',
131 );
132 has sth_select_request => ( # SQL handle for finding requests
133 is => 'lazy',
134 default => sub {
135 my ($self) = @_;
136  
137 $self->db->prepare(
138 join(' ',
139 'SELECT * FROM',
140 $self->request_table_name,
141 'WHERE request_str = ?',
142 ),
143 );
144 },
145 );
146 has sth_insert_request => ( # SQL handle for adding request to database
147 is => 'lazy',
148 default => sub {
149 my ($self) = @_;
150  
151 $self->db->prepare(
152 join(' ',
153 'INSERT OR REPLACE INTO',
154 $self->request_table_name,
155 '(',
156 scalar $self->request_sql_columns,
157 ')',
158 'VALUES (',
159 join(', ',
160 map({ '?' } # one question mark per column
161 @request_columns,
162 ),
163 ),
164 ')',
165 ),
166 );
167 },
168 );
169 has sth_select_whois_by_id => ( # SQL handle for finding WHOIS record by ID
170 is => 'lazy',
171 default => sub {
172 my ($self) = @_;
173  
174 $self->db->prepare(
175 join(' ',
176 'SELECT * FROM',
177 $self->whois_table_name,
178 'WHERE id = ?',
179 ),
180 );
181 },
182 );
183 has sth_select_whois_by_range_str => ( # SQL handle for finding WHOIS record by range_str
184 is => 'lazy',
185 default => sub {
186 my ($self) = @_;
187  
188 $self->db->prepare(
189 join(' ',
190 'SELECT * FROM',
191 $self->whois_table_name,
192 'WHERE range_str = ?',
193 ),
194 );
195 },
196 );
197 has sth_delete_ranges => ( # SQL handle for deleting IPs in the database
198 is => 'lazy',
199 default => sub {
200 my ($self) = @_;
201  
202 $self->db->prepare(
203 join(' ',
204 'DELETE FROM',
205 $self->whois_table_name,
206 # SQL to find an IP or range falling inside a record's range:
207 # match ($db_first <= $ip_first AND $db_last >= $ip_last),
208 # but since first/last are split into two 64 bit ints, we need:
209 # (($db_first_high < $ip_first_high) OR
210 # ($db_first_high == $ip_first_high AND $db_first_low <= $ip_first_low)) AND
211 # (($db_last_high > $ip_last_high ) OR
212 # ($db_last_high == $ip_last_high AND $db_last_low >= $ip_last_low))
213 'WHERE ( first_high < ? OR',
214 ' (first_high == ? AND first_low <= ?)) AND',
215 ' ( last_high > ? OR',
216 ' (last_high == ? AND last_low >= ?))',
217 ),
218 );
219 },
220 );
221 has sth_delete_pattern => ( # SQL handle for deleting IPs based on pattern match
222 is => 'lazy',
223 default => sub {
224 my ($self) = @_;
225  
226 $self->db->prepare(
227 join(' ',
228 'DELETE FROM',
229 $self->whois_table_name,
230 'WHERE result LIKE ?',
231 ),
232 );
233 },
234 );
235 has sth_insert_whois => ( # SQL handle for adding to the WHOIS database
236 is => 'lazy',
237 default => sub {
238 my ($self) = @_;
239  
240 $self->db->prepare(
241 join(' ',
242 'INSERT OR REPLACE INTO',
243 $self->whois_table_name,
244 '(',
245 scalar $self->whois_sql_columns,
246 ')',
247 'VALUES (',
248 join(', ',
249 map({ '?' } # one question mark per column
250 @whois_columns,
251 ),
252 ),
253 ')',
254 ),
255 );
256 },
257 );
258 has sth_max_id => ( # SQL handle get the max ID value in WHOIS database
259 is => 'lazy',
260 default => sub {
261 my ($self) = @_;
262 $self->db->prepare(
263 join(' ',
264 'SELECT MAX(id) from',
265 $self->whois_table_name,
266 ),
267 );
268 },
269 );
270  
271 # some class variables:
272  
273 my (undef, undef, $myName) = File::Spec->splitpath($0);
274  
275 my $help_msg = <<EO_HELP
276  
277 $myName [ options ] IP [ IP... ]
278  
279 Print WHOIS information, and cache it in a database. If the IP is within a
280 netblock that has already been cached, and the cache is younger than the
281 'stale' time, print the cached information instead of running WHOIS again.
282  
283 IP may be dotted decimal format: N.N.N.N, range format: N.N.N.N - N.N.N.N,
284 CIDR format: N.N.N.N/W, or a filename from which IPs will be extracted. If
285 no IP or filename is found on the command line, STDIN is opened.
286  
287 Options (may be abbreviated):
288 filename => SQLite database file name
289 db_filename => a file containing IP addresses and/or ranges
290 parse this file instead of using the
291 command line arguments
292 miss => force a cache miss and update
293 delete => delete by IP or matching WHOIS content
294 entity => an optional string or regular expression to
295 help determine the netblock represented
296 by the WHOIS result
297 verbose => verbose messages
298 help => this message
299  
300 EO_HELP
301 ;
302  
303 # set low 64 bits of a Math::BigInt
304 my $mask_64 = (Math::BigInt->new(1) << 64) - 1; # for masking off bits above 64
305  
306 my $Re = Net::IP::Identifier::Regex->new;
307 my $re_any = $Re->IP_any;
308  
309 # make this package a modulino
310 __PACKAGE__->run unless caller; # modulino
311  
312 sub run {
313 my ($class) = @_;
314  
315 my %opts;
316 my $filename;
317 my $delete;
318 my $help;
319  
320 exit 0 if (not
321 GetOptions(
322 'db_filename=s' => \$opts{db_filename},
323 'miss' => \$opts{force_cache_miss}, # force a cache miss/update
324 'delete=s' => \$delete, # delete record(s) from database
325 'filename=s' => \$filename,
326 'verbose' => \$opts{verbose},
327 'help' => \$help,
328 )
329 );
330  
331 if ($help) {
332 print $help_msg;
333 exit;
334 }
335  
336 map { delete $opts{$_} if not defined $opts{$_} } keys %opts;
337  
338 my $whois_cache = __PACKAGE__->new(%opts);
339  
340 unshift @ARGV, $filename if ($filename);
341  
342 if ($delete) {
343 $whois_cache->delete($delete);
344 return if (not @ARGV);
345 }
346  
347 if (not @ARGV) { # use STDIN?
348 $whois_cache->parse_fh(\*STDIN);
349 }
350  
351 while (@ARGV) {
352 my $arg = shift @ARGV;
353 if (-f $arg) {
354 open my $fh, '<', $arg;
355 croak "Can't open $arg for reading\n" if not $fh;
356 $whois_cache->parse_fh($fh);
357 close $fh;
358 next
359 }
360 elsif ($ARGV[0] and # accept N.N.N.N - N.N.N.N for network blocks too
361 $ARGV[0] eq '-' and
362 $ARGV[1]) {
363 $arg .= (shift @ARGV) . shift @ARGV;
364 }
365  
366 print $whois_cache->get_whois($arg);
367 print "# ", $whois_cache->parse_failed, "\n" if ($whois_cache->parse_failed);
368 }
369 }
370  
371 sub parse_fh {
372 my ($self, $fh) = @_;
373  
374 my $ip_any = $Re->IP_any; # IPv4/6 range, plus, cidr or individual IP
375 while(<$fh>) {
376 my (@ips) = m/($ip_any)/;
377 for my $ip (@ips) {
378 print $self->get_whois($ip), "\n";
379 print "# ", $self->parse_failed, "\n" if ($self->parse_failed);
380 }
381 }
382 }
383  
384 sub ip_str_to_net {
385 my ($self, $req_str) = @_;
386  
387 my ($net, $error);
388 try {
389 $net = Net::IP::Identifier::Net->new($req_str);
390 } catch {
391 $error = $_;
392 };
393 if ($error) {
394 print "# Error converting $req_str to Net object:\n$error";
395 return '';
396 }
397 return $net;
398 }
399  
400 sub get_whois {
401 my ($self, $req_str) = @_;
402  
403 $self->parse_failed(undef); # clear error
404 my $req_net = $self->ip_str_to_net($req_str);
405 if ($req_net->ip ne $req_net->last_ip and
406 not defined $req_net->prefixlen) {
407 # $req_net is a range, but it requires more than a single CIDR to
408 # represent it. this is not legitimate input for jwhois and we
409 # can't really return multiple whois results.
410 my @cidrs = map { sprintf("# %s\n", $_->src_str) } $req_net->range_to_cidrs;
411 die ('# ', $req_net->src_str, " is a non-CIDR range - please split into:\n", @cidrs);
412 }
413 my $record = $self->find_in_cache($req_net);
414 if (not defined $record or
415 $self->force_cache_miss or
416 (time - $record->fetch_time > $self->stale_timeout)) {
417 $record = $self->cache_miss($req_net); # fetch and cache it
418 }
419  
420 return $record;
421 }
422  
423 sub delete {
424 my ($self, $pattern) = @_;
425  
426 my @net_strs = $pattern =~ m/($re_any)/o;
427 if (@net_strs) { # by IP
428 for my $net_str (@net_strs) {
429 my $net = $self->ip_str_to_net($net_str);
430 my ($ip_first_high, $ip_first_low) = $self->split_ip($net->intip);
431 my ($ip_last_high, $ip_last_low ) = $self->split_ip($net->last_int);
432 $self->sth_delete_ranges->execute(
433 "$ip_first_high", "$ip_first_high", "$ip_first_low",
434 "$ip_last_high", "$ip_last_high", "$ip_last_low",
435 );
436 }
437 }
438 else { # by matching WHOIS result to pattern
439 $self->sth_delete_pattern->execute("%$pattern%");
440 }
441 }
442  
443 sub find_in_cache { # try to find $req_net in database
444 my ($self, $req_net) = @_;
445  
446 $self->sth_select_request->execute($req_net->print);
447 my $matches = $self->sth_select_request->fetchall_arrayref;
448 # might be no matches
449 if (not @{$matches}) {
450 print "# Not Found in cache($req_net)\n" if ($self->verbose);
451 return;
452 }
453 my $id = $matches->[0][$self->whois_id]; # get ID of WHOIS record
454  
455 $self->sth_select_whois_by_id->execute($id);
456 $matches = $self->sth_select_whois_by_id->fetchall_arrayref;
457 # might be no matches
458 if (not @{$matches}) {
459 print "# ERROR: $req_net found but no cached WHOIS record with id=$id\n";
460 return;
461 }
462  
463 my $match = $matches->[0]; # should be only one
464 if (not $match) { # shouldn't happen
465 print "# ERROR: $req_net points to empty cache with id=$id\n";
466 return;
467 }
468  
469 my $rec = Local::DBRecord->new();
470 for my $key ($self->whois_sql_columns) {
471 $rec->$key($match->[$self->$key()]); # set DBRecord from DB field
472 }
473 for my $key (qw(first_high first_low last_high last_low)) {
474 # weird, but large ints (with MSB set?) get wrong result if
475 # we just pass the value directly, so convert to hex:
476 $rec->$key(Math::BigInt->new(sprintf("0x%x", $rec->$key)));
477 }
478 print "# Found in cache($req_net)\n" if ($self->verbose);
479  
480 return $rec;
481 }
482  
483 sub cache_miss { # run WHOIS and cache result
484 my ($self, $req_net) = @_;
485  
486 my $whois_rec = $self->fetch_whois_rec($req_net);
487 if ($self->parse_failed and
488 $req_net->version == 6) {
489 print "# Parsing WHOIS result failed, try RIPE\n" if ($self->verbose);
490 $self->_try_ripe(1);
491 $whois_rec = $self->fetch_whois_rec($req_net);
492 }
493 if ($self->parse_failed) { # sigh, we did what we could
494 print "# ", $self->parse_failed, "\n" if ($self->verbose);
495 return $whois_rec; # don't try to cache it
496 }
497  
498 # see if there is already a WHOIS record matching the returned result.
499 # This can happen if cache is stale of if a new (uncached) request
500 # produces WHOIS that's already cached.
501 $self->sth_select_whois_by_range_str->execute($whois_rec->range_str);
502 my ($already) = $self->sth_select_whois_by_range_str->fetchall_arrayref;
503 if ($already and @{$already}) {
504 # 'id' col is PRIMARY KEY. If we set it to existing record, the
505 # insert sth replaces that record instead of inserting a new record
506 $whois_rec->id($already->[0][$self->id]);
507 }
508  
509 my @vals = map { $whois_rec->$_ } $self->whois_sql_columns;
510 # cache (or update) WHOIS record in the whois table
511 $self->sth_insert_whois->execute(@vals);
512 # and insert this request into the request table
513 # if it's already in, it gets updated
514 $self->sth_insert_request->execute(
515 $req_net->print, # request_str
516 $whois_rec->id, # whois_id
517 );
518 # since WHOIS result may not match requested net, add it too,
519 # since it's obviously a valid response were that to be requested
520 # if it's already in, it gets updated
521 $self->sth_insert_request->execute(
522 $whois_rec->range_str, # whois netblock string
523 $whois_rec->id, # whois_id
524 );
525  
526 return $whois_rec;
527 }
528  
529 sub fetch_whois_rec {
530 my ($self, $req_net) = @_;
531  
532 my @cmd = ('jwhois');
533 push @cmd, '-h', 'whois.ripe.net' if ($self->_try_ripe);
534 push @cmd, $req_net->print;
535 print "# Cache miss: running ", join(' ', @cmd), "\n" if ($self->verbose);
536 my $ii = 0;
537 my $whois_result;
538 for (my $ii = 0; $ii < 3; ) {
539 my ($timeout_err, $err);
540 try {
541 # print "run ", join(' ', @cmd), "\n";
542 IPC::Run::run(
543 \@cmd, # run jwhois
544 '>',
545 \$whois_result,
546 '2>',
547 \$err,
548 IPC::Run::timeout( $self->timeout ),
549 ) or $timeout_err = $?;
550 # print "done\n";
551 }
552 catch {
553 $timeout_err = "# Caught: $_";
554 # print "catch error\n";
555 };
556 print "# $err" if ($err);
557  
558 last if not $timeout_err;
559 print "# Timeout: $timeout_err\n";
560  
561 last if ($ii++ >= 2);
562 print "# retry $ii...\n";
563 }
564 if (not defined $whois_result) {
565 die "# No WHOIS result for $req_net\n";
566 }
567  
568 my $rec = Local::DBRecord->new(
569 id => $self->max_id + 1,
570 result => $whois_result,
571 fetch_time => time,
572 );
573  
574 my $parser = Net::IP::Identifier::WhoisParser->new(text => $whois_result);
575  
576 if (defined $parser->range) {
577 $rec->range_str($parser->range->print); # normalized range
578 my ($first_high, $first_low) = $self->split_ip($parser->range->intip);
579 my ($last_high, $last_low ) = $self->split_ip($parser->range->last_int);
580 $rec->first_high($first_high); # upper 64 its of first IP
581 $rec->first_low ($first_low); # lower 64 its of first IP
582 $rec->last_high ($last_high); # upper 64 its of last IP
583 $rec->last_low ($last_low); # lower 64 its of last IP
584 }
585 else {
586 $self->parse_failed("Failed to parse netblock range from WHOIS result");
587 }
588 if ($parser->entity) {
589 $rec->entity($parser->entity);
590 }
591 else {
592 $self->parse_failed("Failed to parse entity from WHOIS result");
593 }
594 return $rec;
595 }
596  
597 sub _db_schema {
598 my ($self, $db) = @_;
599  
600 $db->do(
601 join(' ',
602 'CREATE TABLE IF NOT EXISTS',
603 $self->request_table_name,
604 '(',
605 join(', ',
606 map({join ' ', each %{$_}}
607 @request_columns,
608 ),
609 ),
610 ')',
611 ),
612 );
613 $db->do(
614 join(' ',
615 'CREATE TABLE IF NOT EXISTS',
616 $self->whois_table_name,
617 '(',
618 join(', ',
619 map({join ' ', each %{$_}}
620 @whois_columns,
621 ),
622 ),
623 ')',
624 ),
625 );
626 }
627  
628 # return max value in WHOIS ID rows
629 sub max_id {
630 my ($self) = @_;
631  
632 $self->sth_max_id->execute;
633 my ($max) = $self->sth_max_id->fetchall_arrayref;
634 return $max->[0][0];
635 }
636  
637 # SQL maxes out at 64 bit integers, so split 128 bit IPv6 addresses
638 sub split_ip {
639 my ($self, $int_128) = @_;
640  
641 return ($int_128 >> 64, $int_128 & $mask_64);
642 }
643  
644 # inverse of split_ip, but also converts to IPv4/6
645 sub combine_ip {
646 my ($self, $high, $low, $ipv6) = @_;
647  
648 my @parts;
649 if (not $ipv6) {
650 # IPv4
651 while (@parts < 4) {
652 unshift @parts, $low & 0xff;
653 $low /= 0x100;
654 }
655 return join '.', @parts;
656 }
657 # IPv6
658 my $ip = $high->copy;
659 $ip <<= 64;
660 $ip += $low;
661 while (@parts < 8) {
662 unshift @parts, sprintf("%x", $ip & 0xffff);
663 $ip /= 0x10000;
664 }
665 return join ':', @parts;
666 }
667  
668 # sql columns (without column types)
669 sub request_sql_columns {
670 my ($self) = @_;
671  
672 my @cols = map { keys %{$_} } @request_columns;
673 return wantarray
674 ? @cols
675 : join ', ', @cols;
676 }
677  
678 # sql columns (without column types)
679 sub whois_sql_columns {
680 my ($self) = @_;
681  
682 my @cols = map { keys %{$_} } @whois_columns;
683 return wantarray
684 ? @cols
685 : join ', ', @cols;
686 }
687  
688 1;
689  
690 __END__