blib/lib/Ereshkigal/Kur.pm

filter: Statementstmt 13.7% 94 / 684 Branchbran 12.8% 30 / 234 Conditioncond 6.6% 6 / 90 MC/DCmcdc 5.4% 3 / 55 Subroutinesub 14.4% 10 / 69 Podpod 100% 8 / 8 totaltotal 13.2% 151 / 1140 CC 168 SCAR 43.5
CC
168
Cov
13%
_load_state
342.0
_load_retry_state
210.0
_cmd_clear_retries
156.0
CRAP 77.8
« blib/lib/Ereshkigal.pm ↑ Summary blib/lib/Ereshkigal/App/Command/start.pm »
1 package Ereshkigal::Kur;
2  
3 14 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 14 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 14 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 14 ▶use base 'Error::Helper';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 14 ▶use POE;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 14 ▶use POE::Component::Server::JSONUnix ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 14 ▶use Net::Firewall::BlockerHelper ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 14 ▶use Ereshkigal::LogDrek qw( log_drek );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 14 ▶use Ereshkigal::IP qw( normalize_ip normalize_cidr );
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 =head1 NAME
14  
15 Ereshkigal::Kur - FW handler for Ereshkigal.
16  
17 =head1 VERSION
18  
19 Version 0.0.1
20  
21 =cut
22  
23 14 our $VERSION = '0.0.1';
24  
25 =head1 SYNOPSIS
26  
27 use Ereshkigal::Kur;
28  
29 my $kur = Ereshkigal::Kur->new(
30 'name' => 'sshd',
31 'backend' => 'ipfw',
32 'ports' => ['22'],
33 'protocols' => ['tcp'],
34 );
35  
36 $kur->start_server;
37  
38 Each Kur instance wraps a single L<Net::Firewall::BlockerHelper> instance and
39 serves it up via a L<POE::Component::Server::JSONUnix> server listening on a
40 unix socket under C<$run_base_dir/kur/>.
41  
42 =head1 METHODS
43  
44 =head2 new
45  
46 Initiates the object. All errors are considered fatal, meaning if new fails
47 it will die.
48  
49 - name :: Name of this specific instance. Must match /^[a-zA-Z0-9\-]+$/.
50 Default :: undef
51  
52 - backend :: The backend to use for Net::Firewall::BlockerHelper.
53 Default :: undef
54  
55 - ports :: An array of ports to block, passed to Net::Firewall::BlockerHelper.
56 Default :: []
57  
58 - protocols :: An array of protocols to block, passed to Net::Firewall::BlockerHelper.
59 Default :: []
60  
61 - prefix :: Prefix to use, passed to Net::Firewall::BlockerHelper.
62 Default :: undef, left for the backend to default to kur
63  
64 - options :: Backend specific options hash, passed to Net::Firewall::BlockerHelper.
65 Default :: undef, left for the backend to default to {}
66  
67 - self_heal :: Self heal setting, passed to Net::Firewall::BlockerHelper.
68 Default :: undef, left for the backend to default to 1
69  
70 - ban_time :: How long bans should last in seconds. 0 means bans never
71 time out. May be overridden per ban request.
72 Default :: 600
73  
74 - checkpoint :: Seconds between periodic rewrites of the ban state CSV.
75 0 disables the periodic rewrite... ban/unban, stop, and on demand
76 checkpoints still happen.
77 Default :: 60
78  
79 - enable_cidr :: Boolean for whether CIDR banning is enabled for this
80 instance. Even when set, CIDR commands only work if the backend
81 supports CIDR bans. Config files carry strings rather than
82 booleans, so the value is folded... undef, the empty string, 0,
83 false, no, and off are all off, and anything else at all is on.
84 Default :: 0
85  
86 - cidr_silent_drop :: Boolean for how a CIDR command is handled when CIDR
87 banning is not available for this instance, either because
88 enable_cidr is off or the backend does not support it. When set the
89 command is silently dropped, returning dropped => 1, rather than
90 erroring, which is the point when fanning out to a mix of CIDR
91 capable and incapable instances. Folded the same way enable_cidr
92 is.
93 Default :: 0
94  
95 - run_base_dir :: Base dir for run files. The socket and PID for this
96 instance live under C<$run_base_dir/kur/> named for this instance.
97 Default :: /var/run/ereshkigal
98  
99 - cache_base_dir :: Base dir for cache files. The ban state and the
100 unban retry state for this instance are persisted as CSVs under
101 here, named for the instance, so timed bans and unbans still owed
102 to the firewall both survive a restart. See L</state_path>,
103 L</cidr_state_path>, L</retry_state_path>, and
104 L</cidr_retry_state_path> for the four.
105 Default :: /var/cache/ereshkigal
106  
107 =cut
108  
109 23 ▶sub new {
Subroutine new: called CC=26 SCAR=33.6
Pod documented
110 23 my ( $blank, %opts ) = @_;
111  
112 23 my $self = {
113 perror => undef,
114 error => undef,
115 errorLine => undef,
116 errorFilename => undef,
117 errorString => "",
118 errorExtra => {
119 all_errors_fatal => 1,
120 all_fatal => 1,
121 flags => {
122 1 => 'NErunBaseDir',
123 2 => 'invalidName',
124 3 => 'backendInitFailed',
125 4 => 'nonRWrunBaseDir',
126 5 => 'NEcacheBaseDir',
127 6 => 'nonRWcacheBaseDir',
128 7 => 'invalidBanTime',
129 8 => 'invalidCheckpoint',
130 },
131 fatal_flags => {},
132 perror_not_fatal => 0,
133 },
134 name => undef,
135 backend => undef,
136 ports => [],
137 protocols => [],
138 prefix => undef,
139 options => undef,
140 self_heal => undef,
141 ban_time => 600,
142 checkpoint => 60,
143 enable_cidr => 0,
144 cidr_silent_drop => 0,
145 run_base_dir => '/var/run/ereshkigal',
146 cache_base_dir => '/var/cache/ereshkigal',
147 backend_obj => undef,
148 cidr_supported => 0,
149 server => undef,
150 started => undef,
151 stopping => 0,
152 bans => {},
153 cidr_bans => {},
154 unban_retries => {},
155 cidr_unban_retries => {},
156 last_checkpoint => 0,
157 stats => {
158 bans => 0,
159 unbans => 0,
160 cidr_bans => 0,
161 cidr_unbans => 0,
162 errors => 0,
163 expired => 0,
164 cidr_expired => 0,
165 },
166 };
167 23 bless $self;
168  
169 23 my @to_merge = (
170 'name', 'backend', 'ports', 'protocols',
171 'prefix', 'options', 'self_heal', 'ban_time',
172 'checkpoint', 'enable_cidr', 'cidr_silent_drop', 'run_base_dir',
173 'cache_base_dir'
174 );
175 23 foreach my $item (@to_merge) {
176 299 ▶ if ( defined( $opts{$item} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{$item}) 143 156 299
177 143 $self->{$item} = $opts{$item};
178 }
179 }
180  
181 # the two CIDR toggles are booleans... a config may hand them over as the
182 # literal strings true/false, which are both truthy in Perl, so those are
183 # folded down before the truthiness of the value is trusted
184 23 foreach my $toggle ( 'enable_cidr', 'cidr_silent_drop' ) {
185 46 ▶ if ( !defined( $self->{$toggle} ) || $self->{$toggle} =~ /\A(?:|0|false|no|off)\z/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{$toggle} or $self->{$toggle} =~ /\A(?:|0|false|no|off)\z/i) { } 45 1 46
Condition66%2/3
not defined $self->{$toggle} or $self->{$toggle} =~ /\A(?:|0|false|no|off)\z/i
l!l&&r!l&&!r
0451
MC/DC50%1/2
not defined $self->{$toggle} or $self->{$toggle} =~ /\A(?:|0|false|no|off)\z/i
not defined $self->{$toggle} $self->{$toggle} =~ /\A(?:|0|false|no|off)\z/i
Truth table66%2/3
not(A) or B
A= not defined $self->{$toggle}B= $self->{$toggle} =~ /\A(?:|0|false|no|off)\z/i
ABresult
1X1
011
000
186 45 $self->{$toggle} = 0;
187 } else {
188 1 $self->{$toggle} = 1;
189 }
190 }
191  
192 23 ▶ if ( $self->{ban_time} !~ /^[0-9]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"ban_time"} =~ /^[0-9]+$/) 2 21 23
193 2 $self->{perror} = 1;
194 2 $self->{error} = 7;
195 2 $self->{errorString} = 'ban_time, "' . $self->{ban_time} . '", is not a non-negative int of seconds';
196 2 $self->warn;
197 }
198  
199 21 ▶ if ( $self->{checkpoint} !~ /^[0-9]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"checkpoint"} =~ /^[0-9]+$/) 2 19 21
200 2 $self->{perror} = 1;
201 2 $self->{error} = 8;
202 2 $self->{errorString} = 'checkpoint, "' . $self->{checkpoint} . '", is not a non-negative int of seconds';
203 2 $self->warn;
204 }
205  
206 19 ▶ if ( !defined( $self->{name} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $self->{'name'}) { } 1 18 19
elsif (not $self->{'name'} =~ /^[a-zA-Z0-9\-]+$/) { } 5 13 18
207 1 $self->{perror} = 1;
208 1 $self->{error} = 2;
209 1 $self->{errorString} = 'name is undef';
210 1 $self->warn;
211 } elsif ( $self->{name} !~ /^[a-zA-Z0-9\-]+$/ ) {
212 5 $self->{perror} = 1;
213 5 $self->{error} = 2;
214 5 $self->{errorString} = 'The specified name, "' . $self->{name} . '", does not match /^[a-zA-Z0-9\-]+$/';
215 5 $self->warn;
216 }
217  
218 13 foreach my $dir ( $self->{run_base_dir}, $self->{run_base_dir} . '/kur' ) {
219 24 ▶ if ( !-e $dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $dir) 14 10 24
220 # don't need to check if this worked failed or not here as the next if statement will handle that
221 14 eval { mkdir($dir); };
222 }
223 24 ▶ if ( !-d $dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $dir) 1 23 24
224 1 $self->{perror} = 1;
225 1 $self->{error} = 1;
226 1 $self->{errorString} = 'run dir,"' . $dir . '", does not exist or is not a directory';
227 1 $self->warn;
228 }
229 23 ▶ if ( !-r $dir || !-w $dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-r $dir and -w $dir) 1 22 23
Condition66%2/3
-r $dir and -w $dir
!ll&&!rl&&r
0122
MC/DC50%1/2
-r $dir and -w $dir
-r $dir -w $dir
Truth table66%2/3
A and B
A= -r $dirB= -w $dir
ABresult
0X0
100
111
230 1 $self->{perror} = 1;
231 1 $self->{error} = 4;
232 1 $self->{errorString} = 'run dir,"' . $dir . '", is either not writable or readable by the current user';
233 1 $self->warn;
234 }
235 } ## end foreach my $dir ( $self->{run_base_dir}, $self->...)
236  
237 11 ▶ if ( !-e $self->{cache_base_dir} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $self->{"cache_base_dir"}) 7 4 11
238 # don't need to check if this worked failed or not here as the next if statement will handle that
239 7 eval { mkdir( $self->{cache_base_dir} ); };
240 }
241 11 ▶ if ( !-d $self->{cache_base_dir} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $self->{"cache_base_dir"}) 1 10 11
242 1 $self->{perror} = 1;
243 1 $self->{error} = 5;
244 1 $self->{errorString} = 'cache_base_dir,"' . $self->{cache_base_dir} . '", does not exist or is not a directory';
245 1 $self->warn;
246 }
247 10 ▶ if ( !-r $self->{cache_base_dir} || !-w $self->{cache_base_dir} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-r $self->{"cache_base_dir"} and -w $self->{"cache_base_dir"}) 1 9 10
Condition66%2/3
-r $self->{"cache_base_dir"} and -w $self->{"cache_base_dir"}
!ll&&!rl&&r
019
MC/DC50%1/2
-r $self->{"cache_base_dir"} and -w $self->{"cache_base_dir"}
-r $self->{"cache_base_dir"} -w $self->{"cache_base_dir"}
Truth table66%2/3
A and B
A= -r $self->{"cache_base_dir"}B= -w $self->{"cache_base_dir"}
ABresult
0X0
100
111
248 1 $self->{perror} = 1;
249 1 $self->{error} = 6;
250 $self->{errorString}
251 = 'cache_base_dir,"'
252 . $self->{cache_base_dir}
253 1 . '", is either not writable or readable by the current user';
254 1 $self->warn;
255 }
256  
257 9 eval {
258 $self->{backend_obj} = Net::Firewall::BlockerHelper->new(
259 backend => $self->{backend},
260 ports => $self->{ports},
261 protocols => $self->{protocols},
262 name => $self->{name},
263 defined( $self->{prefix} ) ? ( prefix => $self->{prefix} ) : (),
264 defined( $self->{options} ) ? ( options => $self->{options} ) : (),
265 9 ▶ defined( $self->{self_heal} ) ? ( self_heal => $self->{self_heal} ) : (),
Branch: 3 branches
BranchTrueFalseTotal
defined $self->{'prefix'} ? : 1 8 9
defined $self->{'options'} ? : 0 9 9
defined $self->{'self_heal'} ? : 1 8 9
266 );
267 1 $self->{backend_obj}->init_backend;
268 };
269 9 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 9 0 9
270 9 $self->{perror} = 1;
271 9 $self->{error} = 3;
272 9 $self->{errorString} = 'Failed to init the backend... ' . $@;
273 9 $self->warn;
274 }
275  
276 # note whether the backend can carry CIDR bans... enable_cidr is the
277 # operator opting in, but a backend that cannot do CIDR still cannot, so
278 # the two together are what gate the CIDR commands
279 0 $self->{cidr_supported} = $self->_backend_cidr_supported;
280 0 ▶ if ( $self->{enable_cidr} && !$self->{cidr_supported} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"enable_cidr"} and not $self->{"cidr_supported"}) 0 0 0
Condition0%0/3
$self->{"enable_cidr"} and not $self->{"cidr_supported"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"enable_cidr"} and not $self->{"cidr_supported"}
$self->{"enable_cidr"} not $self->{"cidr_supported"}
Truth table0%0/3
A and not(B)
A= $self->{"enable_cidr"}B= not $self->{"cidr_supported"}
ABresult
0X0
100
111
281 log_drek(
282 'warning',
283 'enable_cidr is set but the "'
284 . $self->{backend}
285 . '" backend does not support CIDR bans... CIDR commands will be refused',
286 undef,
287 0 ▶ 'kur-' . ( defined( $self->{name} ) ? $self->{name} : '' )
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'name'} ? : 0 0 0
288 );
289 } ## end if ( $self->{enable_cidr} && !$self->{cidr_supported...})
290  
291 # bring any persisted ban state back, dropping and unbanning whatever
292 # expired while not running
293 0 $self->_load_bans;
294 0 $self->_load_cidr_bans;
295 0 $self->_load_retries;
296  
297 0 return $self;
298 } ## end sub new
299  
300 =head2 socket_path
301  
302 Returns the path of the unix socket for this instance.
303  
304 my $socket_path = $kur->socket_path;
305  
306 =cut
307  
308 0 ▶sub socket_path {
Subroutine socket_path: not called CC=1 SCAR=6.9
Pod documented
309 0 my ($self) = @_;
310  
311 0 return $self->{run_base_dir} . '/kur/' . $self->{name} . '.sock';
312 }
313  
314 =head2 pid_path
315  
316 Returns the path of the PID file for this instance.
317  
318 my $pid_path = $kur->pid_path;
319  
320 =cut
321  
322 0 ▶sub pid_path {
Subroutine pid_path: not called CC=1 SCAR=6.9
Pod documented
323 0 my ($self) = @_;
324  
325 0 return $self->{run_base_dir} . '/kur/' . $self->{name} . '.pid';
326 }
327  
328 =head2 state_path
329  
330 Returns the path of the ban state CSV for this instance.
331  
332 my $state_path = $kur->state_path;
333  
334 =cut
335  
336 0 ▶sub state_path {
Subroutine state_path: not called CC=1 SCAR=6.9
Pod documented
337 0 my ($self) = @_;
338  
339 0 return $self->{cache_base_dir} . '/kur.' . $self->{name} . '.csv';
340 }
341  
342 =head2 cidr_state_path
343  
344 Returns the path of the CIDR ban state CSV for this instance. This is kept
345 separate from L</state_path> so the single IP state format stays untouched.
346  
347 my $cidr_state_path = $kur->cidr_state_path;
348  
349 =cut
350  
351 0 ▶sub cidr_state_path {
Subroutine cidr_state_path: not called CC=1 SCAR=6.9
Pod documented
352 0 my ($self) = @_;
353  
354 0 return $self->{cache_base_dir} . '/kur.' . $self->{name} . '.cidr.csv';
355 }
356  
357 =head2 retry_state_path
358  
359 Returns the path of the unban retry state CSV for this instance, the tablet
360 carrying entries whose unban at expiry failed and is still owed to the
361 firewall.
362  
363 my $retry_state_path = $kur->retry_state_path;
364  
365 =cut
366  
367 0 ▶sub retry_state_path {
Subroutine retry_state_path: not called CC=1 SCAR=6.9
Pod documented
368 0 my ($self) = @_;
369  
370 0 return $self->{cache_base_dir} . '/kur.' . $self->{name} . '.retry.csv';
371 }
372  
373 =head2 cidr_retry_state_path
374  
375 Returns the path of the CIDR unban retry state CSV for this instance, the
376 CIDR counterpart of L</retry_state_path>.
377  
378 my $cidr_retry_state_path = $kur->cidr_retry_state_path;
379  
380 =cut
381  
382 0 ▶sub cidr_retry_state_path {
Subroutine cidr_retry_state_path: not called CC=1 SCAR=6.9
Pod documented
383 0 my ($self) = @_;
384  
385 0 return $self->{cache_base_dir} . '/kur.' . $self->{name} . '.cidr.retry.csv';
386 }
387  
388 =head2 start_server
389  
390 Starts up the L<POE::Component::Server::JSONUnix> server for this instance,
391 calling $poe_kernel->run.
392  
393 This should not be expected to return till the server is told to stop.
394  
395 The socket is chmoded to 0600 given only the manager, running as the same
396 user, talks to it.
397  
398 A ban sweeper is also started, which checks once a second for timed bans
399 that have expired and unbans them, and handles the periodic checkpointing
400 of the ban state CSVs. SIGTERM and SIGINT are handled, checkpointing and
401 tearing the backend down the same as the stop command before exiting.
402  
403 IPs passed to ban and unban are validated and normalized to their canonical
404 string form, so variant spellings of the same IP, most notably IPv6 long
405 form vs short form as well as case, are all treated as the same IP. For ban
406 anything failing to validate errors per IP without disturbing the rest of
407 the request, while for unban it is fatal to the request.
408  
409 The JSON commands handled are as below.
410  
411 - ban :: Ban the IPs specified via the array args.ips. args.ban_time,
412 if defined, overrides the instance default for how long the bans
413 should last in seconds, with 0 meaning never time out. Banning an
414 already banned IP just refreshes its timer.
415  
416 - unban :: Check if the IP, args.ip, is banned and if so unban it.
417  
418 - cidr_ban :: Ban the CIDR ranges specified via the array args.cidrs,
419 otherwise behaving like ban. Only handled when enable_cidr is set
420 and the backend supports CIDR bans, otherwise it is either dropped
421 or refused per cidr_silent_drop.
422  
423 - cidr_unban :: Check if the CIDR, args.cidr, is banned and if so unban
424 it. Gated the same as cidr_ban.
425  
426 - banned :: Return a list of banned IPs along with an expires map of
427 when each times out, 0 meaning never. banned_cidr and cidr_expires
428 carry the same for CIDR bans. unban_retries and cidr_unban_retries
429 carry the per entry book keeping for unbans still owed to the
430 firewall.
431  
432 - status :: Return instance status info and stats, including ban_time,
433 counts of timed and permanent bans, the next expiry, and how many
434 unbans are still owed to the firewall along with how long the
435 longest owed has been outstanding.
436  
437 - flush :: Unban everything currently banned, ranges as well as single
438 IPs, emptying both ban books and both unban retry books with them.
439  
440 - re_init :: Have the backend tear its firewall setup down and build it
441 again, re-banning everything the ban books carry. Bans are not
442 enforced while that is happening. Tearing down takes any rule a
443 failed unban left behind, so the retry books are emptied too.
444  
445 - checkpoint :: Write the ban state CSVs out now.
446  
447 - clear_retries :: Forget unbans still owed to the firewall, either the
448 single one named by args.ip or args.cidr, or all of them when
449 neither is given. Only the book keeping is forgotten, nothing is
450 asked of the firewall, so anything genuinely still banished there
451 stays that way.
452  
453 - stop :: Checkpoint, teardown the backend, and exit.
454  
455 =cut
456  
457 0 ▶sub start_server {
Subroutine start_server: not called CC=1 SCAR=6.9
Pod documented
458 0 my ($self) = @_;
459  
460 0 $self->errorblank;
461  
462 0 my $ident = 'kur-' . $self->{name};
463  
464 my $server = POE::Component::Server::JSONUnix->spawn(
465 'socket_path' => $self->socket_path,
466 'socket_mode' => oct('0600'),
467 'alias' => $ident,
468 0 ▶ 'on_error' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
469 0 my ( $operation, $errnum, $errstr ) = @_;
470 0 log_drek( 'err', 'socket error during ' . $operation . '... ' . $errstr . ' (' . $errnum . ')',
471 undef, $ident );
472 },
473 'commands' => {
474 0 ▶ 'ban' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
475 0 my ( undef, $request ) = @_;
476 0 return $self->_cmd_ban($request);
477 },
478 0 ▶ 'unban' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
479 0 my ( undef, $request ) = @_;
480 0 return $self->_cmd_unban($request);
481 },
482 0 ▶ 'cidr_ban' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
483 0 my ( undef, $request ) = @_;
484 0 return $self->_cmd_cidr_ban($request);
485 },
486 0 ▶ 'cidr_unban' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
487 0 my ( undef, $request ) = @_;
488 0 return $self->_cmd_cidr_unban($request);
489 },
490 0 ▶ 'banned' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
491 0 return $self->_cmd_banned;
492 },
493 0 ▶ 'status' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
494 0 return $self->_cmd_status;
495 },
496 0 ▶ 'flush' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
497 0 return $self->_cmd_flush;
498 },
499 0 ▶ 're_init' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
500 0 return $self->_cmd_re_init;
501 },
502 0 ▶ 'checkpoint' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
503 0 return $self->_cmd_checkpoint;
504 },
505 0 ▶ 'clear_retries' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
506 0 my ( undef, $request ) = @_;
507 0 return $self->_cmd_clear_retries($request);
508 },
509 0 ▶ 'stop' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
510 0 my ( undef, undef, $ctx ) = @_;
511 0 return $self->_cmd_stop($ctx);
512 },
513 },
514 0 );
515  
516 0 $self->{server} = $server;
517 0 $self->{started} = time;
518  
519 # the ban sweeper... a self-rescheduling one second alarm that expires
520 # timed bans and handles the periodic checkpoint... it stops
521 # rescheduling once stop has been requested so the session ends and the
522 # kernel can exit... it also watches for TERM/INT so a signaled kur
523 # still checkpoints and tears the backend down rather than dying with
524 # the firewall state dangling
525 POE::Session->create(
526 'inline_states' => {
527 0 ▶ '_start' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
528 0 $_[KERNEL]->sig( 'TERM', 'sig_shutdown' );
529 0 $_[KERNEL]->sig( 'INT', 'sig_shutdown' );
530 0 $_[KERNEL]->delay( 'sweep', 1 );
531 },
532 0 ▶ 'sweep' => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
533 0 ▶ if ( $self->{stopping} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"stopping"}) 0 0 0
534 0 return;
535 }
536 0 $self->_tick;
537 0 $_[KERNEL]->delay( 'sweep', 1 );
538 },
539 0 ▶ 'sig_shutdown' => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
540 0 my $signal = $_[ARG0];
541 0 $_[KERNEL]->sig_handled;
542 0 ▶ if ( $self->{stopping} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"stopping"}) 0 0 0
543 0 return;
544 }
545 0 log_drek( 'info', 'SIG' . $signal . ' received, tearing the backend down', undef, $ident );
546 0 $self->_stop_guts;
547 # _stop_guts set stopping, so the pending sweep alarm is the
548 # only thing keeping this session alive... clear it and fire
549 # the server session's shutdown so the kernel can exit
550 0 $_[KERNEL]->delay('sweep');
551 0 $_[KERNEL]->post( $ident, 'shutdown' );
552 },
553 },
554 0 );
555  
556 0 log_drek( 'info', 'started... socket=' . $self->socket_path . ' backend=' . $self->{backend}, undef, $ident );
557  
558 0 $poe_kernel->run;
559  
560 0 log_drek( 'info', 'stopped', undef, $ident );
561  
562 0 return;
563 } ## end sub start_server
564  
565 # The single choke point for every call into the Net::Firewall::BlockerHelper
566 # frontend held in $self->{backend_obj}. It exists because that frontend has
567 # two ways of failing and only one of them is a die... depending on the
568 # Error::Helper fatality settings in play a failure may instead just warn and
569 # leave the error flag set, which a bare method call would sail straight past.
570 # Everything in this module goes through here so both look the same to the
571 # caller, which is why none of the command handlers check errors themselves.
572 #
573 # The method is called on the frontend inside an eval. A die is rethrown as
574 # is, and if the call survived but left the frontend's error flag set, the
575 # frontend's errorString is thrown instead.
576 #
577 # Args, the first required and the rest optional...
578 #
579 # $method :: The name of the method to call on the frontend, as a plain
580 # string, called as a method so it may be any of the frontend's
581 # public API... 'ban', 'unban', 'ban_cidr', 'unban_cidr',
582 # 'list', 'list_cidr', 'check', 'flush', 're_init', or
583 # 'teardown'. Not validated here, so a name the frontend does
584 # not implement dies with the usual can't locate object method.
585 # %args :: The remaining pairs, passed through to that method verbatim.
586 # In practice this is either empty, for the ones taking no
587 # arguments, or a single ban => $entry pair for the ban and
588 # unban family.
589 #
590 # Returns whatever the method returned, as a list, propagated unchanged. For
591 # list and list_cidr that is the entries the firewall is carrying; for check
592 # it is a single true or false healthy value, which is why callers of that
593 # assign it as ($healthy); for the rest it is generally empty and ignored.
594 #
595 # Dies with either the frontend's own exception or its errorString, neither
596 # carrying a trailing newline, so a caller wanting to report it cleanly has
597 # to trim it.
598 #
599 # my @banned = $self->_backend_do('list');
600 #
601 # $self->_backend_do( 'unban', ban => '1.2.3.4' );
602 #
603 # my ($healthy) = $self->_backend_do('check');
604 0 ▶sub _backend_do {
Subroutine _backend_do: not called CC=3 SCAR=24.8
605 0 my ( $self, $method, %args ) = @_;
606  
607 0 my @results;
608 0 eval { @results = $self->{backend_obj}->$method(%args); };
609 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
610 0 die($@);
611 }
612 0 ▶ if ( $self->{backend_obj}->error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"backend_obj"}->error) 0 0 0
613 0 die( $self->{backend_obj}->errorString );
614 }
615  
616 0 return @results;
617 } ## end sub _backend_do
618  
619 # The per family knobs the shared ban/unban/sweep/load helpers use. The single
620 # IP and the CIDR paths are identical beyond these, so rather than two near
621 # copies of every helper there is one of each taking a $spec, which is one of
622 # the two entries below... $family_spec{ip} or $family_spec{cidr}. Any helper
623 # below documenting a $spec argument means one of these two hash refs, and
624 # names only the keys it actually reaches for.
625 #
626 # The keys, all present in both entries...
627 #
628 # noun :: The family in error messages meant for a human,
629 # 'IP' or 'CIDR'.
630 # label :: The family in lower case, 'ip' or 'cidr'. Used as
631 # the first column name in the tablet header, and
632 # matched against when deciding if a tablet's first
633 # line is that header.
634 # log_label :: What one entry of this family is called in the log,
635 # 'ban' or 'cidr ban'.
636 # infix :: Fragment glued into log lines before the entry
637 # itself, '' or 'cidr '. Separate from log_label as
638 # the two read differently depending on the sentence.
639 # normalizer :: Code ref, normalize_ip or normalize_cidr, taking one
640 # raw string and returning the canonical form or undef
641 # if it will not validate. Everything is put through
642 # this before being booked, which is what keeps the
643 # books canonical only.
644 # ban_method :: Frontend method banning one entry, 'ban' or
645 # 'ban_cidr'.
646 # unban_method :: Frontend method unbanning one entry, 'unban' or
647 # 'unban_cidr'.
648 # list_method :: Frontend method listing what the firewall carries,
649 # 'list' or 'list_cidr'.
650 # hash :: Name of the key on $self holding this family's ban
651 # book, 'bans' or 'cidr_bans'. That book is a hash of
652 # canonical entry to { banned_at => epoch,
653 # expires => epoch or 0 for never }.
654 # retry_hash :: Name of the key on $self holding this family's unban
655 # retry book, 'unban_retries' or
656 # 'cidr_unban_retries'. That book is a hash of
657 # canonical entry to { first_tried => epoch,
658 # last_tried => epoch, times_tried => int,
659 # next_try => epoch, delay => seconds }.
660 # ban_stat :: Key under $self->{stats} counting bans for this
661 # family, 'bans' or 'cidr_bans'.
662 # unban_stat :: Key under $self->{stats} counting unbans,
663 # 'unbans' or 'cidr_unbans'.
664 # expired_stat :: Key under $self->{stats} counting expiries,
665 # 'expired' or 'cidr_expired'.
666 # checkpoint :: Name of the method writing this family's ban tablet,
667 # '_checkpoint' or '_checkpoint_cidr'. Called as
668 # $self->$method with no arguments.
669 # retry_checkpoint :: Name of the method writing this family's retry
670 # tablet, '_checkpoint_retries' or
671 # '_checkpoint_cidr_retries'.
672 # retry_path :: Name of the accessor giving this family's retry
673 # tablet path, 'retry_state_path' or
674 # 'cidr_retry_state_path'.
675 # retry_arg :: The request argument naming a single entry of this
676 # family, 'ip' or 'cidr'. Used by the clear_retries
677 # handler to work out which family was named.
678 14 my %family_spec = (
679 'ip' => {
680 'noun' => 'IP',
681 'label' => 'ip',
682 'log_label' => 'ban',
683 'infix' => '',
684 'normalizer' => \&normalize_ip,
685 'ban_method' => 'ban',
686 'unban_method' => 'unban',
687 'list_method' => 'list',
688 'hash' => 'bans',
689 'retry_hash' => 'unban_retries',
690 'ban_stat' => 'bans',
691 'unban_stat' => 'unbans',
692 'expired_stat' => 'expired',
693 'checkpoint' => '_checkpoint',
694 'retry_checkpoint' => '_checkpoint_retries',
695 'retry_path' => 'retry_state_path',
696 'retry_arg' => 'ip',
697 },
698 'cidr' => {
699 'noun' => 'CIDR',
700 'label' => 'cidr',
701 'log_label' => 'cidr ban',
702 'infix' => 'cidr ',
703 'normalizer' => \&normalize_cidr,
704 'ban_method' => 'ban_cidr',
705 'unban_method' => 'unban_cidr',
706 'list_method' => 'list_cidr',
707 'hash' => 'cidr_bans',
708 'retry_hash' => 'cidr_unban_retries',
709 'ban_stat' => 'cidr_bans',
710 'unban_stat' => 'cidr_unbans',
711 'expired_stat' => 'cidr_expired',
712 'checkpoint' => '_checkpoint_cidr',
713 'retry_checkpoint' => '_checkpoint_cidr_retries',
714 'retry_path' => 'cidr_retry_state_path',
715 'retry_arg' => 'cidr',
716 },
717 );
718  
719 # Guard called at the top of every command handler that would touch the
720 # backend, refusing it once stop has been requested. It exists because stop
721 # tears the backend down and writes a final tablet, but the server session
722 # stays up for another second so the stop response can flush... anything
723 # arriving in that window would both fail against a torn down backend and
724 # overwrite the fresh tablet stop just left behind. The read only handlers,
725 # banned and status, and the book only ones, checkpoint and clear_retries,
726 # deliberately do not call this, as neither can do that damage.
727 #
728 # Takes no arguments beyond the invocant, reading $self->{stopping}, which
729 # _stop_guts sets.
730 #
731 # Returns nothing meaningful, an empty return, when the kur is not stopping.
732 # The whole point is the die on the other branch, so callers just call it and
733 # carry on.
734 #
735 # Dies with 'this kur is stopping', no trailing newline, once stopping is
736 # set. That reaches the client as a normal error response.
737 #
738 # sub _cmd_flush {
739 # my ($self) = @_;
740 # $self->_refuse_when_stopping;
741 # ...
742 # }
743 0 ▶sub _refuse_when_stopping {
Subroutine _refuse_when_stopping: not called CC=2 SCAR=17.9
744 0 my ($self) = @_;
745  
746 0 ▶ if ( $self->{stopping} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"stopping"}) 0 0 0
747 0 die('this kur is stopping');
748 }
749  
750 0 return;
751 }
752  
753 # Works out how long the bans in one request should last, which is the
754 # instance default unless that request carried its own ban_time. This is the
755 # per request layer of the ban_time layering, the ones below it having already
756 # been resolved into $self->{ban_time} by new... a request beats the kur
757 # setting, which beats the manager wide one, which beats 600.
758 #
759 # Validation happens here rather than being left to the backend so a bad
760 # ban_time fails the whole request up front, instead of after some of its IPs
761 # have already been banned.
762 #
763 # Args, one required...
764 #
765 # $args :: The args hash ref of the request, which is whatever the client
766 # sent and so may be missing keys or carry rubbish. Only
767 # args.ban_time is looked at, and it is optional... when absent
768 # or undef the instance default is used. When present it must be
769 # a plain scalar of digits, so a non-negative integer of seconds
770 # with 0 meaning the ban never expires. A ref, a negative number,
771 # or anything non-numeric dies.
772 #
773 # Returns the effective ban_time as an integer of seconds, 0 meaning the bans
774 # should never expire. Callers hand that straight to _ban_many.
775 #
776 # Dies with 'args.ban_time must be a non-negative int of seconds', no
777 # trailing newline, on a carried ban_time that will not validate.
778 #
779 # my $ban_time = $self->_resolve_ban_time( $request->{args} );
780 #
781 # # with args of { ips => ['1.2.3.4'], ban_time => 3600 } that is 3600,
782 # # and with { ips => ['1.2.3.4'] } it is whatever $self->{ban_time} is
783 0 ▶sub _resolve_ban_time {
Subroutine _resolve_ban_time: not called CC=4 SCAR=30.0
784 0 my ( $self, $args ) = @_;
785  
786 0 ▶ if ( !defined( $args->{ban_time} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $args->{"ban_time"}) 0 0 0
787 0 return $self->{ban_time};
788 }
789 0 ▶ if ( ref( $args->{ban_time} ) ne '' || $args->{ban_time} !~ /^[0-9]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args->{"ban_time"} ne "" or not $args->{"ban_time"} =~ /^[0-9]+$/) 0 0 0
Condition0%0/3
ref $args->{"ban_time"} ne "" or not $args->{"ban_time"} =~ /^[0-9]+$/
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $args->{"ban_time"} ne "" or not $args->{"ban_time"} =~ /^[0-9]+$/
ref $args->{"ban_time"} ne "" not $args->{"ban_time"} =~ /^[0-9]+$/
Truth table0%0/3
A or not(B)
A= ref $args->{"ban_time"} ne ""B= not $args->{"ban_time"} =~ /^[0-9]+$/
ABresult
1X1
011
000
790 0 die('args.ban_time must be a non-negative int of seconds');
791 }
792  
793 0 return $args->{ban_time};
794 } ## end sub _resolve_ban_time
795  
796 # Gives self_heal its chance on the refresh path. Normally self_heal lives
797 # inside the backend's own ban and unban, checking the firewall setup is still
798 # there before each one, but re-banning something already banned deliberately
799 # does not call the backend at all... and for a ban source hammering the same
800 # handful of addresses that refresh is the common case, so a setup swept away
801 # by a firewall reload could go unnoticed indefinitely. This runs the
802 # check-and-re_init half by hand to close that.
803 #
804 # Reads the effective self_heal, defaulting to on when the instance leaves it
805 # undef, and returns straight away when it is off. Otherwise the backend is
806 # asked to check, and if that succeeds but reports unhealthy the backend is
807 # asked to re_init. A successful re_init empties both retry books and
808 # checkpoints them, since re_init tears the setup down and rebuilds from the
809 # ban books, taking any rule a failed unban left behind with it.
810 #
811 # Takes no arguments beyond the invocant.
812 #
813 # Returns nothing meaningful, an empty return, whichever branch it took.
814 #
815 # Deliberately dies for nothing. Both backend calls are wrapped, a failed
816 # check is treated as no reason to act, and a failed re_init is only logged...
817 # this is best effort housekeeping on the way through a refresh, so a
818 # firewall having a bad moment is left for the next real ban to trip over
819 # rather than turning a successful refresh into an error.
820 #
821 # # from _ban_many, on finding the entry already in the book
822 # $self->_refresh_heal;
823 # $self->{ $spec->{hash} }{$entry}{expires} = $expires;
824 0 ▶sub _refresh_heal {
Subroutine _refresh_heal: not called CC=7 SCAR=40.3
825 0 my ($self) = @_;
826  
827 0 ▶ my $self_heal = defined( $self->{self_heal} ) ? ( $self->{self_heal} ? 1 : 0 ) : 1;
Branch: 2 branches
BranchTrueFalseTotal
defined $self->{'self_heal'} ? : 0 0 0
$self->{'self_heal'} ? : 0 0 0
828 0 ▶ if ( !$self_heal ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self_heal) 0 0 0
829 0 return;
830 }
831  
832 0 my $healthy;
833 0 eval { ($healthy) = $self->_backend_do('check'); };
834 0 ▶ if ( !$@ && !$healthy ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($@ or $healthy) 0 0 0
Condition0%0/3
$@ or $healthy
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ or $healthy
$@ $healthy
Truth table0%0/3
A or B
A= $@B= $healthy
ABresult
1X1
011
000
835 0 eval { $self->_backend_do('re_init'); };
836 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
837 0 log_drek( 'err', 're_init during refresh self heal failed... ' . $@, undef, 'kur-' . $self->{name} );
838 } else {
839 # re_init re-bans only what the book carries, so anything pending
840 # an unban retry is no longer in the firewall
841 0 $self->{unban_retries} = {};
842 0 $self->{cidr_unban_retries} = {};
843 0 $self->_checkpoint_retries;
844 0 $self->_checkpoint_cidr_retries;
845 }
846 } ## end if ( !$@ && !$healthy )
847  
848 0 return;
849 } ## end sub _refresh_heal
850  
851 # The shared loop body behind both _cmd_ban and _cmd_cidr_ban, the two being
852 # identical once the family knobs are parameterized out. Every entry is
853 # answered for separately, so one bad address never spoils the rest of a
854 # request... that is the reason this returns a per entry hash rather than
855 # dieing on the first problem.
856 #
857 # For each entry in turn... it is normalized, and an entry that will not
858 # normalize is recorded as an error and skipped. One already in the ban book is
859 # a refresh, so its expiry is reset, _refresh_heal is given its chance, and
860 # the backend is deliberately not asked to re-add it, as not every backend
861 # takes that gracefully. One with a pending unban retry means the firewall
862 # still carries the rule, so that retry is cancelled and the entry booked
863 # afresh, again without troubling the backend. Anything else is banned via the
864 # backend and booked. Nothing here writes a tablet... the caller checkpoints
865 # once for the whole request.
866 #
867 # Args, all three required and positional...
868 #
869 # $entries :: Array ref of raw entries straight off the request, so
870 # args.ips or args.cidrs as the client sent them. Elements
871 # are whatever arrived and may be undef, refs, or nonsense;
872 # each is put through the family normalizer and a failure
873 # becomes that entry's error rather than a die. An empty array
874 # is legal here and simply produces an empty result, the
875 # callers having already rejected one.
876 # $ban_time :: Effective seconds from _resolve_ban_time. 0 means the bans
877 # never expire, anything else is added to the current time to
878 # get each entry's expiry.
879 # $spec :: One of the %family_spec entries described above. Uses
880 # normalizer, noun, log_label, infix, hash, retry_hash,
881 # retry_checkpoint, ban_method, and ban_stat.
882 #
883 # Returns a hash ref keyed by entry, holding one result per entry of the
884 # request. A good entry is keyed by its canonical form, so the caller sees the
885 # normalized spelling rather than what was sent, and its value is
886 # { status => 'ok' }, or { status => 'ok', refreshed => 1 } when it was
887 # already banned and only had its timer reset. An entry that would not
888 # normalize is keyed by the raw string it arrived as, or by the empty string
889 # when it arrived undef, with a value of
890 # { status => 'error', error => '...' }. A backend refusal is the same error
891 # shape but keyed by the canonical form.
892 #
893 # Does not die. Every failure is a per entry error in the returned hash.
894 #
895 # my $results = $self->_ban_many(
896 # [ '1.2.3.4', 'nonsense' ],
897 # 600,
898 # $family_spec{ip},
899 # );
900 # # $results is {
901 # # '1.2.3.4' => { status => 'ok' },
902 # # 'nonsense' => { status => 'error', error => '"nonsense" does ...' },
903 # # }
904 #
905 # my $results = $self->_ban_many( ['1.2.3.0/24'], 0, $family_spec{cidr} );
906 0 ▶sub _ban_many {
Subroutine _ban_many: not called CC=8 SCAR=42.8
907 0 my ( $self, $entries, $ban_time, $spec ) = @_;
908  
909 0 my $ident = 'kur-' . $self->{name};
910  
911 0 my $results = {};
912 0 foreach my $raw_entry ( @{$entries} ) {
913 # bounced here rather than left for the backend to judge, given the
914 # backend accepts ambiguous stuff like leading zero octet IPv4, and
915 # reduced to the canonical form so variant spellings dedupe
916 0 my $entry = $spec->{normalizer}->($raw_entry);
917 0 ▶ if ( !defined($entry) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $entry) 0 0 0
918 0 ▶ my $key = defined($raw_entry) ? $raw_entry : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $raw_entry ? : 0 0 0
919 0 $self->{stats}{errors}++;
920 $results->{$key} = {
921 'status' => 'error',
922 'error' => '"' . $key . '" does not appear to be an IPv4 or IPv6 ' . $spec->{noun}
923 0 };
924 log_drek(
925 'err',
926 $spec->{log_label} . ' of "'
927 . $key
928 . '" failed... does not appear to be an IPv4 or IPv6 '
929 . $spec->{noun},
930 undef,
931 0 $ident
932 );
933 0 next;
934 } ## end if ( !defined($entry) )
935 0 ▶ my $expires = $ban_time ? time + $ban_time : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ban_time ? : 0 0 0
936  
937 # already banned, so just refresh its timer... the backend ban is
938 # not re-ran, as not every backend takes re-adding an existing entry
939 # gracefully, but self_heal still gets its chance via _refresh_heal
940 0 ▶ if ( defined( $self->{ $spec->{hash} }{$entry} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$self{$spec->{"hash"}}{$entry}) 0 0 0
941 0 $self->_refresh_heal;
942 0 $self->{ $spec->{hash} }{$entry}{expires} = $expires;
943 0 $results->{$entry} = { 'status' => 'ok', 'refreshed' => 1 };
944 0 log_drek( 'info', 'refreshed ' . $spec->{log_label} . ' of ' . $entry . ' expires=' . $expires,
945 undef, $ident );
946 0 next;
947 }
948  
949 # a pending unban retry means the firewall still carries it, so the
950 # backend is not asked to re-add what it already has... the retry is
951 # cancelled and the entry booked fresh
952 0 ▶ if ( defined( $self->{ $spec->{retry_hash} }{$entry} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$self{$spec->{"retry_hash"}}{$entry}) 0 0 0
953 0 delete( $self->{ $spec->{retry_hash} }{$entry} );
954 0 my $retry_checkpoint_method = $spec->{retry_checkpoint};
955 0 $self->$retry_checkpoint_method;
956 0 $self->{stats}{ $spec->{ban_stat} }++;
957 0 $self->{ $spec->{hash} }{$entry} = { 'banned_at' => time, 'expires' => $expires };
958 0 $results->{$entry} = { 'status' => 'ok' };
959 log_drek( 'info',
960 0 'banned ' . $spec->{infix} . $entry . ' expires=' . $expires . ', cancelling pending unban retry',
961 undef, $ident );
962 0 next;
963 } ## end if ( defined( $self->{ $spec->{retry_hash}...}))
964  
965 0 my $ban_method = $spec->{ban_method};
966 0 eval { $self->_backend_do( $ban_method, ban => $entry ); };
967 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
968 0 $self->{stats}{errors}++;
969 0 $results->{$entry} = { 'status' => 'error', 'error' => $@ };
970 0 log_drek( 'err', $spec->{log_label} . ' of "' . $entry . '" failed... ' . $@, undef, $ident );
971 } else {
972 0 $self->{stats}{ $spec->{ban_stat} }++;
973 0 $self->{ $spec->{hash} }{$entry} = { 'banned_at' => time, 'expires' => $expires };
974 0 $results->{$entry} = { 'status' => 'ok' };
975 0 log_drek( 'info', 'banned ' . $spec->{infix} . $entry . ' expires=' . $expires, undef, $ident );
976 }
977 } ## end foreach my $raw_entry ( @{$entries} )
978  
979 0 return $results;
980 } ## end sub _ban_many
981  
982 # The shared body behind both _cmd_unban and _cmd_cidr_unban. It asks the
983 # firewall rather than the book whether the entry is actually there, which is
984 # what lets an unban be fired at every kur in a fan out without the ones that
985 # never held it erroring... they answer was_banned 0 and nothing else happens.
986 #
987 # The backend is listed and each entry it reports is normalized before being
988 # compared, because a firewall may well render an entry differently to how it
989 # was handed over, IPv6 especially, and it is that spelling it wants back to
990 # remove it. When no match is found any stale book entry is dropped and the
991 # tablet rewritten, so a hand removal behind the kur's back still tidies up.
992 # When a match is found the backend is asked to unban it, and on success the
993 # book, the retry book, and both tablets are brought into line.
994 #
995 # Args, both required and positional...
996 #
997 # $entry :: A single entry in canonical form. The caller is expected to
998 # have already put the request argument through the family
999 # normalizer and dealt with a failure, so this is never undef
1000 # and never a raw spelling... the book and the retry book are
1001 # keyed by this form.
1002 # $spec :: One of the %family_spec entries described above. Uses
1003 # normalizer, list_method, unban_method, hash, retry_hash,
1004 # checkpoint, retry_checkpoint, unban_stat, and infix.
1005 #
1006 # Returns 1 when the firewall was carrying the entry and it has now been
1007 # removed, and 0 when it was not carrying it at all. The callers put that
1008 # straight into their was_banned field, so 0 is a perfectly ordinary answer
1009 # and not a failure.
1010 #
1011 # Dies if the backend refuses the unban, rethrowing whatever it said, having
1012 # first counted an error. It also dies if listing the backend fails, that
1013 # being a bare _backend_do call. A caller wanting a failed unban to be
1014 # survivable has to wrap it.
1015 #
1016 # my $was_banned = $self->_unban_one( '1.2.3.4', $family_spec{ip} );
1017 #
1018 # my $was_banned = $self->_unban_one( '1.2.3.0/24', $family_spec{cidr} );
1019 0 ▶sub _unban_one {
Subroutine _unban_one: not called CC=8 SCAR=42.8
1020 0 my ( $self, $entry, $spec ) = @_;
1021  
1022 0 my $checkpoint_method = $spec->{checkpoint};
1023  
1024 # check if it is actually present before trying to unban it... what the
1025 # backend lists back is compared in normalized form, as a firewall may
1026 # well render an entry differently to how it was handed over, IPv6
1027 # especially, and that spelling is what it wants back to remove it
1028 0 my @banned = $self->_backend_do( $spec->{list_method} );
1029 0 my $present;
1030 0 foreach my $banned_entry (@banned) {
1031 0 my $normalized = $spec->{normalizer}->($banned_entry);
1032 0 ▶ if ( ( defined($normalized) ? $normalized : $banned_entry ) eq $entry ) {
Branch: 2 branches
BranchTrueFalseTotal
if ((defined $normalized ? $normalized : $banned_entry) eq $entry) 0 0 0
defined $normalized ? : 0 0 0
1033 0 $present = $banned_entry;
1034 0 last;
1035 }
1036 }
1037 0 ▶ if ( !defined($present) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $present) 0 0 0
1038 # make sure no stale timer is left behind either way
1039 0 ▶ if ( defined( delete( $self->{ $spec->{hash} }{$entry} ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined delete $$self{$spec->{"hash"}}{$entry}) 0 0 0
1040 0 $self->$checkpoint_method;
1041 }
1042 0 return 0;
1043 }
1044  
1045 # unbanned via the spelling the backend book actually carries, which for
1046 # anything banned by this process is the canonical form anyway
1047 0 eval { $self->_backend_do( $spec->{unban_method}, ban => $present ); };
1048 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1049 0 $self->{stats}{errors}++;
1050 0 die($@);
1051 }
1052 0 $self->{stats}{ $spec->{unban_stat} }++;
1053 # the book and the retry list are both keyed by the canonical form, that
1054 # being the only form either ever carries, so the backend's spelling is
1055 # not a key to worry about here... a pending unban retry is now moot
1056 0 delete( $self->{ $spec->{hash} }{$entry} );
1057 0 ▶ if ( defined( delete( $self->{ $spec->{retry_hash} }{$entry} ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined delete $$self{$spec->{"retry_hash"}}{$entry}) 0 0 0
1058 0 my $retry_checkpoint_method = $spec->{retry_checkpoint};
1059 0 $self->$retry_checkpoint_method;
1060 }
1061 0 $self->$checkpoint_method;
1062 0 log_drek( 'info', 'unbanned ' . $spec->{infix} . $entry, undef, 'kur-' . $self->{name} );
1063  
1064 0 return 1;
1065 } ## end sub _unban_one
1066  
1067 # Handles the ban command off the socket, the single IP half of the pair with
1068 # _cmd_cidr_ban. All the real work is _ban_many's... this validates the shape
1069 # of the request, resolves the sentence, and checkpoints once at the end
1070 # rather than once per IP, so a request banning a hundred addresses writes one
1071 # tablet rather than a hundred.
1072 #
1073 # Args, one required...
1074 #
1075 # $request :: The request hash ref as it came off the socket. Only
1076 # $request->{args} is read, and that must be a hash ref
1077 # carrying an ips key holding an array ref of one or more raw
1078 # IPs. Elements are not checked here, _ban_many judging each
1079 # one. args.ban_time is optional and goes to
1080 # _resolve_ban_time.
1081 #
1082 # Returns a hash ref of { ips => $results }, where $results is the per entry
1083 # hash _ban_many built... each key an IP and each value either
1084 # { status => 'ok' }, { status => 'ok', refreshed => 1 }, or
1085 # { status => 'error', error => '...' }. That whole thing becomes the result
1086 # field of the response.
1087 #
1088 # Dies if the kur is stopping, if args is missing, or if args.ips is not a
1089 # array ref of at least one element, and via _resolve_ban_time if
1090 # args.ban_time will not validate. Individual bad IPs do not die.
1091 #
1092 # my $result = $self->_cmd_ban(
1093 # { 'args' => { 'ips' => [ '1.2.3.4', '5.6.7.8' ] } }
1094 # );
1095 # # $result is { ips => { '1.2.3.4' => { status => 'ok' }, ... } }
1096 #
1097 # my $result = $self->_cmd_ban(
1098 # { 'args' => { 'ips' => ['1.2.3.4'], 'ban_time' => 0 } }
1099 # );
1100 0 ▶sub _cmd_ban {
Subroutine _cmd_ban: not called CC=4 SCAR=30.0
1101 0 my ( $self, $request ) = @_;
1102  
1103 0 $self->_refuse_when_stopping;
1104  
1105 0 my $args = $request->{args};
1106 0 ▶ if ( !defined($args) || ref( $args->{ips} ) ne 'ARRAY' || !@{ $args->{ips} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $args or ref $args->{"ips"} ne "ARRAY" or not @{$args->{"ips"};}) 0 0 0
Condition0%0/6
not defined $args or ref $args->{"ips"} ne "ARRAY" or not @{$args->{"ips"};}
l!l&&r!l&&!r
000
not defined $args or ref $args->{"ips"} ne "ARRAY"
l!l&&r!l&&!r
000
MC/DC0%0/3
not defined $args or ref $args->{"ips"} ne "ARRAY" or not @{$args->{"ips"};}
not defined $args ref $args->{"ips"} ne "ARRAY" not @{$args->{"ips"};}
Truth table0%0/4
not(A) or B or not(C)
A= not defined $argsB= ref $args->{"ips"} ne "ARRAY"C= not @{$args->{"ips"};}
ABCresult
1XX1
01X1
0011
0000
1107 0 die('args.ips must be an array of one or more IPs');
1108 }
1109  
1110 0 my $results = $self->_ban_many( $args->{ips}, $self->_resolve_ban_time($args), $family_spec{ip} );
1111  
1112 0 $self->_checkpoint;
1113  
1114 0 return { 'ips' => $results };
1115 } ## end sub _cmd_ban
1116  
1117 # Handles the unban command off the socket, the single IP half of the pair
1118 # with _cmd_cidr_unban. Unlike ban it takes exactly one address, and unlike
1119 # ban a bad one is fatal to the whole request rather than a per entry error...
1120 # there being only the one entry, there is nothing to salvage.
1121 #
1122 # Args, one required...
1123 #
1124 # $request :: The request hash ref as it came off the socket. Only
1125 # $request->{args} is read, and that must be a hash ref
1126 # carrying an ip key holding a single raw IP as a plain scalar.
1127 # An array ref is refused rather than treated as a list of one.
1128 # There is deliberately no kur argument here... the manager
1129 # fans unban at every kur it has.
1130 #
1131 # Returns a hash ref of { ip => $canonical, was_banned => 0 or 1 }. The ip
1132 # field is the canonical form rather than what was sent, so a client that
1133 # asked in a variant IPv6 spelling can see what was actually acted on, and
1134 # was_banned says whether the firewall was carrying it... 0 is a normal
1135 # answer meaning it was not.
1136 #
1137 # Dies if the kur is stopping, if args is missing, if args.ip is missing or a
1138 # ref, or if it will not normalize, and via _unban_one if the backend refuses
1139 # the unban.
1140 #
1141 # my $result = $self->_cmd_unban( { 'args' => { 'ip' => '1.2.3.4' } } );
1142 # # $result is { ip => '1.2.3.4', was_banned => 1 }
1143 #
1144 # my $result = $self->_cmd_unban(
1145 # { 'args' => { 'ip' => '2001:0DB8::1' } }
1146 # );
1147 # # $result is { ip => '2001:db8::1', was_banned => 0 }
1148 0 ▶sub _cmd_unban {
Subroutine _cmd_unban: not called CC=5 SCAR=34.0
1149 0 my ( $self, $request ) = @_;
1150  
1151 0 $self->_refuse_when_stopping;
1152  
1153 0 my $args = $request->{args};
1154 0 ▶ if ( !defined($args) || !defined( $args->{ip} ) || ref( $args->{ip} ) ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $args && defined $args->{"ip"} or ref $args->{"ip"} ne "") 0 0 0
Condition0%0/6
not defined $args && defined $args->{"ip"} or ref $args->{"ip"} ne ""
l!l&&r!l&&!r
000
defined $args && defined $args->{'ip'}
!ll&&!rl&&r
000
MC/DC0%0/3
not defined $args && defined $args->{"ip"} or ref $args->{"ip"} ne ""
defined $args defined $args->{'ip'} ref $args->{"ip"} ne ""
Truth table0%0/4
not(A && B) or C
A= defined $argsB= defined $args->{'ip'}C= ref $args->{"ip"} ne ""
ABCresult
0XX1
10X1
1111
1100
1155 0 die('args.ip must be an IP');
1156 }
1157 0 my $ip = normalize_ip( $args->{ip} );
1158 0 ▶ if ( !defined($ip) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ip) 0 0 0
1159 0 die( 'args.ip, "' . $args->{ip} . '", does not appear to be an IPv4 or IPv6 IP' );
1160 }
1161  
1162 0 return { 'ip' => $ip, 'was_banned' => $self->_unban_one( $ip, $family_spec{ip} ) };
1163 } ## end sub _cmd_unban
1164  
1165 # Works out whether the backend this kur is wrapping can carry whole ranges,
1166 # by reaching through the Net::Firewall::BlockerHelper frontend to the actual
1167 # backend object underneath it and reading the cidr_supported flag there.
1168 # That is the same flag the frontend itself gates ban_cidr on, so asking it
1169 # directly keeps this kur's answer and the frontend's refusal in step. It is
1170 # called once at init, the answer cached in $self->{cidr_supported}, so the
1171 # reaching through happens the once rather than per command.
1172 #
1173 # Reaching two levels into another distribution's internals is why every step
1174 # is guarded... a frontend that is undef, not blessed, or has no backend
1175 # object yet is treated as no support rather than being allowed to die,
1176 # because this runs during init where a die would take the whole kur down over
1177 # a question that has a perfectly good conservative answer.
1178 #
1179 # Takes no arguments beyond the invocant, reading $self->{backend_obj}.
1180 #
1181 # Returns 1 when the backend claims CIDR support and 0 otherwise, including
1182 # every case where the answer could not be reached at all. Never undef, so it
1183 # is safe to store and test directly.
1184 #
1185 # Does not die.
1186 #
1187 # $self->{cidr_supported} = $self->_backend_cidr_supported;
1188 0 ▶sub _backend_cidr_supported {
Subroutine _backend_cidr_supported: not called CC=6 SCAR=37.4
1189 0 my ($self) = @_;
1190  
1191 0 my $frontend = $self->{backend_obj};
1192 0 ▶ if ( !defined($frontend) || ref($frontend) eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $frontend or ref $frontend eq "") 0 0 0
Condition0%0/3
not defined $frontend or ref $frontend eq ""
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $frontend or ref $frontend eq ""
not defined $frontend ref $frontend eq ""
Truth table0%0/3
not(A) or B
A= not defined $frontendB= ref $frontend eq ""
ABresult
1X1
011
000
1193 0 return 0;
1194 }
1195 0 my $backend = $frontend->{backend_obj};
1196 0 ▶ if ( !defined($backend) || ref($backend) eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $backend or ref $backend eq "") 0 0 0
Condition0%0/3
not defined $backend or ref $backend eq ""
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $backend or ref $backend eq ""
not defined $backend ref $backend eq ""
Truth table0%0/3
not(A) or B
A= not defined $backendB= ref $backend eq ""
ABresult
1X1
011
000
1197 0 return 0;
1198 }
1199  
1200 0 ▶ return $backend->{cidr_supported} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$backend->{'cidr_supported'} ? : 0 0 0
1201 } ## end sub _backend_cidr_supported
1202  
1203 # Whether this instance will actually act on a CIDR command, which needs both
1204 # halves... the operator has to have opted in via enable_cidr, and the backend
1205 # has to be able to carry ranges at all. Either alone is not enough, which is
1206 # why this exists rather than the callers testing enable_cidr and assuming.
1207 #
1208 # Takes no arguments beyond the invocant, reading $self->{enable_cidr}, which
1209 # new folded to a plain 1 or 0, and $self->{cidr_supported}, which init
1210 # cached from _backend_cidr_supported.
1211 #
1212 # Returns 1 when ranges may be acted on and 0 otherwise. It does not say which
1213 # half was missing... _cidr_guard works that out for the error message.
1214 #
1215 # Does not die.
1216 #
1217 # if ( !$self->_cidr_available ) {
1218 # # skip loading the CIDR tablet entirely
1219 # return;
1220 # }
1221 0 ▶sub _cidr_available {
Subroutine _cidr_available: not called CC=3 SCAR=24.8
1222 0 my ($self) = @_;
1223  
1224 0 ▶ return ( $self->{enable_cidr} && $self->{cidr_supported} ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'enable_cidr'} && $self->{'cidr_supported'} ? : 0 0 0
Condition0%0/3
$self->{"enable_cidr"} and $self->{"cidr_supported"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"enable_cidr"} and $self->{"cidr_supported"}
$self->{"enable_cidr"} $self->{"cidr_supported"}
Truth table0%0/3
A and B
A= $self->{"enable_cidr"}B= $self->{"cidr_supported"}
ABresult
0X0
100
111
1225 }
1226  
1227 # The gate both CIDR command handlers pass through before doing anything
1228 # else, deciding what a kur that cannot oblige should do about it. There are
1229 # three answers rather than two because of fan outs... a gate spanning range
1230 # capable and range incapable kurs would have every cidr-ban soured by the
1231 # incapable ones if their only option were an error, so cidr_silent_drop lets
1232 # those quietly report the command as dropped and leave the response clean.
1233 #
1234 # It runs before the handlers validate their payload, deliberately, so a kur
1235 # that was never going to act short circuits regardless of whether the
1236 # request was well formed.
1237 #
1238 # Takes no arguments beyond the invocant, reading _cidr_available,
1239 # $self->{enable_cidr}, $self->{cidr_silent_drop}, and $self->{backend} for
1240 # the message.
1241 #
1242 # Returns undef when CIDR is available, which the callers read as carry on.
1243 # When it is not available and cidr_silent_drop is set it returns a hash ref
1244 # of { dropped => 1, reason => '...' }, which the callers return to the client
1245 # unchanged as the whole result... reason names which half was missing, either
1246 # that CIDR bans are not enabled for the kur or that the named backend does
1247 # not support them.
1248 #
1249 # Dies with that same reason string, no trailing newline, when CIDR is
1250 # unavailable and cidr_silent_drop is not set.
1251 #
1252 # my $drop = $self->_cidr_guard;
1253 # if ( defined($drop) ) {
1254 # return $drop;
1255 # }
1256 # # reached only when this kur really will act on ranges
1257 0 ▶sub _cidr_guard {
Subroutine _cidr_guard: not called CC=4 SCAR=30.0
1258 0 my ($self) = @_;
1259  
1260 0 ▶ if ( $self->_cidr_available ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_cidr_available) 0 0 0
1261 0 return undef;
1262 }
1263  
1264 0 my $reason;
1265 0 ▶ if ( !$self->{enable_cidr} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{'enable_cidr'}) { } 0 0 0
1266 0 $reason = 'CIDR bans are not enabled for this kur';
1267 } else {
1268 0 $reason = 'the "' . $self->{backend} . '" backend does not support CIDR bans';
1269 }
1270  
1271 0 ▶ if ( $self->{cidr_silent_drop} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cidr_silent_drop"}) 0 0 0
1272 0 log_drek( 'info', 'dropping CIDR command... ' . $reason, undef, 'kur-' . $self->{name} );
1273 0 return { 'dropped' => 1, 'reason' => $reason };
1274 }
1275  
1276 0 die($reason);
1277 } ## end sub _cidr_guard
1278  
1279 # Handles the cidr_ban command off the socket, the range twin of _cmd_ban and
1280 # identical to it beyond the family knobs and the guard. _cidr_guard gets
1281 # first say, so a kur that will not act on ranges answers before the payload
1282 # is even looked at.
1283 #
1284 # Args, one required...
1285 #
1286 # $request :: The request hash ref as it came off the socket. A missing
1287 # args is tolerated as far as the guard, becoming an empty hash
1288 # so a dropping kur can answer cleanly rather than dieing over
1289 # a payload it was never going to read. Past the guard,
1290 # args.cidrs must be an array ref of one or more raw ranges,
1291 # elements unchecked here as _ban_many judges each. Host bits
1292 # are masked off by the normalizer, so 1.2.3.4/24 and
1293 # 1.2.3.0/24 are one range. args.ban_time is optional.
1294 #
1295 # Returns a hash ref of { cidrs => $results } with the same per entry shape
1296 # _cmd_ban returns, keyed by canonical range. When the guard dropped the
1297 # command it instead returns that guard's { dropped => 1, reason => '...' },
1298 # so a caller has to be ready for either shape.
1299 #
1300 # Dies if the kur is stopping, if the guard refuses rather than drops, if
1301 # args.cidrs is not an array ref of at least one element, or via
1302 # _resolve_ban_time on a bad ban_time.
1303 #
1304 # my $result = $self->_cmd_cidr_ban(
1305 # { 'args' => { 'cidrs' => ['1.2.3.0/24'] } }
1306 # );
1307 # # $result is { cidrs => { '1.2.3.0/24' => { status => 'ok' } } }
1308 #
1309 # # on a kur with CIDR off and cidr_silent_drop set
1310 # # $result is { dropped => 1, reason => 'CIDR bans are not enabled ...' }
1311 0 ▶sub _cmd_cidr_ban {
Subroutine _cmd_cidr_ban: not called CC=5 SCAR=34.0
1312 0 my ( $self, $request ) = @_;
1313  
1314 0 $self->_refuse_when_stopping;
1315  
1316 0 my $args = $request->{args};
1317 0 ▶ if ( !defined($args) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $args) 0 0 0
1318 0 $args = {};
1319 }
1320  
1321 # the guard comes first so a dropping or incapable instance short circuits
1322 # regardless of the payload... a capable one falls through and validates
1323 0 my $drop = $self->_cidr_guard;
1324 0 ▶ if ( defined($drop) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $drop) 0 0 0
1325 0 return $drop;
1326 }
1327  
1328 0 ▶ if ( ref( $args->{cidrs} ) ne 'ARRAY' || !@{ $args->{cidrs} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args->{"cidrs"} ne "ARRAY" or not @{$args->{"cidrs"};}) 0 0 0
Condition0%0/3
ref $args->{"cidrs"} ne "ARRAY" or not @{$args->{"cidrs"};}
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $args->{"cidrs"} ne "ARRAY" or not @{$args->{"cidrs"};}
ref $args->{"cidrs"} ne "ARRAY" not @{$args->{"cidrs"};}
Truth table0%0/3
A or not(B)
A= ref $args->{"cidrs"} ne "ARRAY"B= not @{$args->{"cidrs"};}
ABresult
1X1
011
000
1329 0 die('args.cidrs must be an array of one or more CIDRs');
1330 }
1331  
1332 0 my $results = $self->_ban_many( $args->{cidrs}, $self->_resolve_ban_time($args), $family_spec{cidr} );
1333  
1334 0 $self->_checkpoint_cidr;
1335  
1336 0 return { 'cidrs' => $results };
1337 } ## end sub _cmd_cidr_ban
1338  
1339 # Handles the cidr_unban command off the socket, the range twin of
1340 # _cmd_unban. _cidr_guard gets first say the same way it does for cidr_ban.
1341 #
1342 # Args, one required...
1343 #
1344 # $request :: The request hash ref as it came off the socket. A missing
1345 # args is tolerated as far as the guard, for the same reason
1346 # it is in _cmd_cidr_ban. Past the guard, args.cidr must be a
1347 # single raw range as a plain scalar; a ref is refused. Host
1348 # bits are masked off, so naming any address inside a banned
1349 # network finds it.
1350 #
1351 # Returns a hash ref of { cidr => $canonical, was_banned => 0 or 1 }, the cidr
1352 # field being the masked canonical form rather than what was sent. When the
1353 # guard dropped the command it instead returns that guard's
1354 # { dropped => 1, reason => '...' }.
1355 #
1356 # Dies if the kur is stopping, if the guard refuses rather than drops, if
1357 # args.cidr is missing or a ref, if it will not normalize, or via _unban_one
1358 # if the backend refuses the unban.
1359 #
1360 # my $result = $self->_cmd_cidr_unban(
1361 # { 'args' => { 'cidr' => '1.2.3.4/24' } }
1362 # );
1363 # # $result is { cidr => '1.2.3.0/24', was_banned => 1 }
1364 0 ▶sub _cmd_cidr_unban {
Subroutine _cmd_cidr_unban: not called CC=6 SCAR=37.4
1365 0 my ( $self, $request ) = @_;
1366  
1367 0 $self->_refuse_when_stopping;
1368  
1369 0 my $args = $request->{args};
1370 0 ▶ if ( !defined($args) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $args) 0 0 0
1371 0 $args = {};
1372 }
1373  
1374 0 my $drop = $self->_cidr_guard;
1375 0 ▶ if ( defined($drop) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $drop) 0 0 0
1376 0 return $drop;
1377 }
1378  
1379 0 ▶ if ( !defined( $args->{cidr} ) || ref( $args->{cidr} ) ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $args->{"cidr"} or ref $args->{"cidr"} ne "") 0 0 0
Condition0%0/3
not defined $args->{"cidr"} or ref $args->{"cidr"} ne ""
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $args->{"cidr"} or ref $args->{"cidr"} ne ""
not defined $args->{"cidr"} ref $args->{"cidr"} ne ""
Truth table0%0/3
not(A) or B
A= not defined $args->{"cidr"}B= ref $args->{"cidr"} ne ""
ABresult
1X1
011
000
1380 0 die('args.cidr must be a CIDR');
1381 }
1382 0 my $cidr = normalize_cidr( $args->{cidr} );
1383 0 ▶ if ( !defined($cidr) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cidr) 0 0 0
1384 0 die( 'args.cidr, "' . $args->{cidr} . '", does not appear to be an IPv4 or IPv6 CIDR' );
1385 }
1386  
1387 0 return { 'cidr' => $cidr, 'was_banned' => $self->_unban_one( $cidr, $family_spec{cidr} ) };
1388 } ## end sub _cmd_cidr_unban
1389  
1390 # Handles the banned command off the socket, the detail view of who this kur
1391 # is holding. The lists come from the firewall itself rather than the ban
1392 # books, so what is reported is what is really in place... the books only
1393 # supply the expiry times, which the firewall has no notion of.
1394 #
1395 # One consequence worth knowing: an entry whose unban failed at expiry has left
1396 # the ban book but not the firewall, so it appears in banned and in
1397 # unban_retries at once. That is not an inconsistency, it is the whole point of
1398 # the retry books.
1399 #
1400 # Takes no arguments beyond the invocant. Deliberately not gated on
1401 # _refuse_when_stopping, being read only, nor on _cidr_available, as
1402 # list_cidr is safe on every backend and simply comes back empty on the ones
1403 # that do not do ranges.
1404 #
1405 # Returns a hash ref carrying six keys...
1406 #
1407 # banned :: Array ref of the single IPs the firewall is
1408 # carrying, in whatever spelling it reports them.
1409 # expires :: Hash ref of canonical IP to the epoch its sentence
1410 # ends, 0 meaning never. Keyed off the ban book, so
1411 # a firewall entry the book does not know about has
1412 # no key here.
1413 # banned_cidr :: Array ref of the ranges the firewall is carrying.
1414 # cidr_expires :: The range equivalent of expires.
1415 # unban_retries :: Hash ref from _retry_details for the IP family,
1416 # each key an entry still owed to the firewall.
1417 # cidr_unban_retries :: The range equivalent.
1418 #
1419 # Dies only if listing the backend fails, that being a bare _backend_do call.
1420 #
1421 # my $result = $self->_cmd_banned;
1422 # # $result is {
1423 # # banned => ['1.2.3.4'], expires => { '1.2.3.4' => 1785919052 },
1424 # # banned_cidr => [], cidr_expires => {},
1425 # # unban_retries => {}, cidr_unban_retries => {},
1426 # # }
1427 0 ▶sub _cmd_banned {
Subroutine _cmd_banned: not called CC=3 SCAR=24.8
1428 0 my ($self) = @_;
1429  
1430 0 my @banned = $self->_backend_do('list');
1431  
1432 0 my $expires = {};
1433 0 foreach my $ip ( keys( %{ $self->{bans} } ) ) {
1434 0 $expires->{$ip} = $self->{bans}{$ip}{expires};
1435 }
1436  
1437 # list_cidr is safe on every backend, returning empty on the ones that do
1438 # not do CIDR, so there is no need to gate this on _cidr_available
1439 0 my @banned_cidr = $self->_backend_do('list_cidr');
1440  
1441 0 my $cidr_expires = {};
1442 0 foreach my $cidr ( keys( %{ $self->{cidr_bans} } ) ) {
1443 0 $cidr_expires->{$cidr} = $self->{cidr_bans}{$cidr}{expires};
1444 }
1445  
1446 return {
1447 'banned' => \@banned,
1448 'expires' => $expires,
1449 'banned_cidr' => \@banned_cidr,
1450 'cidr_expires' => $cidr_expires,
1451 'unban_retries' => $self->_retry_details( $family_spec{ip} ),
1452 0 'cidr_unban_retries' => $self->_retry_details( $family_spec{cidr} ),
1453 };
1454 } ## end sub _cmd_banned
1455  
1456 # Flattens one family's retry book into the shape the banned command reports,
1457 # a plain hash of entry to its counts and times. It exists so the wire format
1458 # is decided in one place rather than in the command handler, and so the
1459 # delay field stays internal... that is the backoff's own book keeping and
1460 # means nothing to a client, next_try already saying when the entry is due.
1461 #
1462 # These are unbans still owed to the firewall, deliberately reported
1463 # separately rather than folded into the banned lists, which are what the
1464 # firewall is carrying on this kur's behalf.
1465 #
1466 # Args, one required...
1467 #
1468 # $spec :: One of the %family_spec entries described above. Uses only
1469 # retry_hash.
1470 #
1471 # Returns a hash ref keyed by canonical entry, empty when nothing is owed.
1472 # Each value is a hash ref of...
1473 #
1474 # first_tried :: Epoch the unban first failed, so the age of the debt.
1475 # last_tried :: Epoch of the most recent attempt.
1476 # times_tried :: How many attempts have been made, counting the one at
1477 # expiry, so it is at least 1.
1478 # next_try :: Epoch the next attempt is due. A value in the past means
1479 # it is due at the next sweep.
1480 #
1481 # Does not die.
1482 #
1483 # my $owed = $self->_retry_details( $family_spec{ip} );
1484 # # $owed is {
1485 # # '1.2.3.4' => {
1486 # # first_tried => 1785918152, last_tried => 1785919052,
1487 # # times_tried => 9, next_try => 1785919112,
1488 # # },
1489 # # }
1490 0 ▶sub _retry_details {
Subroutine _retry_details: not called CC=2 SCAR=17.9
1491 0 my ( $self, $spec ) = @_;
1492  
1493 0 my $details = {};
1494 0 foreach my $entry ( keys( %{ $self->{ $spec->{retry_hash} } } ) ) {
1495 0 my $retry = $self->{ $spec->{retry_hash} }{$entry};
1496 $details->{$entry} = {
1497 'first_tried' => $retry->{first_tried},
1498 'last_tried' => $retry->{last_tried},
1499 'times_tried' => $retry->{times_tried},
1500 'next_try' => $retry->{next_try},
1501 0 };
1502 }
1503  
1504 0 return $details;
1505 } ## end sub _retry_details
1506  
1507 # Finds the first_tried of the longest owed retry in one family, which is the
1508 # single number that tells an operator whether the backend is having a brief
1509 # moment or has been refusing since last week. status reports it so that
1510 # question can be answered without pulling the whole per entry list out of
1511 # banned.
1512 #
1513 # Args, one required...
1514 #
1515 # $spec :: One of the %family_spec entries described above. Uses only
1516 # retry_hash.
1517 #
1518 # Returns the epoch of the oldest first_tried across that family's retry
1519 # book, as an integer, or 0 when nothing is owed. 0 is unambiguous here since a
1520 # real first_tried is an epoch, so a caller can test it as a boolean for
1521 # anything owed at all.
1522 #
1523 # Does not die.
1524 #
1525 # my $oldest = $self->_retries_oldest( $family_spec{ip} );
1526 # # 0 with a clean book, or something like 1785918152 with a debt
1527 # # first taken on at that time
1528 0 ▶sub _retries_oldest {
Subroutine _retries_oldest: not called CC=4 SCAR=30.0
1529 0 my ( $self, $spec ) = @_;
1530  
1531 0 my $oldest = 0;
1532 0 foreach my $entry ( keys( %{ $self->{ $spec->{retry_hash} } } ) ) {
1533 0 my $first_tried = $self->{ $spec->{retry_hash} }{$entry}{first_tried};
1534 0 ▶ if ( !$oldest || $first_tried < $oldest ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $oldest or $first_tried < $oldest) 0 0 0
Condition0%0/3
not $oldest or $first_tried < $oldest
l!l&&r!l&&!r
000
MC/DC0%0/2
not $oldest or $first_tried < $oldest
not $oldest $first_tried < $oldest
Truth table0%0/3
not(A) or B
A= not $oldestB= $first_tried < $oldest
ABresult
1X1
011
000
1535 0 $oldest = $first_tried;
1536 }
1537 }
1538  
1539 0 return $oldest;
1540 } ## end sub _retries_oldest
1541  
1542 # Handles the status command off the socket, the summary view of this kur...
1543 # how it is configured, what it has been doing, and how much it is holding.
1544 # The counts come from the firewall while the timed versus permanent split
1545 # comes from the ban books, since only the books know about sentences.
1546 #
1547 # Takes no arguments beyond the invocant. Read only, so deliberately not
1548 # gated on _refuse_when_stopping.
1549 #
1550 # Returns a hash ref carrying the instance settings as given, name, backend,
1551 # ports, protocols, prefix, ban_time and checkpoint, along with...
1552 #
1553 # last_checkpoint :: Epoch of the last successful ban tablet
1554 # write, 0 if there has not been one.
1555 # pid :: This kur process's PID.
1556 # uptime :: Seconds since the server came up.
1557 # stats :: The live stats hash ref, counting bans,
1558 # unbans, cidr_bans, cidr_unbans, errors,
1559 # expired, and cidr_expired.
1560 # banned_count :: How many single IPs the firewall carries.
1561 # bans_timed :: How many of the booked IP bans expire.
1562 # bans_permanent :: How many never do.
1563 # next_expiry :: Soonest epoch any sentence ends, across
1564 # BOTH families, 0 when everything is
1565 # permanent or nothing is banned.
1566 # cidr_enabled :: Whether the operator opted in to ranges.
1567 # cidr_supported :: Whether the backend can carry them.
1568 # cidr_banned_count :: How many ranges the firewall carries.
1569 # cidr_bans_timed :: How many booked range bans expire.
1570 # cidr_bans_permanent :: How many never do.
1571 # unban_retries :: How many unbans are still owed to the
1572 # firewall on the IP side.
1573 # unban_retries_oldest :: first_tried of the longest owed of those,
1574 # 0 when none, from _retries_oldest.
1575 # cidr_unban_retries :: The range equivalent of unban_retries.
1576 # cidr_unban_retries_oldest :: The range equivalent of the above.
1577 #
1578 # Dies only if listing the backend fails, that being a bare _backend_do call.
1579 #
1580 # my $status = $self->_cmd_status;
1581 # # $status->{banned_count} is 3, $status->{unban_retries} is 0, ...
1582 0 ▶sub _cmd_status {
Subroutine _cmd_status: not called CC=9 SCAR=45.0
1583 0 my ($self) = @_;
1584  
1585 0 my @banned = $self->_backend_do('list');
1586  
1587 0 my $timed = 0;
1588 0 my $permanent = 0;
1589 0 my $next_expiry = 0;
1590 0 foreach my $ip ( keys( %{ $self->{bans} } ) ) {
1591 0 ▶ if ( $self->{bans}{$ip}{expires} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'bans'}{$ip}{'expires'}) { } 0 0 0
1592 0 $timed++;
1593 0 ▶ if ( !$next_expiry || $self->{bans}{$ip}{expires} < $next_expiry ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $next_expiry or $self->{"bans"}{$ip}{"expires"} < $next_expiry) 0 0 0
Condition0%0/3
not $next_expiry or $self->{"bans"}{$ip}{"expires"} < $next_expiry
l!l&&r!l&&!r
000
MC/DC0%0/2
not $next_expiry or $self->{"bans"}{$ip}{"expires"} < $next_expiry
not $next_expiry $self->{"bans"}{$ip}{"expires"} < $next_expiry
Truth table0%0/3
not(A) or B
A= not $next_expiryB= $self->{"bans"}{$ip}{"expires"} < $next_expiry
ABresult
1X1
011
000
1594 0 $next_expiry = $self->{bans}{$ip}{expires};
1595 }
1596 } else {
1597 0 $permanent++;
1598 }
1599 } ## end foreach my $ip ( keys( %{ $self->{bans} } ) )
1600  
1601 0 my @banned_cidr = $self->_backend_do('list_cidr');
1602 0 my $cidr_timed = 0;
1603 0 my $cidr_permanent = 0;
1604 0 foreach my $cidr ( keys( %{ $self->{cidr_bans} } ) ) {
1605 0 ▶ if ( $self->{cidr_bans}{$cidr}{expires} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'cidr_bans'}{$cidr}{'expires'}) { } 0 0 0
1606 0 $cidr_timed++;
1607 0 ▶ if ( !$next_expiry || $self->{cidr_bans}{$cidr}{expires} < $next_expiry ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $next_expiry or $self->{"cidr_bans"}{$cidr}{"expires"} < $next_expiry) 0 0 0
Condition0%0/3
not $next_expiry or $self->{"cidr_bans"}{$cidr}{"expires"} < $next_expiry
l!l&&r!l&&!r
000
MC/DC0%0/2
not $next_expiry or $self->{"cidr_bans"}{$cidr}{"expires"} < $next_expiry
not $next_expiry $self->{"cidr_bans"}{$cidr}{"expires"} < $next_expiry
Truth table0%0/3
not(A) or B
A= not $next_expiryB= $self->{"cidr_bans"}{$cidr}{"expires"} < $next_expiry
ABresult
1X1
011
000
1608 0 $next_expiry = $self->{cidr_bans}{$cidr}{expires};
1609 }
1610 } else {
1611 0 $cidr_permanent++;
1612 }
1613 } ## end foreach my $cidr ( keys( %{ $self->{cidr_bans} ...}))
1614  
1615 return {
1616 'name' => $self->{name},
1617 'backend' => $self->{backend},
1618 'ports' => $self->{ports},
1619 'protocols' => $self->{protocols},
1620 'prefix' => $self->{prefix},
1621 'ban_time' => $self->{ban_time},
1622 'checkpoint' => $self->{checkpoint},
1623 'last_checkpoint' => $self->{last_checkpoint},
1624 'pid' => $$,
1625 'uptime' => time - $self->{started},
1626 'stats' => $self->{stats},
1627 'banned_count' => scalar(@banned),
1628 'bans_timed' => $timed,
1629 'bans_permanent' => $permanent,
1630 'next_expiry' => $next_expiry,
1631 'cidr_enabled' => $self->{enable_cidr},
1632 'cidr_supported' => $self->{cidr_supported},
1633 'cidr_banned_count' => scalar(@banned_cidr),
1634 'cidr_bans_timed' => $cidr_timed,
1635 'cidr_bans_permanent' => $cidr_permanent,
1636 # unbans that failed at expiry and are still owed to the firewall...
1637 # oldest is the first_tried of the longest owed, so an operator can
1638 # tell a blip from something wedged without asking for banned
1639 0 'unban_retries' => scalar( keys( %{ $self->{unban_retries} } ) ),
1640 'unban_retries_oldest' => $self->_retries_oldest( $family_spec{ip} ),
1641 0 'cidr_unban_retries' => scalar( keys( %{ $self->{cidr_unban_retries} } ) ),
1642 0 'cidr_unban_retries_oldest' => $self->_retries_oldest( $family_spec{cidr} ),
1643 };
1644 } ## end sub _cmd_status
1645  
1646 # Handles the flush command off the socket, emptying this kur entirely. The
1647 # manager drives it from unban --all, which is the only way a client reaches
1648 # it... there is no flush subcommand of its own.
1649 #
1650 # The backend's flush clears both single IP and range rules in one go, so
1651 # both ban books are emptied alongside it rather than being unbanned one at a
1652 # time. Both retry books go too... a debt is a rule the firewall was still
1653 # carrying, and flush has just removed every rule this kur owns, so nothing
1654 # is owed any more. All four tablets are then rewritten, which is what stops a
1655 # restart bringing any of it back.
1656 #
1657 # Takes no arguments beyond the invocant.
1658 #
1659 # Returns a hash ref of { flushed => 1 }. There is no count... the backend's
1660 # flush does not report one, and the book sizes before the wipe would not
1661 # necessarily match what the firewall actually removed.
1662 #
1663 # Dies if the kur is stopping, or if the backend refuses the flush, in which
1664 # case nothing is emptied... the books and tablets are only touched after the
1665 # backend has agreed.
1666 #
1667 # my $result = $self->_cmd_flush;
1668 # # $result is { flushed => 1 } and this kur now holds nothing
1669 0 ▶sub _cmd_flush {
Subroutine _cmd_flush: not called CC=1 SCAR=6.9
1670 0 my ($self) = @_;
1671  
1672 0 $self->_refuse_when_stopping;
1673  
1674 # the backend flush clears both single IP and CIDR rules, so the CIDR
1675 # tracking is cleared and checkpointed alongside the single IP tracking,
1676 # and pending unban retries are moot
1677 0 $self->_backend_do('flush');
1678 0 $self->{bans} = {};
1679 0 $self->{cidr_bans} = {};
1680 0 $self->{unban_retries} = {};
1681 0 $self->{cidr_unban_retries} = {};
1682 0 $self->_checkpoint;
1683 0 $self->_checkpoint_cidr;
1684 0 $self->_checkpoint_retries;
1685 0 $self->_checkpoint_cidr_retries;
1686 0 log_drek( 'info', 'flushed all bans', undef, 'kur-' . $self->{name} );
1687  
1688 0 return { 'flushed' => 1 };
1689 } ## end sub _cmd_flush
1690  
1691 # Handles the re_init command off the socket, the repair for a firewall setup
1692 # something outside Ereshkigal has interfered with... a shorewall restart, a
1693 # pf -F all, a firewalld reload, a hand flushed ipset. The backend tears its
1694 # table, set, chain or list down and builds it again, then re-bans everything
1695 # the ban books carry, so the books are the authority and the firewall is
1696 # brought back into line with them.
1697 #
1698 # Bans are not enforced for the moment the rebuild takes, which is brief but
1699 # real, and is the reason this is a command rather than something done
1700 # routinely.
1701 #
1702 # Both retry books are emptied afterwards and their tablets rewritten,
1703 # because tearing the setup down takes any rule a failed unban left orphaned
1704 # in it... those debts have just been settled by the teardown itself. Only the
1705 # books are re-banned, so nothing that was owed comes back.
1706 #
1707 # Takes no arguments beyond the invocant.
1708 #
1709 # Returns a hash ref of { re_init => 1 }.
1710 #
1711 # Dies if the kur is stopping, or if the backend's re_init fails, in which
1712 # case the retry books are left alone... a failed rebuild may well have left
1713 # the orphaned rules exactly where they were.
1714 #
1715 # my $result = $self->_cmd_re_init;
1716 # # $result is { re_init => 1 } and the firewall matches the books again
1717 0 ▶sub _cmd_re_init {
Subroutine _cmd_re_init: not called CC=1 SCAR=6.9
1718 0 my ($self) = @_;
1719  
1720 0 $self->_refuse_when_stopping;
1721  
1722 # re_init tears down and re-bans only what the book carries, so anything
1723 # pending an unban retry is no longer in the firewall
1724 0 $self->_backend_do('re_init');
1725 0 $self->{unban_retries} = {};
1726 0 $self->{cidr_unban_retries} = {};
1727 0 $self->_checkpoint_retries;
1728 0 $self->_checkpoint_cidr_retries;
1729 0 log_drek( 'info', 're_init done', undef, 'kur-' . $self->{name} );
1730  
1731 0 return { 're_init' => 1 };
1732 } ## end sub _cmd_re_init
1733  
1734 # Handles the clear_retries command off the socket, forgetting unbans still
1735 # owed to the firewall. This is the escape hatch for a debt that will never be
1736 # paid, the rule having been removed by hand or the entry having never
1737 # existed as far as the backend is concerned, which would otherwise be
1738 # retried at the 60 second cap forever.
1739 #
1740 # Forgetting a debt does not touch the firewall at all... it only stops this
1741 # kur asking. Anything genuinely still in place stays in place, with nothing
1742 # tracking it, which is why the documentation points people at unban or
1743 # re_init first.
1744 #
1745 # Both families are walked. Naming an entry of one family leaves the other
1746 # entirely alone, rather than clearing it wholesale, which is what the
1747 # other_family_named check is for... without it, naming an ip would empty the
1748 # whole CIDR book as a side effect.
1749 #
1750 # Args, one required...
1751 #
1752 # $request :: The request hash ref as it came off the socket. A missing
1753 # args is fine and means clear everything. args.ip and
1754 # args.cidr are both optional, at most one may be given, and
1755 # each must be a plain scalar naming a single entry of that
1756 # family. Either is normalized before the lookup, since the
1757 # retry books are keyed canonically, so naming a variant
1758 # spelling still finds the debt. Neither given means every
1759 # debt in both families goes.
1760 #
1761 # Returns a hash ref of...
1762 #
1763 # cleared :: Total entries forgotten across both families.
1764 # cleared_ip :: How many on the single IP side... 1 or 0 when an ip was
1765 # named, otherwise however many the book held.
1766 # cleared_cidr :: The range equivalent.
1767 #
1768 # All three are 0 when nothing was owed, which is not an error... clearing a
1769 # entry that is not owed is a no-op rather than a failure.
1770 #
1771 # Dies if both args.ip and args.cidr are given, if a named entry is a ref, or
1772 # if a named entry will not normalize. Deliberately not gated on
1773 # _refuse_when_stopping, as it touches only book keeping.
1774 #
1775 # my $result = $self->_cmd_clear_retries( {} );
1776 # # $result is { cleared => 3, cleared_ip => 2, cleared_cidr => 1 }
1777 #
1778 # my $result = $self->_cmd_clear_retries(
1779 # { 'args' => { 'ip' => '1.2.3.4' } }
1780 # );
1781 # # $result is { cleared => 1, cleared_ip => 1, cleared_cidr => 0 }
1782 0 ▶sub _cmd_clear_retries {
Subroutine _cmd_clear_retries: not called CC=12 SCAR=50.5
1783 0 my ( $self, $request ) = @_;
1784  
1785 0 ▶ my $args = defined( $request->{args} ) ? $request->{args} : {};
Branch: 1 branch
BranchTrueFalseTotal
defined $request->{'args'} ? : 0 0 0
1786  
1787 0 ▶ if ( defined( $args->{ip} ) && defined( $args->{cidr} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"ip"} and defined $args->{"cidr"}) 0 0 0
Condition0%0/3
defined $args->{"ip"} and defined $args->{"cidr"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $args->{"ip"} and defined $args->{"cidr"}
defined $args->{"ip"} defined $args->{"cidr"}
Truth table0%0/3
A and B
A= defined $args->{"ip"}B= defined $args->{"cidr"}
ABresult
0X0
100
111
1788 0 die('only one of args.ip and args.cidr may be given');
1789 }
1790  
1791 0 my $ident = 'kur-' . $self->{name};
1792 0 my $cleared = { 'ip' => 0, 'cidr' => 0 };
1793  
1794 0 foreach my $family ( 'ip', 'cidr' ) {
1795 0 my $spec = $family_spec{$family};
1796 0 my $named = $args->{ $spec->{retry_arg} };
1797 0 ▶ my $other_family_named = defined( $args->{ $family_spec{ $family eq 'ip' ? 'cidr' : 'ip' }->{retry_arg} } );
Branch: 1 branch
BranchTrueFalseTotal
$family eq 'ip' ? : 0 0 0
1798  
1799 # a named entry only clears from its own family, and naming one
1800 # family means the other is left alone entirely
1801 0 ▶ if ( defined($named) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $named) 0 0 0
1802 0 ▶ if ( ref($named) ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $named ne "") 0 0 0
1803 0 die( 'args.' . $spec->{retry_arg} . ' must be a single ' . $spec->{noun} );
1804 }
1805 0 my $entry = $spec->{normalizer}->($named);
1806 0 ▶ if ( !defined($entry) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $entry) 0 0 0
1807 die( 'args.'
1808 . $spec->{retry_arg} . ', "'
1809 . $named
1810 . '", does not appear to be an IPv4 or IPv6 '
1811 0 . $spec->{noun} );
1812 }
1813 0 ▶ if ( defined( delete( $self->{ $spec->{retry_hash} }{$entry} ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined delete $$self{$spec->{"retry_hash"}}{$entry}) 0 0 0
1814 0 $cleared->{$family} = 1;
1815 0 my $retry_checkpoint_method = $spec->{retry_checkpoint};
1816 0 $self->$retry_checkpoint_method;
1817 0 log_drek( 'info', 'forgot the owed unban of ' . $spec->{infix} . $entry, undef, $ident );
1818 }
1819 0 next;
1820 } ## end if ( defined($named) )
1821  
1822 0 ▶ next if ($other_family_named);
Branch: 1 branch
BranchTrueFalseTotal
if $other_family_named 0 0 0
1823  
1824 0 my $count = scalar( keys( %{ $self->{ $spec->{retry_hash} } } ) );
1825 0 ▶ if ($count) {
Branch: 1 branch
BranchTrueFalseTotal
if ($count) 0 0 0
1826 0 $self->{ $spec->{retry_hash} } = {};
1827 0 $cleared->{$family} = $count;
1828 0 my $retry_checkpoint_method = $spec->{retry_checkpoint};
1829 0 $self->$retry_checkpoint_method;
1830 0 log_drek( 'info', 'forgot ' . $count . ' owed ' . $spec->{infix} . 'unbans', undef, $ident );
1831 }
1832 } ## end foreach my $family ( 'ip', 'cidr' )
1833  
1834 return {
1835 'cleared' => $cleared->{ip} + $cleared->{cidr},
1836 'cleared_ip' => $cleared->{ip},
1837 'cleared_cidr' => $cleared->{cidr},
1838 0 };
1839 } ## end sub _cmd_clear_retries
1840  
1841 # Handles the checkpoint command off the socket, forcing all four tablets out
1842 # now. The tablets are already written on every mutation and every checkpoint
1843 # seconds, so this is rarely needed... it is here for taking a consistent
1844 # snapshot before a backup or a look at the files by hand.
1845 #
1846 # Takes no arguments beyond the invocant. Deliberately not gated on
1847 # _refuse_when_stopping, as writing tablets is safe at any point and stop
1848 # does exactly this on its way out.
1849 #
1850 # Returns a hash ref of...
1851 #
1852 # checkpointed :: Always 1. There is no failure answer... a tablet
1853 # write that fails logs and counts an error rather
1854 # than reporting back, so this says the command ran,
1855 # not that all four files landed.
1856 # bans :: How many single IP bans the book holds.
1857 # cidr_bans :: How many range bans it holds.
1858 # unban_retries :: How many single IP unbans are still owed.
1859 # cidr_unban_retries :: How many range unbans are still owed.
1860 #
1861 # The counts come from the books rather than the files, so they say what was
1862 # meant to be written.
1863 #
1864 # Does not die.
1865 #
1866 # my $result = $self->_cmd_checkpoint;
1867 # # $result is {
1868 # # checkpointed => 1, bans => 12, cidr_bans => 2,
1869 # # unban_retries => 0, cidr_unban_retries => 0,
1870 # # }
1871 0 ▶sub _cmd_checkpoint {
Subroutine _cmd_checkpoint: not called CC=1 SCAR=6.9
1872 0 my ($self) = @_;
1873  
1874 0 $self->_checkpoint;
1875 0 $self->_checkpoint_cidr;
1876 0 $self->_checkpoint_retries;
1877 0 $self->_checkpoint_cidr_retries;
1878 0 log_drek( 'info', 'checkpointed', undef, 'kur-' . $self->{name} );
1879  
1880 return {
1881 'checkpointed' => 1,
1882 0 'bans' => scalar( keys( %{ $self->{bans} } ) ),
1883 0 'cidr_bans' => scalar( keys( %{ $self->{cidr_bans} } ) ),
1884 0 'unban_retries' => scalar( keys( %{ $self->{unban_retries} } ) ),
1885 0 'cidr_unban_retries' => scalar( keys( %{ $self->{cidr_unban_retries} } ) ),
1886 };
1887 } ## end sub _cmd_checkpoint
1888  
1889 # Handles the stop command off the socket. Unlike every other handler this one
1890 # answers the client itself rather than returning a result to be sent, because
1891 # the response has to be flushed before the shutdown takes the server session
1892 # down with it... returning normally would have the session torn down first
1893 # and the client left hanging. Returning undef is how the JSONUnix handler
1894 # protocol says the handler has already responded.
1895 #
1896 # The teardown happens through _stop_guts, shared with the signal handler, so
1897 # a stop command and a SIGTERM leave the kur in the same state. A teardown
1898 # failure does not stop the shutdown... the process is going either way, so
1899 # the error is reported to the client and logged rather than being allowed to
1900 # strand the kur half up.
1901 #
1902 # Args, one required...
1903 #
1904 # $ctx :: The POE::Component::Server::JSONUnix per request context object
1905 # for the connection, handed to the handler by the server. Used
1906 # for respond_result to send the answer and close to hang up. It
1907 # must be this request's own context, as that is the connection
1908 # the answer belongs to.
1909 #
1910 # Returns undef, always, which the server reads as the handler having dealt
1911 # with the response itself.
1912 #
1913 # Does not die. The teardown error, if there was one, reaches the client as a
1914 # teardown_error field alongside stopping => 1, so a client can tell a clean
1915 # stop from a messy one. The shutdown is posted with a one second delay to
1916 # give that response time to flush.
1917 #
1918 # # from the server's command dispatch table
1919 # 'stop' => sub {
1920 # my ( undef, undef, $ctx ) = @_;
1921 # return $self->_cmd_stop($ctx);
1922 # },
1923 0 ▶sub _cmd_stop {
Subroutine _cmd_stop: not called CC=2 SCAR=17.9
1924 0 my ( $self, $ctx ) = @_;
1925  
1926 0 log_drek( 'info', 'stop requested, tearing the backend down', undef, 'kur-' . $self->{name} );
1927  
1928 0 my $teardown_error = $self->_stop_guts;
1929  
1930 0 ▶ $ctx->respond_result( { 'stopping' => 1, $teardown_error ? ( 'teardown_error' => $teardown_error ) : () } );
Branch: 1 branch
BranchTrueFalseTotal
$teardown_error ? : 0 0 0
1931 0 $ctx->close;
1932  
1933 # the current session is the JSONUnix server session, so this fires its
1934 # shutdown state after the response has had time to flush
1935 0 $poe_kernel->delay( 'shutdown', 1 );
1936  
1937 0 return undef;
1938 } ## end sub _cmd_stop
1939  
1940 # The common guts of stopping, shared by the stop command and the TERM/INT
1941 # handler so a signaled kur leaves exactly the state an asked one does...
1942 # tablets on disk and the firewall setup torn down, rather than the process
1943 # dying with its rules dangling.
1944 #
1945 # It sets stopping first, which stops the sweeper rescheduling so its session
1946 # can end and takes _refuse_when_stopping's guard live, then writes all four
1947 # tablets before touching the backend, so the state is safe on disk even if
1948 # the teardown goes badly.
1949 #
1950 # A successful teardown empties both retry books and rewrites their tablets,
1951 # because tearing down takes the whole setup with it, orphaned rules
1952 # included... anything that was owed has just been paid, and leaving the
1953 # tablets in place would have the next run retrying unbans for rules that no
1954 # longer exist. A failed teardown keeps those debts, as it may well have left
1955 # the rules exactly where they were.
1956 #
1957 # Takes no arguments beyond the invocant.
1958 #
1959 # Returns the teardown error as a string when the backend refused to tear
1960 # down, or the empty string when it went cleanly. Callers test it as a boolean
1961 # and pass it on... _cmd_stop puts it in the response, the signal handler
1962 # ignores it, both having logged it here.
1963 #
1964 # Does not die. The teardown is wrapped precisely so a failure cannot strand
1965 # a kur half stopped.
1966 #
1967 # my $teardown_error = $self->_stop_guts;
1968 # if ($teardown_error) {
1969 # # went down messy, the firewall may still carry rules
1970 # }
1971 0 ▶sub _stop_guts {
Subroutine _stop_guts: not called CC=2 SCAR=17.9
1972 0 my ($self) = @_;
1973  
1974 # keeps the ban sweeper from rescheduling so its session can end
1975 0 $self->{stopping} = 1;
1976  
1977 # leave a fresh state CSV behind
1978 0 $self->_checkpoint;
1979 0 $self->_checkpoint_cidr;
1980 0 $self->_checkpoint_retries;
1981 0 $self->_checkpoint_cidr_retries;
1982  
1983 0 eval { $self->_backend_do('teardown'); };
1984 0 my $teardown_error = $@;
1985 0 ▶ if ($teardown_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($teardown_error) { } 0 0 0
1986 0 log_drek( 'err', 'teardown failed... ' . $teardown_error, undef, 'kur-' . $self->{name} );
1987 } else {
1988 # teardown takes the whole firewall setup with it, orphaned rules
1989 # included, so anything that was owed has just been paid... left in
1990 # place the tablets would have the next run retrying unbans for
1991 # rules that no longer exist. a failed teardown may well have left
1992 # them there, so those debts are kept
1993 0 $self->{unban_retries} = {};
1994 0 $self->{cidr_unban_retries} = {};
1995 0 $self->_checkpoint_retries;
1996 0 $self->_checkpoint_cidr_retries;
1997 } ## end else [ if ($teardown_error) ]
1998  
1999 0 return $teardown_error;
2000 } ## end sub _stop_guts
2001  
2002 # The body of the once a second sweeper alarm started by start_server, and
2003 # the only thing in this module that happens without a client asking for it.
2004 # Everything time driven hangs off here... sentences being served, unban
2005 # retries coming due, and the periodic tablet rewrite.
2006 #
2007 # The sweep runs every tick, while the checkpoint only runs once the
2008 # configured interval has passed since the last successful one, so a busy kur
2009 # is not rewriting four files a second. A checkpoint of 0 disables the
2010 # periodic rewrite entirely, mutations and stop still writing as they go.
2011 #
2012 # Takes no arguments beyond the invocant. The session calling it has already
2013 # checked stopping, so this does not.
2014 #
2015 # Returns nothing meaningful, an empty return.
2016 #
2017 # Does not die, and must not... a die here would take the sweeper session
2018 # down and leave sentences running forever. _sweep_family wraps every backend
2019 # call, and the checkpoints report failure by logging rather than throwing.
2020 #
2021 # # from the sweeper session
2022 # 'sweep' => sub {
2023 # return if $self->{stopping};
2024 # $self->_tick;
2025 # $_[KERNEL]->delay( 'sweep', 1 );
2026 # },
2027 0 ▶sub _tick {
Subroutine _tick: not called CC=3 SCAR=24.8
2028 0 my ($self) = @_;
2029  
2030 0 $self->_sweep_bans;
2031  
2032 0 ▶ if ( $self->{checkpoint} && ( time - $self->{last_checkpoint} ) >= $self->{checkpoint} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"checkpoint"} and time - $self->{"last_checkpoint"} >= $self->{"checkpoint"}) 0 0 0
Condition0%0/3
$self->{"checkpoint"} and time - $self->{"last_checkpoint"} >= $self->{"checkpoint"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"checkpoint"} and time - $self->{"last_checkpoint"} >= $self->{"checkpoint"}
$self->{"checkpoint"} time - $self->{"last_checkpoint"} >= $self->{"checkpoint"}
Truth table0%0/3
A and B
A= $self->{"checkpoint"}B= time - $self->{"last_checkpoint"} >= $self->{"checkpoint"}
ABresult
0X0
100
111
2033 0 $self->_checkpoint;
2034 0 $self->_checkpoint_cidr;
2035 0 $self->_checkpoint_retries;
2036 0 $self->_checkpoint_cidr_retries;
2037 }
2038  
2039 0 return;
2040 } ## end sub _tick
2041  
2042 # Runs the expiry sweep over both families, which is all it does... the work
2043 # is _sweep_family's, this just saves _tick from knowing there are two
2044 # families to walk.
2045 #
2046 # Takes no arguments beyond the invocant.
2047 #
2048 # Returns nothing meaningful, an empty return.
2049 #
2050 # Does not die, _sweep_family wrapping every backend call it makes.
2051 #
2052 # $self->_sweep_bans;
2053 0 ▶sub _sweep_bans {
Subroutine _sweep_bans: not called CC=2 SCAR=17.9
2054 0 my ($self) = @_;
2055  
2056 0 foreach my $family ( 'ip', 'cidr' ) {
2057 0 $self->_sweep_family( $family_spec{$family} );
2058 }
2059  
2060 0 return;
2061 }
2062  
2063 # The shared per family sweep, and where a sentence actually ends. It has two
2064 # halves, both driven off the same current time.
2065 #
2066 # First, every booked entry whose expiry has passed is unbanned via the
2067 # backend and dropped from the book. The drop happens whether or not the
2068 # backend took it... the sentence has been served either way, and a book
2069 # still claiming a ban the kur has finished with would just feed this same
2070 # loop a doomed unban every second. What a refused unban leaves behind
2071 # instead is an entry in the retry book, so the debt to the firewall is
2072 # remembered rather than the rule being orphaned silently.
2073 #
2074 # Second, every retry that has come due is attempted again. A success drops
2075 # it; a failure bumps the counts and pushes next_try out by the current delay,
2076 # doubling that delay to a cap of 60 seconds, the same backoff shape the
2077 # manager uses for respawning a dead kur. Nothing here ever gives up... a debt
2078 # that can never be paid is cleared by the clear_retries command, by a
2079 # re-ban, or by a teardown, not by this loop deciding it has tried enough.
2080 #
2081 # The two tablets are written at most once each per call, and only when
2082 # something actually changed, which is why the two changed flags exist rather
2083 # than checkpointing inside the loops.
2084 #
2085 # Args, one required...
2086 #
2087 # $spec :: One of the %family_spec entries described above. Uses hash,
2088 # retry_hash, unban_method, expired_stat, log_label, checkpoint,
2089 # and retry_checkpoint.
2090 #
2091 # Returns nothing meaningful, an empty return. What it did is visible in the
2092 # books, the stats, and the log.
2093 #
2094 # Does not die. Every backend call is wrapped, since this runs off a POE
2095 # alarm where a die would take the sweeper session down and leave every
2096 # remaining sentence running forever. A refused unban counts an error and
2097 # becomes a retry instead.
2098 #
2099 # $self->_sweep_family( $family_spec{ip} );
2100 #
2101 # $self->_sweep_family( $family_spec{cidr} );
2102 0 ▶sub _sweep_family {
Subroutine _sweep_family: not called CC=11 SCAR=48.8
2103 0 my ( $self, $spec ) = @_;
2104  
2105 0 my $ident = 'kur-' . $self->{name};
2106 0 my $now = time;
2107 0 my $changed = 0;
2108 0 my $retry_changed = 0;
2109  
2110 0 foreach my $banned_entry ( keys( %{ $self->{ $spec->{hash} } } ) ) {
2111 0 my $entry = $self->{ $spec->{hash} }{$banned_entry};
2112 0 ▶ if ( !$entry->{expires} || $entry->{expires} > $now ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $entry->{"expires"} or $entry->{"expires"} > $now) 0 0 0
Condition0%0/3
not $entry->{"expires"} or $entry->{"expires"} > $now
l!l&&r!l&&!r
000
MC/DC0%0/2
not $entry->{"expires"} or $entry->{"expires"} > $now
not $entry->{"expires"} $entry->{"expires"} > $now
Truth table0%0/3
not(A) or B
A= not $entry->{"expires"}B= $entry->{"expires"} > $now
ABresult
1X1
011
000
2113 0 next;
2114 }
2115  
2116 0 eval { $self->_backend_do( $spec->{unban_method}, ban => $banned_entry ); };
2117 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
2118 0 $self->{stats}{errors}++;
2119 # the sentence is still considered served... the firewall side is
2120 # left to the retry loop below rather than staying orphaned there
2121 0 $self->{ $spec->{retry_hash} }{$banned_entry} = {
2122 'first_tried' => $now,
2123 'last_tried' => $now,
2124 'times_tried' => 1,
2125 'next_try' => $now + 1,
2126 'delay' => 2,
2127 };
2128 0 $retry_changed = 1;
2129 log_drek(
2130 'err',
2131 'unbanning expired '
2132 0 . $spec->{log_label} . ' of "'
2133 . $banned_entry
2134 . '" failed, will retry... '
2135 . $@,
2136 undef,
2137 $ident
2138 );
2139 } ## end if ($@)
2140 0 delete( $self->{ $spec->{hash} }{$banned_entry} );
2141 0 $self->{stats}{ $spec->{expired_stat} }++;
2142 0 $changed = 1;
2143 0 log_drek( 'info', $spec->{log_label} . ' of ' . $banned_entry . ' expired', undef, $ident );
2144 } ## end foreach my $banned_entry ( keys( %{ $self->{ $spec...}}))
2145  
2146 # retries unbans that failed at expiry, backing off with the same
2147 # doubling to a cap of 60 seconds the manager uses for respawns... a
2148 # re-ban via _ban_many cancels the entry instead
2149 0 foreach my $retry_entry ( keys( %{ $self->{ $spec->{retry_hash} } } ) ) {
2150 0 my $retry = $self->{ $spec->{retry_hash} }{$retry_entry};
2151 0 ▶ if ( $retry->{next_try} > $now ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($retry->{"next_try"} > $now) 0 0 0
2152 0 next;
2153 }
2154  
2155 0 eval { $self->_backend_do( $spec->{unban_method}, ban => $retry_entry ); };
2156 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
2157 0 $self->{stats}{errors}++;
2158 0 $retry->{last_tried} = $now;
2159 0 $retry->{times_tried}++;
2160 0 $retry->{next_try} = $now + $retry->{delay};
2161 0 ▶ $retry->{delay} = $retry->{delay} * 2 > 60 ? 60 : $retry->{delay} * 2;
Branch: 1 branch
BranchTrueFalseTotal
$retry->{'delay'} * 2 > 60 ? : 0 0 0
2162 0 $retry_changed = 1;
2163 log_drek(
2164 'err',
2165 'unban retry '
2166 . $retry->{times_tried} . ' for '
2167 0 . $spec->{log_label} . ' of "'
2168 . $retry_entry
2169 . '" failed... '
2170 . $@,
2171 undef,
2172 $ident
2173 );
2174 } else {
2175 0 delete( $self->{ $spec->{retry_hash} }{$retry_entry} );
2176 0 $retry_changed = 1;
2177 0 log_drek( 'info', 'unban retry for ' . $spec->{log_label} . ' of ' . $retry_entry . ' succeeded',
2178 undef, $ident );
2179 }
2180 } ## end foreach my $retry_entry ( keys( %{ $self->{ $spec...}}))
2181  
2182 0 ▶ if ($changed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($changed) 0 0 0
2183 0 my $checkpoint_method = $spec->{checkpoint};
2184 0 $self->$checkpoint_method;
2185 }
2186 0 ▶ if ($retry_changed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($retry_changed) 0 0 0
2187 0 my $retry_checkpoint_method = $spec->{retry_checkpoint};
2188 0 $self->$retry_checkpoint_method;
2189 }
2190  
2191 0 return;
2192 } ## end sub _sweep_family
2193  
2194 # Writes the single IP ban tablet, and the only one of the four checkpoint
2195 # wrappers that tracks when it last succeeded... _tick measures the periodic
2196 # interval against last_checkpoint, so it is deliberately only bumped on a
2197 # successful write. A failing tablet therefore has the periodic timer trying
2198 # again every tick rather than waiting out the interval each time.
2199 #
2200 # Takes no arguments beyond the invocant.
2201 #
2202 # Returns nothing meaningful, an empty return. Whether the write landed is
2203 # visible in $self->{last_checkpoint} and, on failure, the log and the error
2204 # stat.
2205 #
2206 # Does not die, _write_state reporting failure by returning false.
2207 #
2208 # $self->_checkpoint;
2209 0 ▶sub _checkpoint {
Subroutine _checkpoint: not called CC=2 SCAR=17.9
2210 0 my ($self) = @_;
2211  
2212 0 my $now = time;
2213 0 ▶ if ( $self->_write_state( $self->state_path, $self->{bans}, $now, 'ip' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_write_state($self->state_path, $self->{"bans"}, $now, "ip")) 0 0 0
2214 0 $self->{last_checkpoint} = $now;
2215 }
2216  
2217 0 return;
2218 } ## end sub _checkpoint
2219  
2220 # Writes the range ban tablet, the sibling of _checkpoint. The two families
2221 # keep separate files so the single IP tablet's format stayed exactly as it
2222 # was before ranges existed, rather than growing a family column that older
2223 # state would not carry.
2224 #
2225 # It does not touch last_checkpoint... that is _checkpoint's alone, the two
2226 # being written together everywhere so one timestamp covers both.
2227 #
2228 # Takes no arguments beyond the invocant.
2229 #
2230 # Returns nothing meaningful, an empty return.
2231 #
2232 # Does not die, _write_state reporting failure by returning false.
2233 #
2234 # $self->_checkpoint_cidr;
2235 0 ▶sub _checkpoint_cidr {
Subroutine _checkpoint_cidr: not called CC=1 SCAR=6.9
2236 0 my ($self) = @_;
2237  
2238 0 $self->_write_state( $self->cidr_state_path, $self->{cidr_bans}, time, 'cidr' );
2239  
2240 0 return;
2241 }
2242  
2243 # Writes the single IP unban retry tablet, so a debt to the firewall survives
2244 # a restart... the rule is still in place after one, so the obligation is
2245 # just as real. It is a separate file from the ban tablet because the two hold
2246 # different things: one is who is banned, the other is who should not be but
2247 # still is.
2248 #
2249 # Takes no arguments beyond the invocant.
2250 #
2251 # Returns nothing meaningful, an empty return.
2252 #
2253 # Does not die, _write_retry_state reporting failure by returning false.
2254 #
2255 # $self->_checkpoint_retries;
2256 0 ▶sub _checkpoint_retries {
Subroutine _checkpoint_retries: not called CC=1 SCAR=6.9
2257 0 my ($self) = @_;
2258  
2259 0 $self->_write_retry_state( $family_spec{ip} );
2260  
2261 0 return;
2262 }
2263  
2264 # Writes the range unban retry tablet, mirroring _checkpoint_retries for the
2265 # other family. The four checkpoint wrappers exist as named methods rather
2266 # than the callers reaching for _write_state and _write_retry_state directly
2267 # because %family_spec stores them by name, so a shared helper can write the
2268 # right family's tablet without knowing which family it is working on.
2269 #
2270 # Takes no arguments beyond the invocant.
2271 #
2272 # Returns nothing meaningful, an empty return.
2273 #
2274 # Does not die, _write_retry_state reporting failure by returning false.
2275 #
2276 # $self->_checkpoint_cidr_retries;
2277 #
2278 # # or reached by name from a shared helper
2279 # my $method = $spec->{retry_checkpoint};
2280 # $self->$method;
2281 0 ▶sub _checkpoint_cidr_retries {
Subroutine _checkpoint_cidr_retries: not called CC=1 SCAR=6.9
2282 0 my ($self) = @_;
2283  
2284 0 $self->_write_retry_state( $family_spec{cidr} );
2285  
2286 0 return;
2287 }
2288  
2289 # Writes one family's retry book out as a CSV, the debts owed to the firewall
2290 # made durable. Atomic the same way _write_state is, a temp file in the same
2291 # directory renamed over the target, so a reader never sees a half written
2292 # tablet and a failure leaves the last good one in place.
2293 #
2294 # The times are stored absolute rather than as a remaining figure, unlike the
2295 # ban tablet's ban_time_left. A debt has no sentence to re-anchor against...
2296 # it is simply owed until paid, and a next_try left in the past after a long
2297 # downtime just means the retry is due at once, which is the wanted behavior.
2298 #
2299 # An empty retry book unlinks the tablet rather than leaving a header only file
2300 # behind, so the file existing at all means something is owed. That is worth
2301 # knowing before changing it, as an operator can and does check for the file.
2302 #
2303 # The row format, one per debt, after a header line of
2304 # <label>,first_tried,last_tried,times_tried,next_try,delay ...
2305 #
2306 # <entry>,<first_tried>,<last_tried>,<times_tried>,<next_try>,<delay>
2307 #
2308 # with the entry in canonical form and the rest integers, the times epochs and
2309 # delay the seconds the backoff had reached. Rows are sorted by entry so the
2310 # file is stable between writes and diffs cleanly.
2311 #
2312 # Args, one required...
2313 #
2314 # $spec :: One of the %family_spec entries described above. Uses
2315 # retry_path, retry_hash, label, and infix.
2316 #
2317 # Returns 1 on success, including the nothing owed case where the file was
2318 # removed or was already absent, and 0 when the write failed, having logged
2319 # it and counted an error. Every caller ignores the return, the logging being
2320 # the real reporting, but it is there for one that wants it.
2321 #
2322 # Does not die. An open, print, close, rename or unlink failure is caught,
2323 # logged, counted, and reported by the return value... a tablet write is
2324 # housekeeping and must never take down a ban or a sweep.
2325 #
2326 # $self->_write_retry_state( $family_spec{ip} );
2327 # # writes /var/cache/ereshkigal/kur.<name>.retry.csv, or removes it when
2328 # # nothing is owed
2329 0 ▶sub _write_retry_state {
Subroutine _write_retry_state: not called CC=9 SCAR=45.0
2330 0 my ( $self, $spec ) = @_;
2331  
2332 0 my $path_method = $spec->{retry_path};
2333 0 my $state_file = $self->$path_method;
2334 0 my $retries = $self->{ $spec->{retry_hash} };
2335  
2336 0 ▶ if ( !%{$retries} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (%{$retries;}) 0 0 0
2337 0 ▶ if ( -e $state_file && !unlink($state_file) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $state_file and not unlink($state_file)) 0 0 0
Condition0%0/3
-e $state_file and not unlink($state_file)
!ll&&!rl&&r
000
MC/DC0%0/2
-e $state_file and not unlink($state_file)
-e $state_file not unlink($state_file)
Truth table0%0/3
A and not(B)
A= -e $state_fileB= not unlink($state_file)
ABresult
0X0
100
111
2338 0 $self->{stats}{errors}++;
2339 log_drek( 'err',
2340 'removing the empty ' . $spec->{infix} . 'retry tablet "' . $state_file . '" failed... ' . $!,
2341 0 undef, 'kur-' . $self->{name} );
2342 }
2343 0 return 1;
2344 }
2345  
2346 0 my $tmp_file = $state_file . '.tmp';
2347 0 eval {
2348 0 ▶ open( my $fh, '>', $tmp_file ) || die( 'open failed... ' . $! );
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $tmp_file or die 'open failed... ' . $! 0 0 0
2349 0 print $fh $spec->{label} . ",first_tried,last_tried,times_tried,next_try,delay\n";
2350 0 foreach my $key ( sort( keys( %{$retries} ) ) ) {
2351 0 my $retry = $retries->{$key};
2352 print $fh join( ',',
2353 $key, $retry->{first_tried}, $retry->{last_tried},
2354 0 $retry->{times_tried}, $retry->{next_try}, $retry->{delay} ) . "\n";
2355 }
2356 # as with the ban tablets, buffered print failures only surface at
2357 # close, and skipping the rename keeps the last good file in place
2358 0 ▶ close($fh) || die( 'close failed... ' . $! );
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die 'close failed... ' . $! 0 0 0
2359 0 ▶ rename( $tmp_file, $state_file ) || die( 'rename failed... ' . $! );
Branch: 1 branch
BranchTrueFalseTotal
rename $tmp_file, $state_file or die 'rename failed... ' . $! 0 0 0
2360 };
2361 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
2362 0 unlink($tmp_file);
2363 0 $self->{stats}{errors}++;
2364 log_drek( 'err',
2365 'checkpointing ' . $spec->{infix} . 'unban retry state to "' . $state_file . '" failed... ' . $@,
2366 0 undef, 'kur-' . $self->{name} );
2367 0 return 0;
2368 }
2369  
2370 0 return 1;
2371 } ## end sub _write_retry_state
2372  
2373 # Writes one family's ban book out as a CSV, which is what makes a timed ban
2374 # survive a restart with the right time left on it. Shared by both ban
2375 # checkpoints, the only difference between them being the file, the hash, and
2376 # the first column's name, which is why this takes them as arguments rather
2377 # than a $spec.
2378 #
2379 # Atomic... everything is written to a temp file beside the target and renamed
2380 # over it, so a reader never sees a partial tablet. The close is checked as
2381 # well as the open, because buffered print failures, a full filesystem being
2382 # the usual one, only surface when the handle is closed; skipping the rename
2383 # on any failure keeps the previous good tablet rather than replacing it with
2384 # a truncated one.
2385 #
2386 # The row format, one per ban, after a header line of
2387 # <label>,time,ban_time_left ...
2388 #
2389 # <entry>,<written>,<left>
2390 #
2391 # where written is the epoch this write happened and left is the seconds of
2392 # sentence remaining at that moment, 0 meaning the ban never expires. Storing
2393 # it relative rather than as an expiry epoch is what lets a restored ban serve
2394 # out its remaining time rather than being anchored to a clock that may have
2395 # moved. A ban expiring within the same second is clamped to 1 rather than
2396 # rounding to 0, since 0 is spoken for by permanent... anything genuinely
2397 # expired is the sweeper's business, not this one's. Rows are sorted by entry
2398 # so the file is stable between writes.
2399 #
2400 # Args, all four required and positional...
2401 #
2402 # $state_file :: Full path of the tablet to write. The temp file is this
2403 # with .tmp appended, so the directory has to be writable.
2404 # $bans :: The ban book to write, a hash ref of canonical entry to
2405 # { banned_at => epoch, expires => epoch or 0 }. Only
2406 # expires is read. An empty hash writes a header only file
2407 # rather than removing it, unlike the retry tablets.
2408 # $now :: Epoch to record as the write time and to measure each
2409 # remaining sentence against. Passed in rather than taken
2410 # here so every row of one write agrees.
2411 # $label :: Name for the first column, 'ip' or 'cidr'. It is also
2412 # what the loader matches to recognise the header line.
2413 #
2414 # Returns 1 on success and 0 on failure, having logged the failure and
2415 # counted an error. _checkpoint uses that to decide whether to bump
2416 # last_checkpoint.
2417 #
2418 # Does not die, for the same reason _write_retry_state does not.
2419 #
2420 # $self->_write_state(
2421 # $self->state_path, $self->{bans}, time, 'ip'
2422 # );
2423 0 ▶sub _write_state {
Subroutine _write_state: not called CC=8 SCAR=42.8
2424 0 my ( $self, $state_file, $bans, $now, $label ) = @_;
2425  
2426 0 my $tmp_file = $state_file . '.tmp';
2427 0 eval {
2428 0 ▶ open( my $fh, '>', $tmp_file ) || die( 'open failed... ' . $! );
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $tmp_file or die 'open failed... ' . $! 0 0 0
2429 0 print $fh $label . ",time,ban_time_left\n";
2430 0 foreach my $key ( sort( keys( %{$bans} ) ) ) {
2431 0 my $left = 0;
2432 0 ▶ if ( $bans->{$key}{expires} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bans->{$key}{"expires"}) 0 0 0
2433 0 $left = $bans->{$key}{expires} - $now;
2434 # clamped so a nearly expired ban can't collide with 0 meaning
2435 # permanent... anything actually expired is the sweeper's job
2436 0 ▶ if ( $left < 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($left < 1) 0 0 0
2437 0 $left = 1;
2438 }
2439 }
2440 0 print $fh $key . ',' . $now . ',' . $left . "\n";
2441 } ## end foreach my $key ( sort( keys( %{$bans} ) ) )
2442 # checked as buffered print failures, a full filesystem for example,
2443 # only surface here... skipping the rename keeps the previous good
2444 # state file in place rather than replacing it with a truncated one
2445 0 ▶ close($fh) || die( 'close failed... ' . $! );
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die 'close failed... ' . $! 0 0 0
2446 0 ▶ rename( $tmp_file, $state_file ) || die( 'rename failed... ' . $! );
Branch: 1 branch
BranchTrueFalseTotal
rename $tmp_file, $state_file or die 'rename failed... ' . $! 0 0 0
2447 };
2448 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
2449 0 unlink($tmp_file);
2450 0 $self->{stats}{errors}++;
2451 log_drek( 'err', 'checkpointing ' . $label . ' ban state to "' . $state_file . '" failed... ' . $@,
2452 0 undef, 'kur-' . $self->{name} );
2453 0 return 0;
2454 }
2455  
2456 0 return 1;
2457 } ## end sub _write_state
2458  
2459 # Restores the single IP ban book from its tablet at startup, which is what
2460 # makes a restart invisible to anyone serving a sentence. Called from new
2461 # once the backend is up, so the re-bans it drives land on a freshly inited
2462 # firewall.
2463 #
2464 # The work is _load_state's. This is just the single IP half of the pair with
2465 # _load_cidr_bans, kept as its own named sub so new reads as three plain
2466 # calls rather than a loop over families it would otherwise have to know
2467 # about.
2468 #
2469 # Takes no arguments beyond the invocant.
2470 #
2471 # Returns nothing meaningful, an empty return. What was restored is visible in
2472 # $self->{bans} and the log.
2473 #
2474 # Does not die, _load_state surviving an unreadable tablet, a malformed row,
2475 # and a backend that refuses a re-ban.
2476 #
2477 # $self->_load_bans;
2478 0 ▶sub _load_bans {
Subroutine _load_bans: not called CC=1 SCAR=6.9
2479 0 my ($self) = @_;
2480  
2481 0 $self->_load_state( $self->state_path, $family_spec{ip} );
2482  
2483 0 return;
2484 }
2485  
2486 # Restores the range ban book from its tablet at startup, mirroring
2487 # _load_bans for the other family, with one deliberate difference... it is
2488 # skipped entirely when ranges are not available to this instance.
2489 #
2490 # That skip matters because of what not skipping would do. Loading is not
2491 # passive: every restored row is re-banned through the backend. Handing a
2492 # tablet full of ranges to a backend that cannot carry them, or to a kur
2493 # whose operator has since turned enable_cidr off, would be a burst of
2494 # failures at every startup. Skipping leaves the file untouched instead, so a
2495 # later run that turns ranges back on finds its state exactly as it was.
2496 #
2497 # Takes no arguments beyond the invocant.
2498 #
2499 # Returns nothing meaningful, an empty return, including the skipped case,
2500 # which is not reported... _cidr_available already logged the mismatch at
2501 # init if there was one.
2502 #
2503 # Does not die.
2504 #
2505 # $self->_load_cidr_bans;
2506 0 ▶sub _load_cidr_bans {
Subroutine _load_cidr_bans: not called CC=2 SCAR=17.9
2507 0 my ($self) = @_;
2508  
2509 0 ▶ if ( !$self->_cidr_available ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_cidr_available) 0 0 0
2510 0 return;
2511 }
2512  
2513 0 $self->_load_state( $self->cidr_state_path, $family_spec{cidr} );
2514  
2515 0 return;
2516 } ## end sub _load_cidr_bans
2517  
2518 # Restores both retry books from their tablets at startup. An unban that was
2519 # still owed when the kur went down is owed just as much now, the rule having
2520 # outlived the process, so the entries come back with their counts and their
2521 # backoff intact rather than starting over at one attempt and a one second
2522 # delay.
2523 #
2524 # Both families are loaded unconditionally, which is the one place the range
2525 # side is not gated on _cidr_available. The reason is that a debt is to the
2526 # firewall rather than to the feature... a rule this kur failed to remove is
2527 # sitting there regardless of whether the operator has since turned ranges
2528 # off, and unlike _load_cidr_bans this restores no bans and asks the backend
2529 # for nothing, so there is no failure burst to avoid.
2530 #
2531 # Takes no arguments beyond the invocant.
2532 #
2533 # Returns nothing meaningful, an empty return.
2534 #
2535 # Does not die, _load_retry_state surviving an unreadable tablet and skipping
2536 # rows it cannot parse.
2537 #
2538 # $self->_load_retries;
2539 0 ▶sub _load_retries {
Subroutine _load_retries: not called CC=2 SCAR=17.9
2540 0 my ($self) = @_;
2541  
2542 0 foreach my $family ( 'ip', 'cidr' ) {
2543 0 $self->_load_retry_state( $family_spec{$family} );
2544 }
2545  
2546 0 return;
2547 }
2548  
2549 # The shared per family retry tablet loader, reading back what
2550 # _write_retry_state put down. Unlike the ban loader it asks the backend for
2551 # nothing... a debt is book keeping about a rule that is already there, so
2552 # restoring one means only putting the entry back in the retry book for the
2553 # sweeper to pick up.
2554 #
2555 # Each row is parsed and checked twice. The shape check wants exactly six
2556 # fields with a non-empty entry and five integers, and the normalize check
2557 # wants the entry itself to validate, which keeps the retry books canonical
2558 # only in the same way the ban books are... a raw spelling booked here would
2559 # be a debt the clear_retries command could never name, as that normalizes
2560 # what it is asked to forget. A row failing either is logged and skipped
2561 # rather than taking the file down with it.
2562 #
2563 # A restored delay is brought inside the same bounds the backoff keeps
2564 # itself in, since only its own doubling is clamped and a tablet can carry
2565 # anything. A 0, which only a hand edited one would, is floored back to 2...
2566 # left alone it would peg the backoff at zero forever and have the sweeper
2567 # retrying that entry every single tick. Anything past the 60 second cap is
2568 # brought back to it, a delay of say 999999 having otherwise put the next
2569 # attempt a week and a half out.
2570 #
2571 # The tablet is rewritten at the end so what is on disk matches what was
2572 # actually restored, which is how skipped rows get dropped rather than
2573 # lingering to be skipped again at every future startup.
2574 #
2575 # Args, one required...
2576 #
2577 # $spec :: One of the %family_spec entries described above. Uses
2578 # retry_path, retry_hash, label, normalizer, noun, infix, and
2579 # retry_checkpoint.
2580 #
2581 # Returns nothing meaningful, an empty return, including when the tablet does
2582 # not exist, which is the ordinary case of nothing being owed.
2583 #
2584 # Does not die. A tablet that cannot be opened or read is logged and the load
2585 # abandoned, leaving the book empty rather than the kur refusing to start over
2586 # a file it only needed for housekeeping.
2587 #
2588 # $self->_load_retry_state( $family_spec{ip} );
2589 # # a row of 1.2.3.4,1785918152,1785919052,9,1785919112,60 comes back as
2590 # # $self->{unban_retries}{'1.2.3.4'} with those counts and that backoff
2591 0 ▶sub _load_retry_state {
Subroutine _load_retry_state: not called CC=14 SCAR=53.5
2592 0 my ( $self, $spec ) = @_;
2593  
2594 0 my $path_method = $spec->{retry_path};
2595 0 my $state_file = $self->$path_method;
2596  
2597 0 ▶ if ( !-f $state_file ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $state_file) 0 0 0
2598 0 return;
2599 }
2600  
2601 0 my $ident = 'kur-' . $self->{name};
2602  
2603 0 my @lines;
2604 0 eval {
2605 0 ▶ open( my $fh, '<', $state_file ) || die( 'open failed... ' . $! );
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $state_file or die 'open failed... ' . $! 0 0 0
2606 0 @lines = <$fh>;
2607 0 close($fh);
2608 };
2609 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
2610 0 log_drek( 'err', 'loading ' . $spec->{infix} . 'unban retry state from "' . $state_file . '" failed... ' . $@,
2611 undef, $ident );
2612 0 return;
2613 }
2614  
2615 0 my $line_number = 0;
2616 0 foreach my $line (@lines) {
2617 0 $line_number++;
2618 0 chomp($line);
2619 0 ▶ if ( $line eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line eq "") 0 0 0
2620 0 next;
2621 }
2622 0 ▶ if ( $line_number == 1 && $line =~ /^$spec->{label},/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line_number == 1 and $line =~ /^$spec->{"label"},/) 0 0 0
Condition0%0/3
$line_number == 1 and $line =~ /^$spec->{"label"},/
!ll&&!rl&&r
000
MC/DC0%0/2
$line_number == 1 and $line =~ /^$spec->{"label"},/
$line_number == 1 $line =~ /^$spec->{"label"},/
Truth table0%0/3
A and B
A= $line_number == 1B= $line =~ /^$spec->{"label"},/
ABresult
0X0
100
111
2623 # the header
2624 0 next;
2625 }
2626  
2627 0 my @row = split( /,/, $line );
2628 0 ▶ if ( @row != 6 || $row[0] eq '' || grep { $row[$_] !~ /^[0-9]+$/ } ( 1 .. 5 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@row != 6 or $row[0] eq "" or grep {not $row[$_] =~ /^[0-9]+$/;} 1..5) 0 0 0
Condition0%0/6
@row != 6 or $row[0] eq "" or grep {not $row[$_] =~ /^[0-9]+$/;} 1..5
l!l&&r!l&&!r
000
@row != 6 or $row[0] eq ""
l!l&&r!l&&!r
000
MC/DC0%0/3
@row != 6 or $row[0] eq "" or grep {not $row[$_] =~ /^[0-9]+$/;} 1..5
@row != 6 $row[0] eq "" grep {not $row[$_] =~ /^[0-9]+$/;} 1..5
Truth table0%0/4
A or B or C
A= @row != 6B= $row[0] eq ""C= grep {not $row[$_] =~ /^[0-9]+$/;} 1..5
ABCresult
1XX1
01X1
0011
0000
2629 0 log_drek( 'err', 'skipping malformed line ' . $line_number . ' in "' . $state_file . '"... "' . $line . '"',
2630 undef, $ident );
2631 0 next;
2632 }
2633 0 my ( $entry, $first_tried, $last_tried, $times_tried, $next_try, $delay ) = @row;
2634  
2635 0 my $normalized = $spec->{normalizer}->($entry);
2636 0 ▶ if ( !defined($normalized) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $normalized) 0 0 0
2637 log_drek(
2638 'err',
2639 'skipping line '
2640 . $line_number . ' in "'
2641 . $state_file
2642 . '"... "'
2643 . $entry
2644 . '" is not a valid '
2645 . $spec->{noun},
2646 undef,
2647 0 $ident
2648 );
2649 0 next;
2650 } ## end if ( !defined($normalized) )
2651  
2652 0 ▶ $self->{ $spec->{retry_hash} }{$normalized} = {
Branch: 2 branches
BranchTrueFalseTotal
$delay ? : 0 0 0
$delay > 60 ? : 0 0 0
2653 'first_tried' => $first_tried,
2654 'last_tried' => $last_tried,
2655 'times_tried' => $times_tried,
2656 'next_try' => $next_try,
2657 # a tablet written by hand could carry anything, and the backoff
2658 # only clamps what its own doubling produces, so a restored
2659 # value is brought inside the same bounds here... a 0 would peg
2660 # the backoff at 0 forever and is floored to where a first
2661 # failure would have left it, while anything past the cap would
2662 # put next_try days out and is brought back to the cap
2663 'delay' => $delay ? ( $delay > 60 ? 60 : $delay ) : 2,
2664 };
2665 log_drek(
2666 'info',
2667 'unban of '
2668 . $spec->{infix}
2669 0 . $normalized
2670 . ' still owed from a previous run, tried '
2671 . $times_tried
2672 . ' times',
2673 undef,
2674 $ident
2675 );
2676 } ## end foreach my $line (@lines)
2677  
2678 # rewrite so the tablet reflects what actually got restored
2679 0 my $checkpoint_method = $spec->{retry_checkpoint};
2680 0 $self->$checkpoint_method;
2681  
2682 0 return;
2683 } ## end sub _load_retry_state
2684  
2685 # The shared per family ban tablet loader behind _load_bans and
2686 # _load_cidr_bans, and the one loader that actually touches the firewall...
2687 # restoring a ban means re-banning it, the backend having just been inited
2688 # empty.
2689 #
2690 # Each row's remaining sentence is reconstructed as written + left, which is
2691 # what makes a ban serve out the time it had rather than restarting its
2692 # sentence, and that expiry decides which of two things happens. A row that
2693 # ran out while the kur was down is unbanned rather than restored, in case
2694 # the firewall still carries the rule from before, and counted as expired. A
2695 # row still serving is re-banned and booked.
2696 #
2697 # A re-ban the backend refuses is deliberately not booked, matching how a
2698 # live ban behaves... a book claiming a ban the firewall does not carry would
2699 # only feed the sweeper a doomed unban later.
2700 #
2701 # Rows are checked the same two ways the retry loader checks its own, for
2702 # shape and then for an entry that will normalize, and a failure of either is
2703 # logged and skipped. Everything is normalized before being booked, so a
2704 # tablet carrying a non-canonical spelling has that row dropped rather than
2705 # booked raw, which would leave a ban the unban path could never name.
2706 #
2707 # The tablet is rewritten at the end so it reflects what actually got
2708 # restored, dropping the expired and the skipped.
2709 #
2710 # Args, both required and positional...
2711 #
2712 # $state_file :: Full path of the tablet to read. A missing file is the
2713 # ordinary first run case and returns quietly.
2714 # $spec :: One of the %family_spec entries described above. Uses
2715 # label, normalizer, noun, infix, log_label, ban_method,
2716 # unban_method, hash, expired_stat, and checkpoint.
2717 #
2718 # Returns nothing meaningful, an empty return. What was restored is visible in
2719 # that family's ban book, the expired stat, and the log.
2720 #
2721 # Does not die. An unreadable tablet is logged and the load abandoned, and
2722 # every backend call is wrapped, so neither a bad file nor a firewall in a bad
2723 # mood can stop the kur starting.
2724 #
2725 # $self->_load_state( $self->state_path, $family_spec{ip} );
2726 #
2727 # $self->_load_state( $self->cidr_state_path, $family_spec{cidr} );
2728 0 ▶sub _load_state {
Subroutine _load_state: not called CC=18 SCAR=58.3
2729 0 my ( $self, $state_file, $spec ) = @_;
2730  
2731 0 ▶ if ( !-f $state_file ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $state_file) 0 0 0
2732 0 return;
2733 }
2734  
2735 0 my $ident = 'kur-' . $self->{name};
2736  
2737 0 my @lines;
2738 0 eval {
2739 0 ▶ open( my $fh, '<', $state_file ) || die( 'open failed... ' . $! );
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $state_file or die 'open failed... ' . $! 0 0 0
2740 0 @lines = <$fh>;
2741 0 close($fh);
2742 };
2743 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
2744 0 log_drek( 'err', 'loading ' . $spec->{infix} . 'ban state from "' . $state_file . '" failed... ' . $@,
2745 undef, $ident );
2746 0 return;
2747 }
2748  
2749 0 my $now = time;
2750 0 my $line_number = 0;
2751 0 foreach my $line (@lines) {
2752 0 $line_number++;
2753 0 chomp($line);
2754 0 ▶ if ( $line eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line eq "") 0 0 0
2755 0 next;
2756 }
2757 0 ▶ if ( $line_number == 1 && $line =~ /^$spec->{label},/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line_number == 1 and $line =~ /^$spec->{"label"},/) 0 0 0
Condition0%0/3
$line_number == 1 and $line =~ /^$spec->{"label"},/
!ll&&!rl&&r
000
MC/DC0%0/2
$line_number == 1 and $line =~ /^$spec->{"label"},/
$line_number == 1 $line =~ /^$spec->{"label"},/
Truth table0%0/3
A and B
A= $line_number == 1B= $line =~ /^$spec->{"label"},/
ABresult
0X0
100
111
2758 # the header
2759 0 next;
2760 }
2761  
2762 0 my @row = split( /,/, $line );
2763 0 ▶ if ( @row != 3 || $row[0] eq '' || $row[1] !~ /^[0-9]+$/ || $row[2] !~ /^[0-9]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@row != 3 or $row[0] eq "" or not $row[1] =~ /^[0-9]+$/ or not $row[2] =~ /^[0-9]+$/) 0 0 0
Condition0%0/9
@row != 3 or $row[0] eq "" or not $row[1] =~ /^[0-9]+$/ or not $row[2] =~ /^[0-9]+$/
l!l&&r!l&&!r
000
@row != 3 or $row[0] eq "" or not $row[1] =~ /^[0-9]+$/
l!l&&r!l&&!r
000
@row != 3 or $row[0] eq ""
l!l&&r!l&&!r
000
MC/DC0%0/4
@row != 3 or $row[0] eq "" or not $row[1] =~ /^[0-9]+$/ or not $row[2] =~ /^[0-9]+$/
@row != 3 $row[0] eq "" not $row[1] =~ /^[0-9]+$/ not $row[2] =~ /^[0-9]+$/
Truth table0%0/5
A or B or not(C) or not(D)
A= @row != 3B= $row[0] eq ""C= not $row[1] =~ /^[0-9]+$/D= not $row[2] =~ /^[0-9]+$/
ABCDresult
1XXX1
01XX1
001X1
00011
00000
2764 0 log_drek( 'err', 'skipping malformed line ' . $line_number . ' in "' . $state_file . '"... "' . $line . '"',
2765 undef, $ident );
2766 0 next;
2767 }
2768 0 my ( $banned_entry, $written, $left ) = @row;
2769 # everything is normalized before being booked, so a row that will
2770 # not normalize is a hand edit or a corrupt tablet... it is skipped
2771 # rather than booked raw, which would leave an entry the unban path
2772 # can never name, as it normalizes what it is asked to remove
2773 0 my $normalized = $spec->{normalizer}->($banned_entry);
2774 0 ▶ if ( !defined($normalized) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $normalized) 0 0 0
2775 log_drek(
2776 'err',
2777 'skipping line '
2778 . $line_number . ' in "'
2779 . $state_file
2780 . '"... "'
2781 . $banned_entry
2782 . '" is not a valid '
2783 . $spec->{noun},
2784 undef,
2785 0 $ident
2786 );
2787 0 next;
2788 } ## end if ( !defined($normalized) )
2789 0 $banned_entry = $normalized;
2790  
2791 0 ▶ my $expires = $left ? $written + $left : 0;
Branch: 1 branch
BranchTrueFalseTotal
$left ? : 0 0 0
2792  
2793 0 ▶ if ( $expires && $expires <= $now ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expires and $expires <= $now) 0 0 0
Condition0%0/3
$expires and $expires <= $now
!ll&&!rl&&r
000
MC/DC0%0/2
$expires and $expires <= $now
$expires $expires <= $now
Truth table0%0/3
A and B
A= $expiresB= $expires <= $now
ABresult
0X0
100
111
2794 # expired while not running... the backend may still carry the rule
2795 0 eval { $self->_backend_do( $spec->{unban_method}, ban => $banned_entry ); };
2796 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
2797 log_drek( 'err',
2798 0 'unbanning expired ' . $spec->{log_label} . ' of "' . $banned_entry . '" failed... ' . $@,
2799 undef, $ident );
2800 }
2801 0 $self->{stats}{ $spec->{expired_stat} }++;
2802 0 log_drek( 'info', $spec->{log_label} . ' of ' . $banned_entry . ' expired while not running',
2803 undef, $ident );
2804 0 next;
2805 } ## end if ( $expires && $expires <= $now )
2806  
2807 0 eval { $self->_backend_do( $spec->{ban_method}, ban => $banned_entry ); };
2808 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
2809 # not recorded in the book on failure, matching how a live ban
2810 # behaves... a book claiming a ban the firewall does not carry
2811 # would just feed the sweeper a doomed unban later
2812 log_drek( 'err',
2813 0 're-banning ' . $spec->{infix} . '"' . $banned_entry . '" from saved state failed... ' . $@,
2814 undef, $ident );
2815 0 next;
2816 }
2817 # banned_at is not persisted, so the row's time stands in for it
2818 0 $self->{ $spec->{hash} }{$banned_entry} = { 'banned_at' => $written, 'expires' => $expires };
2819 } ## end foreach my $line (@lines)
2820  
2821 # write an updated one back out so the file reflects what got restored
2822 0 my $checkpoint_method = $spec->{checkpoint};
2823 0 $self->$checkpoint_method;
2824  
2825 0 return;
2826 } ## end sub _load_state
2827  
2828 =head1 ERROR CODES / ERROR FLAGS
2829  
2830 Error handling is provided by L<Error::Helper>. All errors
2831 are considered fatal.
2832  
2833 =head2 1, NErunBaseDir
2834  
2835 The run base dir or the kur dir under it does not exist or is not a directory.
2836  
2837 =head2 2, invalidName
2838  
2839 Name not defined or does not match /^[a-zA-Z0-9\-]+$/.
2840  
2841 =head2 3, backendInitFailed
2842  
2843 Failed to initialize the backend.
2844  
2845 =head2 4, nonRWrunBaseDir
2846  
2847 The run base dir or the kur dir under it is not readable or writable by the
2848 current user.
2849  
2850 =head2 5, NEcacheBaseDir
2851  
2852 The cache base dir does not exist or is not a directory.
2853  
2854 =head2 6, nonRWcacheBaseDir
2855  
2856 The cache base dir is not readable or writable by the current user.
2857  
2858 =head2 7, invalidBanTime
2859  
2860 ban_time is not a non-negative int of seconds.
2861  
2862 =head2 8, invalidCheckpoint
2863  
2864 checkpoint is not a non-negative int of seconds.
2865  
2866 =cut
2867  
2868 14 1; # End of Ereshkigal::Kur
« blib/lib/Ereshkigal.pm ↑ Summary blib/lib/Ereshkigal/App/Command/start.pm »