SafeBrowsing3/DBI.pm untested

filter: Statementstmt 0.0% 0 / 231 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 100 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 35 Podpod 0.0% 0 / 29 totaltotal 0.0% 0 / 429 CC 18 SCAR 21.7
CC
18
Cov
0%
create_range
42.0
add_chunks
12.0
close
6.0
CRAP 8.7
1 package Net::Google::SafeBrowsing3::DBI;
2  
3 use strict;
4 use warnings;
5  
6 use base 'Net::Google::SafeBrowsing3::Storage';
7  
8 use Carp;
9 use DBI;
10 use List::Util qw(first);
11  
12  
13 our $VERSION = '0.3';
14  
15  
16 =head1 NAME
17  
18 Net::Google::SafeBrowsing3::DBI - Base class for all DBI-based back-end storage for the Google Safe Browsing v3 database
19  
20 =head1 SYNOPSIS
21  
22 Net::Google::SafeBrowsing3::DBI cannot be used directly. Instead, use a class inheriting Net::Google::SafeBrowsing3::DBI, like L<Net::Google::SafeBrowsing3::MySQL>.
23  
24  
25 use Net::Google::SafeBrowsing3::MySQL;
26  
27 my $storage = Net::Google::SafeBrowsing3::MySQL->new(host => '127.0.0.1', database => 'GoogleSafeBrowsingv3');
28 ...
29 $storage->close();
30  
31 =head1 DESCRIPTION
32  
33 This is a base implementation of L<Net::Google::SafeBrowsing3::Storage> using DBI.
34  
35 =cut
36  
37  
38 =head1 CONSTRUCTOR
39  
40 =over 4
41  
42 =back
43  
44 =head2 new()
45  
46 This method should be overwritten.
47  
48 Arguments
49  
50 =over 4
51  
52 =item keep_all
53  
54 Optional. Set to 1 to keep old information (such as expiring full hashes) in the database. 0 (delete) by default.
55  
56  
57 =back
58  
59 =cut
60  
61 sub new {
62 my ($class, %args) = @_;
63  
64 my $self = { # default arguments
65 debug => 0,
66 keep_all => 0,
67 %args,
68 };
69  
70 bless $self, $class or croak "Can't bless $class: $!";
71  
72  
73 $self->init();
74  
75 return $self;
76 }
77  
78 =head1 PUBLIC FUNCTIONS
79  
80 =over 4
81  
82 See L<Net::Google::SafeBrowsing3::Storage> for a complete list of public functions.
83  
84 =back
85  
86 =head2 close()
87  
88 Cleanup old full hashes, and close the connection to the database.
89  
90 $storage->close();
91  
92  
93 =cut
94  
95 sub close {
96 my ($self, %args) = @_;
97  
98 if ($self->{keep_all} == 0) {
99 $self->{dbh}->do('DELETE FROM full_hashes WHERE `end` < ?', { }, time());
100 }
101  
102 $self->{dbh}->disconnect;
103 }
104  
105  
106 sub init {
107 my ($self, %args) = @_;
108  
109 # Should connect to database
110 # Should check if all tables exist
111 }
112  
113  
114 sub create_table_updates {
115 my ($self, %args) = @_;
116  
117 my $schema = qq{
118 CREATE TABLE updates (
119 last INT NOT NULL DEFAULT '0',
120 wait INT NOT NULL DEFAULT '0',
121 errors INT NOT NULL DEFAULT '1800',
122 list VARCHAR( 50 ) NOT NULL
123 );
124 }; # Need to handle errors
125  
126 $self->{dbh}->do($schema);
127  
128 my $index = qq{
129 CREATE UNIQUE INDEX list_unique ON updates (list);
130 };
131 $self->{dbh}->do($index);
132 }
133  
134 sub create_table_a_chunks {
135 my ($self, %args) = @_;
136  
137 my $schema = qq{
138 CREATE TABLE a_chunks (
139 hostkey VARCHAR( 8 ),
140 prefix VARCHAR( 32 ),
141 num INT NOT NULL,
142 list VARCHAR( 25 ) NOT NULL
143 );
144 };
145  
146 $self->{dbh}->do($schema);
147  
148 my $index = qq{
149 CREATE INDEX a_chunks_hostkey ON a_chunks (
150 hostkey
151 );
152 };
153 $self->{dbh}->do($index);
154  
155 $index = qq{
156 CREATE INDEX a_chunks_num_list ON a_chunks (
157 num,
158 list
159 );
160 };
161 $self->{dbh}->do($index);
162  
163 $index = qq{
164 CREATE UNIQUE INDEX a_chunks_unique ON a_chunks (
165 hostkey,
166 prefix,
167 num,
168 list
169 );
170 };
171 $self->{dbh}->do($index);
172 }
173  
174 sub create_table_s_chunks {
175 my ($self, %args) = @_;
176  
177 my $schema = qq{
178 CREATE TABLE s_chunks (
179 hostkey VARCHAR( 8 ),
180 prefix VARCHAR( 32 ),
181 num INT NOT NULL,
182 add_num INT Default '0',
183 list VARCHAR( 25 ) NOT NULL
184 );
185 };
186  
187 $self->{dbh}->do($schema);
188  
189 my $index = qq{
190 CREATE INDEX s_chunks_hostkey ON s_chunks (
191 hostkey
192 );
193 };
194 $self->{dbh}->do($index);
195  
196 $index = qq{
197 CREATE INDEX s_chunks_num ON s_chunks (
198 num
199 );
200 };
201 $self->{dbh}->do($index);
202  
203 $index = qq{
204 CREATE INDEX s_chunks_num_list ON s_chunks (
205 num,
206 list
207 );
208 };
209 $self->{dbh}->do($index);
210  
211 $index = qq{
212 CREATE UNIQUE INDEX s_chunks_unique ON s_chunks (
213 hostkey,
214 prefix,
215 num,
216 add_num,
217 list
218 );
219 };
220 $self->{dbh}->do($index);
221 }
222  
223 sub create_table_full_hashes {
224 my ($self, %args) = @_;
225  
226 my $schema = qq{
227 CREATE TABLE full_hashes (
228 id INT AUTO_INCREMENT PRIMARY KEY,
229 num INT,
230 hash VARCHAR( 32 ),
231 list VARCHAR( 25 ),
232 end INT Default '0',
233 type INT Default '0'
234 );
235 };
236  
237 $self->{dbh}->do($schema);
238  
239 my $index = qq{
240 CREATE UNIQUE INDEX hash ON full_hashes (
241 num,
242 hash,
243 list
244 );
245 };
246 $self->{dbh}->do($index);
247 }
248  
249 sub create_table_full_hashes_errors {
250 my ($self, %args) = @_;
251  
252 my $schema = qq{
253 CREATE TABLE full_hashes_errors (
254 id INT AUTO_INCREMENT PRIMARY KEY,
255 errors INT Default '0',
256 prefix VARCHAR( 32 ),
257 timestamp INT Default '0'
258 );
259 };
260  
261 $self->{dbh}->do($schema);
262 }
263  
264  
265 sub add_chunks {
266 my ($self, %args) = @_;
267 my $type = $args{type} || 'a';
268 my $chunknum = $args{chunknum} || 0;
269 my $chunks = $args{chunks} || [];
270 my $list = $args{'list'} || '';
271  
272 # $self->{dbh}->do("PRAGMA journal_mode = OFF");
273 # $self->{dbh}->do("PRAGMA synchronous = OFF");
274  
275 if ($type eq 's') {
276 $self->add_chunks_s(chunknum => $chunknum, chunks => $chunks, list => $list);
277 }
278 elsif ($type eq 'a') {
279 $self->add_chunks_a(chunknum => $chunknum, chunks => $chunks, list => $list);
280 }
281  
282 # $self->{dbh}->do("PRAGMA journal_mode = DELETE");
283 # $self->{dbh}->do("PRAGMA synchronous = FULL");
284 }
285  
286 sub add_chunks_s {
287 my ($self, %args) = @_;
288 my $chunknum = $args{chunknum} || 0;
289 my $chunks = $args{chunks} || [];
290 my $list = $args{'list'} || '';
291  
292 my $add = $self->{dbh}->prepare('INSERT INTO s_chunks (prefix, num, add_num, list) VALUES (?, ?, ?, ?)');
293 my $del = $self->{dbh}->prepare('DELETE FROM s_chunks WHERE prefix = ? AND num = ? AND add_num = ? AND list = ?');
294  
295 foreach my $chunk (@$chunks) {
296 $del->execute( $chunk->{prefix}, $chunknum, $chunk->{add_chunknum}, $list );
297 $add->execute( $chunk->{prefix}, $chunknum, $chunk->{add_chunknum}, $list );
298 }
299  
300 if (scalar @$chunks == 0) { # keep empty chunks
301 $del->execute( '', $chunknum, '', $list );
302 $add->execute( '', $chunknum, '', $list );
303 }
304 }
305  
306 sub add_chunks_a {
307 my ($self, %args) = @_;
308 my $chunknum = $args{chunknum} || 0;
309 my $chunks = $args{chunks} || [];
310 my $list = $args{'list'} || '';
311  
312 my $add = $self->{dbh}->prepare('INSERT INTO a_chunks (prefix, num, list) VALUES (?, ?, ?, ?)');
313 my $del = $self->{dbh}->prepare('DELETE FROM a_chunks WHERE prefix = ? AND num = ? AND list = ?');
314  
315 foreach my $chunk (@$chunks) {
316 $del->execute( $chunk->{prefix}, $chunknum, $list );
317 $add->execute( $chunk->{prefix}, $chunknum, $list );
318 }
319  
320 if (scalar @$chunks == 0) { # keep empty chunks
321 $del->execute( '', $chunknum, $list );
322 $add->execute( '', $chunknum, $list );
323 }
324 }
325  
326 sub get_add_chunks {
327 my ($self, %args) = @_;
328 my $prefix = $args{prefix} || '';
329  
330 my @list = ();
331 my $rows = $self->{dbh}->selectall_arrayref("SELECT * FROM a_chunks WHERE prefix = ?", { Slice => {} }, $prefix);
332  
333 foreach my $row (@$rows) {
334 push(@list, { chunknum => $row->{num}, prefix => $prefix, list => $row->{list} });
335 }
336  
337 return @list;
338 }
339  
340 sub get_sub_chunks {
341 my ($self, %args) = @_;
342 my $prefix = $args{prefix} || '';
343  
344 my @list = ();
345 my $rows = $self->{dbh}->selectall_arrayref("SELECT * FROM s_chunks WHERE prefix = ?", { Slice => {} }, $prefix);
346  
347 foreach my $row (@$rows) {
348 push(@list, { chunknum => $row->{num}, prefix => $prefix, addchunknum => $row->{add_num}, list => $row->{list} });
349 }
350  
351 return @list;
352 }
353  
354 sub get_add_chunks_nums {
355 my ($self, %args) = @_;
356 my $list = $args{'list'} || '';
357
358 my @list = ();
359 my $rows = $self->{dbh}->selectall_arrayref("SELECT DISTINCT(num) FROM a_chunks WHERE list = ? ORDER BY num ASC", { Slice => {} }, $list);
360 foreach my $row (@$rows) {
361 push(@list, $row->{num});
362 }
363  
364 return @list;
365 }
366  
367 sub get_sub_chunks_nums {
368 my ($self, %args) = @_;
369 my $list = $args{'list'} || '';
370
371 my @list = ();
372 my $rows = $self->{dbh}->selectall_arrayref("SELECT DISTINCT(num) FROM s_chunks WHERE list = ? ORDER BY num ASC", { Slice => {} }, $list);
373 foreach my $row (@$rows) {
374 push(@list, $row->{num});
375 }
376  
377 return @list;
378 }
379  
380  
381 sub delete_add_ckunks {
382 my ($self, %args) = @_;
383 my $chunknums = $args{chunknums} || [];
384 my $list = $args{'list'} || '';
385  
386 my $num = $self->{dbh}->do("DELETE FROM a_chunks WHERE num IN (" . join(',', @{ $args{chunknums} }) . ") AND list = ?", { }, $list);
387 $self->debug("Rows deleted: $num\n");
388 }
389  
390  
391 sub delete_sub_ckunks {
392 my ($self, %args) = @_;
393 my $chunknums = $args{chunknums} || [];
394 my $list = $args{'list'} || '';
395  
396 my $num = $self->{dbh}->do("DELETE FROM s_chunks WHERE num IN (" . join(',', @{ $args{chunknums} }) . ") AND list = ?" , { }, $list);
397 $self->debug("Rows deleted: $num\n");
398 }
399  
400 sub get_full_hashes {
401 my ($self, %args) = @_;
402 my $hash = $args{hash} || '';
403 my $list = $args{list} || '';
404 my $timestamp = time();
405  
406 my @hashes = ();
407 my $rows = $self->{dbh}->selectall_arrayref("SELECT hash, type FROM full_hashes WHERE `end` >= ? AND list = ? AND hash = ?", { Slice => {} }, $timestamp, $list, $hash);
408  
409 foreach my $row (@$rows) {
410 push(@hashes, $row);
411 }
412  
413 return @hashes;
414 }
415  
416  
417 sub updated {
418 my ($self, %args) = @_;
419 my $time = $args{'time'} || time;
420 my $wait = $args{'wait'} || 1800;
421 my $list = $args{'list'} || '';
422  
423 if ($self->last_update(list => $list)->{'time'} == 0) {
424 $self->{dbh}->do("INSERT INTO updates (last, wait, errors, list) VALUES (?, ?, 0, ?)", undef, $time, $wait, $list);
425 }
426 else {
427 $self->{dbh}->do("UPDATE updates SET last = ?, wait = ?, errors = 0 WHERE list = ?", undef, $time, $wait, $list);
428 }
429 }
430  
431 sub update_error {
432 my ($self, %args) = @_;
433 my $time = $args{'time'} || time;
434 my $list = $args{'list'} || '';
435 my $wait = $args{'wait'} || 60;
436 my $errors = $args{errors} || 1;
437  
438 if ($self->last_update(list => $list)->{'time'} == 0) {
439 $self->{dbh}->do("INSERT INTO updates (last, wait, errors, list) VALUES (?, ?, ?, ?)", undef, $time, $wait, $errors, $list);
440 }
441 else {
442 $self->{dbh}->do("UPDATE updates SET last = ?, wait = ?, errors = ? WHERE list = ?", undef, $time, $wait, $errors, $list);
443 }
444 }
445  
446 sub last_update {
447 my ($self, %args) = @_;
448 my $list = $args{'list'} || '';
449  
450 my $rows = $self->{dbh}->selectall_arrayref("SELECT last, wait, errors FROM updates WHERE list = ? LIMIT 1", { Slice => {} }, $list);
451  
452 foreach my $row (@$rows) {
453 return {'time' => $row->{'last'} || 0, 'wait' => $row->{'wait'} || 1800, errors => $row->{'errors'} || 0};
454 }
455  
456 return {'time' => 0, 'wait' => 1800};
457 }
458  
459 sub add_full_hashes {
460 my ($self, %args) = @_;
461 my $timestamp = $args{timestamp} || time();
462 my $full_hashes = $args{full_hashes} || [];
463  
464 foreach my $hash (@$full_hashes) {
465 $self->{dbh}->do("DELETE FROM full_hashes WHERE hash = ? AND list = ?", { }, $hash->{hash}, $hash->{list});
466 $self->{dbh}->do("INSERT INTO full_hashes (hash, list, `end`, type) VALUES (?, ?, ?, ?)", { }, $hash->{hash}, $hash->{list}, $timestamp + $hash->{life}, $hash->{type} || 0);
467 }
468 }
469  
470 sub full_hash_error {
471 my ($self, %args) = @_;
472 my $timestamp = $args{timestamp} || time();
473 my $prefix = $args{prefix} || '';
474  
475 my $rows = $self->{dbh}->selectall_arrayref("SELECT id, errors FROM full_hashes_errors WHERE prefix = ? LIMIT 1", { Slice => {} }, $prefix);
476  
477 if (scalar @$rows == 0) {
478 $self->{dbh}->do("INSERT INTO full_hashes_errors (prefix, errors, timestamp) VALUES (?, 1, ?)", { }, $prefix, $timestamp);
479 }
480 else {
481 my $errors = $rows->[0]->{errors} + 1;
482 $self->{dbh}->do("UPDATE full_hashes_errors SET errors = ?, timestamp = ? WHERE id = ?", $errors, $timestamp, $rows->[0]->{id});
483 }
484 }
485  
486 sub full_hash_ok {
487 my ($self, %args) = @_;
488 my $timestamp = $args{timestamp} || time();
489 my $prefix = $args{prefix} || '';
490  
491 my $rows = $self->{dbh}->selectall_arrayref("SELECT id, errors FROM full_hashes_errors WHERE prefix = ? AND errors > 0 LIMIT 1", { Slice => {} }, $prefix);
492  
493 if (scalar @$rows > 0) {
494 $self->{dbh}->do("UPDATE full_hashes_errors SET errors = 0, timestamp = ? WHERE id = ?", $timestamp, $rows->[0]->{id});
495 $self->{dbh}->do("DELETE FROM full_hashes_errors WHERE id = ?", $rows->[0]->{id});
496 }
497 }
498  
499 sub get_full_hash_error {
500 my ($self, %args) = @_;
501 my $prefix = $args{prefix} || '';
502  
503 my $rows = $self->{dbh}->selectall_arrayref("SELECT timestamp, errors FROM full_hashes_errors WHERE prefix = ? LIMIT 1", { Slice => {} }, $prefix);
504
505 if (scalar @$rows == 0) {
506 return undef;
507 }
508 else {
509 return $rows->[0];
510 }
511 }
512  
513 sub reset_full_hashes {
514 my ($self, %args) = @_;
515 my $list = $args{'list'} || '';
516  
517 return if ($self->{keep_all} == 1);
518  
519 $self->{delete_full_hashes} ||= $self->{dbh}->prepare('DELETE FROM full_hashes WHERE list = ?');
520 my $sth = $self->{delete_full_hashes};
521 $sth->execute( $list );
522 }
523  
524 sub reset {
525 my ($self, %args) = @_;
526 my $list = $args{'list'} || '';
527  
528 my $sth = $self->{dbh}->prepare('DELETE FROM s_chunks WHERE list = ?');
529 $sth->execute( $list );
530  
531 $sth = $self->{dbh}->prepare('DELETE FROM a_chunks WHERE list = ?');
532 $sth->execute( $list );
533  
534 $self->{delete_full_hashes} ||= $self->{dbh}->prepare('DELETE FROM full_hashes WHERE list = ?');
535 $sth = $self->{delete_full_hashes};
536 $sth->execute( $list );
537  
538 $sth = $self->{dbh}->prepare('DELETE FROM full_hashes_errors');
539 $sth->execute();
540  
541 $sth = $self->{dbh}->prepare('DELETE FROM updates WHERE list = ?');
542 $sth->execute( $list );
543 }
544  
545 sub create_range {
546 my ($self, %args) = @_;
547 my $numbers = $args{numbers} || []; # should already be ordered
548  
549 return '' if (scalar @$numbers == 0);
550  
551 my $range = $$numbers[0];
552 my $new_range = 0;
553 for(my $i = 1; $i < scalar @$numbers; $i++) {
554 # next if ($$numbers[$i] == $$numbers[$i-1]); # should not happen
555  
556 if ($$numbers[$i] != $$numbers[$i-1] + 1) {
557 $range .= $$numbers[$i-1] if ($i > 1 && $new_range == 1);
558 $range .= ',' . $$numbers[$i];
559  
560 $new_range = 0
561 }
562 elsif ($new_range == 0) {
563 $range .= "-";
564 $new_range = 1;
565 }
566 }
567 $range .= $$numbers[scalar @$numbers - 1] if ($new_range == 1);
568  
569 return $range;
570 }
571  
572 sub debug {
573 my ($self, @messages) = @_;
574  
575 print join('', @messages) if ($self->{debug} > 0);
576 }
577  
578  
579 =head1 CHANGELOG
580  
581 =over 4
582  
583 =item 0.3
584  
585 Fix deletion of add and sub chunks
586  
587 =item 0.2
588  
589 Fix duplicate update records. Speed up deletion of chunks.
590  
591  
592 =item 0.1
593  
594 Initial release.
595  
596 =back
597  
598 =head1 SEE ALSO
599  
600 See L<Net::Google::SafeBrowsing3> for handling Google Safe Browsing v3.
601  
602 See L<Net::Google::SafeBrowsing3::Storage> for the list of public functions.
603  
604 See L<Net::Google::SafeBrowsing3::Sqlite> for a back-end using Sqlite.
605  
606 Google Safe Browsing v3 API: L<https://developers.google.com/safe-browsing/developers_guide_v3>
607  
608  
609 =head1 AUTHOR
610  
611 Julien Sobrier, E<lt>julien@sobrier.netE<gt>
612  
613 =head1 COPYRIGHT AND LICENSE
614  
615 Copyright (C) 2015 by Julien Sobrier
616  
617 This library is free software; you can redistribute it and/or modify
618 it under the same terms as Perl itself, either Perl version 5.8.8 or,
619 at your option, any later version of Perl 5 you may have available.
620  
621  
622 =cut
623  
624 1;