Clacks/Server.pm

filter: Statementstmt 7.9% 89 / 1123 Branchbran 0.0% 0 / 548 Conditioncond 0.0% 0 / 175 MC/DCmcdc 0.0% 0 / 112 Subroutinesub 43.7% 28 / 64 Podpod 100% 5 / 5 totaltotal 6.0% 122 / 2027 SCAR 117.0
CC
373
Cov
5%
_init
3545.9
_handleMessageOverhead
3080.0
_handleMessageCaching
1190.0
CRAP 120333.4
↑ Summary Clacks/Client.pm »
1 package Net::Clacks::Server;
2 #---AUTOPRAGMASTART---
3 4 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use diagnostics;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use mro 'c3';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use English qw(-no_match_vars);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use Carp qw[carp croak confess cluck longmess shortmess];
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 our $VERSION = 36;
10 4 ▶use autodie qw( close );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 4 ▶use Array::Contains;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 4 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 4 ▶use Encode qw(is_utf8 encode_utf8 decode_utf8);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 4 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 4 ▶use builtin qw[true false is_bool];
Subroutine BEGIN: called CC=1 SCAR=0.0
16 4 ▶no warnings qw(experimental::builtin); ## no critic (TestingAndDebugging::ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
17 #---AUTOPRAGMAEND---
18  
19 4 ▶use XML::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 4 ▶use Time::HiRes qw(sleep usleep time);
Subroutine BEGIN: called CC=1 SCAR=0.0
21 4 ▶use Sys::Hostname;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 4 ▶use Errno;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 4 ▶use IO::Socket::IP;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 4 ▶use IO::Select;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 4 ▶use IO::Socket::SSL;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 4 ▶use YAML::Syck;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 4 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 4 ▶use File::Copy;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 4 ▶use Scalar::Util qw(looks_like_number weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 # For turning off SSL session cache
32 4 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 4 Readonly my $SSL_SESS_CACHE_OFF => 0x0000;
34  
35 4 my %overheadflags = (
36 A => "auth_token", # Authentication token
37 O => "auth_ok", # Authentication OK
38 F => "auth_failed", # Authentication FAILED
39  
40 E => 'error_message', # Server to client error message
41  
42 C => "close_all_connections",
43 D => "discard_message",
44 G => "forward_message",
45 I => "set_interclacks_mode", # value: true/false, disables 'G' and 'U'
46 L => "lock_for_sync", # value: true/false, only available in interclacks client mode
47 M => "informal_message", # informal message, no further operation on it
48 N => "no_logging",
49 S => "shutdown_service", # value: positive number (number in seconds before shutdown). If interclacks clients are present, should be high
50 # enough to flush all buffers to them
51  
52 T => 'timestamp', # Used before KEYSYNC to compensate for time drift between different systems
53 U => "return_to_sender",
54 Z => "no_flags", # Only sent when no other flags are set
55 );
56  
57 BEGIN {
58 {
59 # We need to add some extra function to IO::Socket::SSL so we can track the client ID
60 # on both TCP and Unix Domain Sockets
61 4 ▶ no strict 'refs'; ## no critic (TestingAndDebugging::ProhibitNoStrict)
Subroutine BEGIN: called CC=1 SCAR=1.4
Subroutine BEGIN: called CC=1 SCAR=1.4
62 4 *{"IO::Socket::SSL::_setClientID"} = sub {
63 0 ▶ my ($self, $cid) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
64
65 0 ${*$self}{'__client_id'} = $cid; ## no critic (References::ProhibitDoubleSigils)
66 0 return;
67 4 };
68
69 4 *{"IO::Socket::SSL::_getClientID"} = sub {
70 0 ▶ my ($self) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
71
72 0 ▶ return ${*$self}{'__client_id'} || ''; ## no critic (References::ProhibitDoubleSigils)
Condition0%0/2
do { *$self }->{'__client_id'} || ''
l!l
00
MC/DC0%0/1
do { *$self }->{'__client_id'} || ''
do { *$self }->{'__client_id'}
Truth table0%0/2
A
A= do { *$self }->{'__client_id'}
Aresult
11
00
73 4 };
74  
75 }
76
77 }
78  
79 ▶sub new($class, $isDebugging, $configfile) {
Subroutine new: not called CC=2 SCAR=17.9
Pod documented
80  
81 0 my $self = bless {}, $class;
82  
83 0 $self->{isDebugging} = $isDebugging;
84 0 $self->{configfile} = $configfile;
85  
86 0 $self->{timeoffset} = 0;
87  
88 0 ▶ if(defined($ENV{CLACKS_SIMULATED_TIME_OFFSET})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{"CLACKS_SIMULATED_TIME_OFFSET"}) 0 0 0
89 0 $self->{timeoffset} = 0 + $ENV{CLACKS_SIMULATED_TIME_OFFSET};
90 0 print "****** RUNNING WITH A SIMULATED TIME OFFSET OF ", $self->{timeoffset}, " seconds ******\n";
91 }
92  
93 0 $self->{cache} = {};
94  
95 0 return $self;
96 }
97  
98 ▶sub init($self) {
Subroutine init: not called CC=1 SCAR=6.9
Pod documented
99 # Dummy function for backward compatibility
100 0 carp("Deprecated call to init(), you can remove that function from your code");
101 0 return;
102 }
103  
104 ▶sub run($self) {
Subroutine run: not called CC=10 SCAR=47.0
Pod documented
105 0 ▶ if(!defined($self->{initHasRun}) || !$self->{initHasRun}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"initHasRun"} and $self->{"initHasRun"}) 0 0 0
Condition0%0/3
defined $self->{"initHasRun"} and $self->{"initHasRun"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"initHasRun"} and $self->{"initHasRun"}
defined $self->{"initHasRun"} $self->{"initHasRun"}
Truth table0%0/3
A and B
A= defined $self->{"initHasRun"}B= $self->{"initHasRun"}
ABresult
0X0
100
111
106 0 $self->_init();
107 }
108  
109 0 my $nextdebugfile = 0;
110  
111 0 ▶ while($self->{keepRunning}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"keepRunning"}) 0 0 0
112 0 my $now = time;
113  
114 0 ▶ if($now > $nextdebugfile) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now > $nextdebugfile) 0 0 0
115 0 $nextdebugfile = $now + 10;
116 0 $self->_saveDebugFile();
117 }
118  
119 # Check for shutdown time
120 0 ▶ if($self->{shutdowntime} && $self->{shutdowntime} < $now) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"shutdowntime"} and $self->{"shutdowntime"} < $now) 0 0 0
Condition0%0/3
$self->{"shutdowntime"} and $self->{"shutdowntime"} < $now
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"shutdowntime"} and $self->{"shutdowntime"} < $now
$self->{"shutdowntime"} $self->{"shutdowntime"} < $now
Truth table0%0/3
A and B
A= $self->{"shutdowntime"}B= $self->{"shutdowntime"} < $now
ABresult
0X0
100
111
121 0 print STDERR "Shutdown time has arrived!\n";
122 0 $self->{keepRunning} = 0;
123 }
124  
125 0 $self->runOnce();
126  
127 0 ▶ if($self->{workCount}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'workCount'}) { } 0 0 0
elsif ($self->{'usleep'} < $self->{'config'}{'throttle'}{'maxsleep'}) { } 0 0 0
128 0 $self->{usleep} = 0;
129 } elsif($self->{usleep} < $self->{config}->{throttle}->{maxsleep}) {
130 0 $self->{usleep} += $self->{config}->{throttle}->{step};
131 }
132 0 ▶ if($self->{usleep}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"usleep"}) 0 0 0
133 0 sleep($self->{usleep} / 1000);
134 }
135 }
136  
137 0 $self->runShutdown();
138  
139 0 return;
140 }
141  
142 ▶sub runOnce($self) {
Subroutine runOnce: not called CC=30 SCAR=68.4
Pod documented
143 0 ▶ if(!defined($self->{initHasRun}) || !$self->{initHasRun}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"initHasRun"} and $self->{"initHasRun"}) 0 0 0
Condition0%0/3
defined $self->{"initHasRun"} and $self->{"initHasRun"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"initHasRun"} and $self->{"initHasRun"}
defined $self->{"initHasRun"} $self->{"initHasRun"}
Truth table0%0/3
A and B
A= defined $self->{"initHasRun"}B= $self->{"initHasRun"}
ABresult
0X0
100
111
144 0 $self->_init();
145 }
146  
147 0 $self->{workCount} = 0;
148  
149 0 my $now = $self->_getTime();
150 0 ▶ if($self->{savecache} && $now > ($self->{lastsavecache} + $self->{persistanceinterval})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"savecache"} and $now > $self->{"lastsavecache"} + $self->{"persistanceinterval"}) 0 0 0
Condition0%0/3
$self->{"savecache"} and $now > $self->{"lastsavecache"} + $self->{"persistanceinterval"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"savecache"} and $now > $self->{"lastsavecache"} + $self->{"persistanceinterval"}
$self->{"savecache"} $now > $self->{"lastsavecache"} + $self->{"persistanceinterval"}
Truth table0%0/3
A and B
A= $self->{"savecache"}B= $now > $self->{"lastsavecache"} + $self->{"persistanceinterval"}
ABresult
0X0
100
111
151 0 $self->{lastsavecache} = $now;
152 0 $self->_savePersistanceFile();
153 0 $self->{savecache} = 0;
154 }
155  
156 # We are in client mode. We need to add an interclacks link
157 0 ▶ if(defined($self->{config}->{master}->{socket}) || defined($self->{config}->{master}->{ip})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"config"}{"master"}{"socket"} or defined $self->{"config"}{"master"}{"ip"}) 0 0 0
Condition0%0/3
defined $self->{"config"}{"master"}{"socket"} or defined $self->{"config"}{"master"}{"ip"}
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $self->{"config"}{"master"}{"socket"} or defined $self->{"config"}{"master"}{"ip"}
defined $self->{"config"}{"master"}{"socket"} defined $self->{"config"}{"master"}{"ip"}
Truth table0%0/3
A or B
A= defined $self->{"config"}{"master"}{"socket"}B= defined $self->{"config"}{"master"}{"ip"}
ABresult
1X1
011
000
158 0 $self->_addInterclacksLink();
159 }
160  
161 0 $self->_addNewClients();
162  
163 0 $self->_disconnectClients();
164  
165 0 ▶ if(!(scalar keys %{$self->{clients}})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar keys %{$$self{"clients"};}) 0 0 0
166 # No clients to handle, let's sleep and try again later
167 0 sleep(0.1);
168 0 return $self->{workCount};
169 }
170  
171 0 $self->_clientInput();
172  
173  
174 0 foreach my $cid (keys %{$self->{clients}}) {
175 0 ▶ while(@{$self->{clients}->{$cid}->{charbuffer}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"clients"}{$cid}{"charbuffer"};}) 0 0 0
176 0 my $buf = shift @{$self->{clients}->{$cid}->{charbuffer}};
177  
178 0 $self->{workCount}++;
179 0 ▶ if($buf eq "\r") {
Branch: 2 branches
BranchTrueFalseTotal
if ($buf eq "\r") { } 0 0 0
elsif ($buf eq "\n") { } 0 0 0
180 0 next;
181 } elsif($buf eq "\n") {
182 0 ▶ next if($self->{clients}->{$cid}->{buffer} eq ''); # Empty lines
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"clients"}{$cid}{"buffer"} eq "" 0 0 0
183  
184 my %inmsg = (
185 message => $self->{clients}->{$cid}->{buffer},
186 releasetime => $now + $self->{clients}->{$cid}->{inmessagedelay},
187 0 );
188 0 push @{$self->{clients}->{$cid}->{inmessages}}, \%inmsg;
189 0 $self->{clients}->{$cid}->{buffer} = '';
190 } else {
191 0 $self->{clients}->{$cid}->{buffer} .= $buf;
192 }
193 }
194  
195 0 ▶ if($self->{interclackslock} && !$self->{clients}->{$cid}->{interclacksclient}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"interclackslock"} and not $self->{"clients"}{$cid}{"interclacksclient"}) 0 0 0
Condition0%0/3
$self->{"interclackslock"} and not $self->{"clients"}{$cid}{"interclacksclient"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"interclackslock"} and not $self->{"clients"}{$cid}{"interclacksclient"}
$self->{"interclackslock"} not $self->{"clients"}{$cid}{"interclacksclient"}
Truth table0%0/3
A and not(B)
A= $self->{"interclackslock"}B= not $self->{"clients"}{$cid}{"interclacksclient"}
ABresult
0X0
100
111
196 # We are locked into interclacks sync lock, but this is not the connection to master,
197 # so we don't handle the input buffer for this client at the moment.
198 0 next;
199 }
200  
201  
202 0 ▶ while(scalar @{$self->{clients}->{$cid}->{inmessages}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$self->{"clients"}{$cid}{"inmessages"};}) 0 0 0
203 0 ▶ last if($self->{clients}->{$cid}->{inmessages}->[0]->{releasetime} > $now);
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"clients"}{$cid}{"inmessages"}[0]{"releasetime"} > $now 0 0 0
204 0 my $inmsgtmp = shift @{$self->{clients}->{$cid}->{inmessages}};
205 0 my $inmsg = $inmsgtmp->{message};
206  
207 # Handle CLACKS identification header
208 0 ▶ if($inmsg =~ /^CLACKS\ (.+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inmsg =~ /^CLACKS\ (.+)/u) 0 0 0
209 0 $self->{clients}->{$cid}->{clientinfo} = $1;
210 0 $self->{clients}->{$cid}->{clientinfo} =~ s/\;/\_/g;
211 0 print "Client at ", $cid, " identified as ", $self->{clients}->{$cid}->{clientinfo}, "\n";
212 0 next;
213 }
214  
215 0 $self->{nodebug} = 0;
216 0 $self->{sendinterclacks} = 1;
217 0 $self->{discardafterlogging} = 0;
218 # Handle OVERHEAD messages before logging (for handling 'N' flag correctly)
219 0 $self->_handleMessageOverhead($cid, $inmsg);
220  
221 # Ignore other command when not authenticated
222 0 ▶ if(!$self->{clients}->{$cid}->{authok}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"clients"}{$cid}{"authok"}) 0 0 0
223 0 next;
224 }
225  
226 0 ▶ if(!$self->{nodebug}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"nodebug"}) 0 0 0
227 # Add ALL incoming messages as debug-type messages to the outbox
228 0 my %tmp = (
229 sender => $cid,
230 type => 'DEBUG',
231 data => $inmsg,
232 );
233  
234 0 push @{$self->{outbox}}, \%tmp;
235 }
236  
237 0 ▶ if($self->{discardafterlogging}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"discardafterlogging"}) 0 0 0
238 0 next;
239 }
240  
241  
242  
243 0 ▶ if($inmsg =~ /^OVERHEAD\ /) {
Branch: 4 branches
BranchTrueFalseTotal
if ($inmsg =~ /^OVERHEAD\ /u) { } 0 0 0
elsif ($self->_handleMessageDirect($cid, $inmsg)) { } 0 0 0
elsif ($self->_handleMessageCaching($cid, $inmsg)) { } 0 0 0
elsif ($self->_handleMessageControl($cid, $inmsg)) { } 0 0 0
244 # Already handled
245 0 next;
246 } elsif($self->_handleMessageDirect($cid, $inmsg)) {
247 # Fallthrough
248 } elsif($self->_handleMessageCaching($cid, $inmsg)) {
249 # Fallthrough
250 } elsif($self->_handleMessageControl($cid, $inmsg)) {
251 # Fallthrough
252 # local managment commands
253 } else {
254 0 print STDERR "ERROR Unknown_command ", $inmsg, "\r\n";
255 0 $self->{sendinterclacks} = 0;
256 0 $self->{clients}->{$cid}->{outbuffer} .= "OVERHEAD E unknown_command " . $inmsg . "\r\n";
257 }
258  
259 # forward interclacks messages
260 0 ▶ if($self->{sendinterclacks}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"sendinterclacks"}) 0 0 0
261 0 foreach my $interclackscid (keys %{$self->{clients}}) {
262 0 ▶ if($cid eq $interclackscid || !$self->{clients}->{$interclackscid}->{interclacks}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cid eq $interclackscid or not $self->{"clients"}{$interclackscid}{"interclacks"}) 0 0 0
Condition0%0/3
$cid eq $interclackscid or not $self->{"clients"}{$interclackscid}{"interclacks"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$cid eq $interclackscid or not $self->{"clients"}{$interclackscid}{"interclacks"}
$cid eq $interclackscid not $self->{"clients"}{$interclackscid}{"interclacks"}
Truth table0%0/3
A or not(B)
A= $cid eq $interclackscidB= not $self->{"clients"}{$interclackscid}{"interclacks"}
ABresult
1X1
011
000
263 0 next;
264 }
265 0 $self->{clients}->{$interclackscid}->{outbuffer} .= $inmsg . "\r\n";
266 }
267 }
268  
269 }
270  
271 }
272  
273 # Clean up algorithm, only run every so often
274 0 ▶ if($self->{nextcachecleanup} < $now) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"nextcachecleanup"} < $now) 0 0 0
275 0 $self->_cacheCleanup();
276 0 $self->{nextcachecleanup} = $now + $self->{config}->{cachecleaninterval};
277  
278 }
279  
280 0 $self->_outboxToClientBuffer();
281 0 $self->_clientOutput();
282  
283 0 return $self->{workCount};
284 }
285  
286 ▶sub runShutdown($self) {
Subroutine runShutdown: not called CC=3 SCAR=24.8
Pod documented
287 0 print "Shutting down...\n";
288  
289 # Make sure we save the latest version of the persistance file
290 0 $self->_savePersistanceFile();
291  
292 0 sleep(0.5);
293 0 foreach my $cid (keys %{$self->{clients}}) {
294 0 print "Removing client $cid\n";
295 # Try to notify the client (may or may not work);
296 0 $self->_evalsyswrite($self->{clients}->{$cid}->{socket}, "\r\nQUIT\r\n");
297  
298 # Remove from the selector AND explicitly close — relying on Perl GC was
299 # leaving handles (and thus OS file descriptors) alive whenever IO::Select
300 # still held a reference, particularly for IO::Socket::SSL handles.
301 0 eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
302 0 $self->{selector}->remove($self->{clients}->{$cid}->{socket});
303 };
304 0 $self->_safeCloseSocket($self->{clients}->{$cid}->{socket});
305 0 delete $self->{clients}->{$cid};
306 }
307 0 print "All clients removed\n";
308  
309 # Close the listening sockets too so the next process can re-bind without
310 # waiting for the kernel to release the port / unix-socket inode.
311 0 foreach my $listener (@{$self->{tcpsockets}}) {
312 0 $self->_safeCloseSocket($listener);
313 }
314 0 $self->{tcpsockets} = [];
315  
316 0 return;
317 }
318  
319 ▶sub _saveDebugFile($self) {
Subroutine _saveDebugFile: not called CC=3 SCAR=24.8
320 0 ▶ if(defined($self->{config}->{debugfile})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"config"}{"debugfile"}) 0 0 0
321 0 ▶ if(open(my $ofh, '>', $self->{config}->{debugfile})) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $ofh, ">", $self->{"config"}{"debugfile"}) 0 0 0
322 0 print $ofh Dumper($self->{clients});
323 0 close $ofh;
324 }
325 }
326 0 return;
327 }
328  
329 ▶sub _savePersistanceFile($self) {
Subroutine _savePersistanceFile: not called CC=4 SCAR=30.0
330 0 ▶ if(!$self->{persistance}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"persistance"}) 0 0 0
331 0 return;
332 }
333  
334 0 print "Saving persistance file\n";
335  
336 0 my $tempfname = $self->{config}->{persistancefile} . '_';
337 0 my $backfname = $self->{config}->{persistancefile} . '_bck';
338 0 ▶ if($self->{savecache} == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"savecache"} == 1) 0 0 0
339 # Normal savecache operation only
340 0 copy($self->{config}->{persistancefile}, $backfname);
341 }
342  
343 0 my $persistancedata = chr(0) . 'CLACKSV3' . Dump($self->{cache}) . chr(0) . 'CLACKSV3';
344 0 $self->_writeBinFile($tempfname, $persistancedata);
345 0 move($tempfname, $self->{config}->{persistancefile});
346  
347 0 ▶ if($self->{savecache} == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"savecache"} == 2) 0 0 0
348 # Need to make sure we have a valid backup file, since we had a general problem while loading
349 0 copy($self->{config}->{persistancefile}, $backfname);
350 }
351  
352 0 return;
353 }
354  
355 ▶sub _evalsyswrite($self, $socket, $buffer) {
Subroutine _evalsyswrite: not called CC=4 SCAR=30.0
356 0 ▶ return false unless(length($buffer));
Branch: 1 branch
BranchTrueFalseTotal
unless length $buffer 0 0 0
357  
358 0 my $written = 0;
359 0 my $ok = 0;
360 0 eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
361 0 $written = syswrite($socket, $buffer);
362 0 $ok = 1;
363 };
364 0 ▶ if($EVAL_ERROR || !$ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Net::Clacks::Server::EVAL_ERROR or not $ok) 0 0 0
Condition0%0/3
$Net::Clacks::Server::EVAL_ERROR or not $ok
l!l&&r!l&&!r
000
MC/DC0%0/2
$Net::Clacks::Server::EVAL_ERROR or not $ok
$Net::Clacks::Server::EVAL_ERROR not $ok
Truth table0%0/3
A or not(B)
A= $Net::Clacks::Server::EVAL_ERRORB= not $ok
ABresult
1X1
011
000
365 0 print STDERR "Write error: $EVAL_ERROR\n";
366 0 return -1;
367 }
368  
369 0 return $written;
370 }
371  
372 ▶sub _getTime($self) {
Subroutine _getTime: not called CC=1 SCAR=6.9
373 0 my $now = time + $self->{timeoffset};
374  
375 0 return $now;
376 }
377  
378 # Returns a process-monotonic serial number used to make client CIDs unique.
379 ▶sub _nextClientSerial($self) {
Subroutine _nextClientSerial: not called CC=1 SCAR=6.9
380 0 $self->{clientSerial}++;
381 0 return $self->{clientSerial};
382 }
383  
384 # Best-effort socket close that never throws. SSL sockets get SSL_no_shutdown so
385 # we don't block trying to send a TLS close_notify to a peer that's already gone.
386 ▶sub _safeCloseSocket($self, $socket) {
Subroutine _safeCloseSocket: not called CC=3 SCAR=24.8
387 0 ▶ return if(!defined($socket));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $socket 0 0 0
388 0 eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
389 0 ▶ if(ref($socket) =~ /^IO::Socket::SSL/) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref($socket) =~ /^IO::Socket::SSL/u) { } 0 0 0
390 0 $socket->close(SSL_no_shutdown => 1, SSL_fast_shutdown => 1);
391 } else {
392 0 $socket->close;
393 }
394 };
395 0 return;
396 }
397  
398 ▶sub _slurpBinFile($self, $fname) {
Subroutine _slurpBinFile: not called CC=2 SCAR=17.9
399 # Read in file in binary mode, slurping it into a single scalar.
400 # We have to make sure we use binmode *and* turn on the line termination variable completly
401 # to work around the multiple idiosynchrasies of Perl on Windows
402 0 ▶ open(my $fh, "<", $fname) or croak($ERRNO);
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $fname or croak($Net::Clacks::Server::ERRNO) 0 0 0
403 0 local $INPUT_RECORD_SEPARATOR = undef;
404 0 binmode($fh);
405 0 my $data = <$fh>;
406 0 close($fh);
407  
408 0 return $data;
409 }
410  
411 ▶sub _writeBinFile($self, $fname, $data) {
Subroutine _writeBinFile: not called CC=2 SCAR=17.9
412 # Write file in binmode
413 # We have to make sure we use binmode *and* turn on the line termination variable completly
414 # to work around the multiple idiosynchrasies of Perl on Windows
415 0 ▶ open(my $fh, ">", $fname) or croak($ERRNO);
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $fname or croak($Net::Clacks::Server::ERRNO) 0 0 0
416 0 local $INPUT_RECORD_SEPARATOR = undef;
417 0 binmode($fh);
418 0 print $fh $data;
419 0 close($fh);
420  
421 0 return true;
422 }
423  
424 ▶sub _restorePersistanceFile($self) {
Subroutine _restorePersistanceFile: not called CC=9 SCAR=45.0
425 0 my $previousfname = $self->{config}->{persistancefile} . '_bck';
426 0 my $tempfname = $self->{config}->{persistancefile} . '_';
427 0 my $loadok = 0;
428 0 ▶ if(-f $self->{config}->{persistancefile}) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $self->{"config"}{"persistancefile"}) 0 0 0
429 0 print "Trying to load persistance file ", $self->{config}->{persistancefile}, "\n";
430 0 $loadok = $self->_loadPersistanceFile($self->{config}->{persistancefile});
431 }
432  
433 0 ▶ if(!$loadok && -f $previousfname) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $loadok and -f $previousfname) 0 0 0
Condition0%0/3
not $loadok and -f $previousfname
!ll&&!rl&&r
000
MC/DC0%0/2
not $loadok and -f $previousfname
not $loadok -f $previousfname
Truth table0%0/3
not(A) and B
A= not $loadokB= -f $previousfname
ABresult
0X0
100
111
434 0 print "Trying to load backup (previous) persistance file ", $previousfname, "\n";
435 0 $loadok = $self->_loadPersistanceFile($previousfname);
436 0 ▶ if($loadok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($loadok) 0 0 0
437 0 $self->{savecache} = 2; # Force saving a new persistance file plus a new backup
438 }
439 }
440 0 ▶ if(!$loadok && -f $tempfname) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $loadok and -f $tempfname) 0 0 0
Condition0%0/3
not $loadok and -f $tempfname
!ll&&!rl&&r
000
MC/DC0%0/2
not $loadok and -f $tempfname
not $loadok -f $tempfname
Truth table0%0/3
not(A) and B
A= not $loadokB= -f $tempfname
ABresult
0X0
100
111
441 0 print "Oh no. As a final, desperate solution, trying to load a 'temporary file while saving' persistance file ", $tempfname, "\n";
442 0 $loadok = $self->_loadPersistanceFile($tempfname);
443 0 ▶ if($loadok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($loadok) 0 0 0
444 0 $self->{savecache} = 2; # Force saving a new persistance file plus a new backup
445 }
446 }
447  
448 0 ▶ if(!$loadok) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $loadok) { } 0 0 0
449 0 print "Sorry, no valid persistance file found. Starting server 'blankety-blank'\n";
450 0 $self->{savecache} = 2;
451 } else {
452 0 print "Persistance file loaded\n";
453 }
454
455 0 return;
456 }
457  
458 ▶sub _init($self) {
Subroutine _init: not called CC=60 SCAR=81.7
459 0 ▶ if(defined($self->{initHasRun}) && $self->{initHasRun}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"initHasRun"} and $self->{"initHasRun"}) 0 0 0
Condition0%0/3
defined $self->{"initHasRun"} and $self->{"initHasRun"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"initHasRun"} and $self->{"initHasRun"}
defined $self->{"initHasRun"} $self->{"initHasRun"}
Truth table0%0/3
A and B
A= defined $self->{"initHasRun"}B= $self->{"initHasRun"}
ABresult
0X0
100
111
460 # NOT ALLOWED!
461 0 croak("Multiple calls to _init() are not allowed!");
462 }
463  
464 0 my @paths;
465 0 ▶ if(defined($ENV{'PC_CONFIG_PATHS'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{'PC_CONFIG_PATHS'}) { } 0 0 0
466 0 push @paths, split/\:/, $ENV{'PC_CONFIG_PATHS'};
467 0 print "Found config paths:\n", Dumper(\@paths), " \n";
468 } else {
469 0 print("PC_CONFIG_PATHS undefined, falling back to legacy mode\n");
470 0 @paths = ('', 'configs/');
471 }
472  
473 0 my $filedata;
474 0 my $fname = $self->{configfile};
475 0 foreach my $path (@paths) {
476 0 ▶ if($path ne '' && $path !~ /\/$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path ne "" and not $path =~ m[/$]u) 0 0 0
Condition0%0/3
$path ne "" and not $path =~ m[/$]u
!ll&&!rl&&r
000
MC/DC0%0/2
$path ne "" and not $path =~ m[/$]u
$path ne "" not $path =~ m[/$]u
Truth table0%0/3
A and not(B)
A= $path ne ""B= not $path =~ m[/$]u
ABresult
0X0
100
111
477 0 $path .= '/';
478 }
479 0 my $fullfname = $path . $fname;
480 0 ▶ next unless (-f $fullfname);
Branch: 1 branch
BranchTrueFalseTotal
unless -f $fullfname 0 0 0
481 0 print " Loading config file $fullfname\n";
482  
483 0 $filedata = $self->_slurpBinFile($fullfname);
484  
485 0 foreach my $varname (keys %ENV) {
486 0 ▶ next unless $varname =~ /^PC\_/;
Branch: 1 branch
BranchTrueFalseTotal
unless $varname =~ /^PC\_/u 0 0 0
487  
488 0 my $newval = $ENV{$varname};
489 0 $filedata =~ s/$varname/$newval/g;
490 }
491  
492 0 last;
493 }
494  
495 0 ▶ if(!defined($filedata) || $filedata eq "") {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $filedata or $filedata eq "") 0 0 0
Condition0%0/3
not defined $filedata or $filedata eq ""
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $filedata or $filedata eq ""
not defined $filedata $filedata eq ""
Truth table0%0/3
not(A) or B
A= not defined $filedataB= $filedata eq ""
ABresult
1X1
011
000
496 0 croak("Can't load config file: Not found or empty!");
497 }
498  
499 0 print "------- Parsing config file $fname ------\n";
500 0 my $config = XMLin($filedata, ForceArray => [ 'ip', 'socket', 'user', 'item' ]);
501  
502 0 my $hname = hostname;
503  
504 # Copy hostname-specific stuff to root if it exists
505 0 ▶ if(defined($config->{hosts}->{$hname})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{"hosts"}{$hname}) 0 0 0
506 0 foreach my $key (keys %{$config->{hosts}->{$hname}}) {
507 0 $config->{$key} = $config->{hosts}->{$hname}->{$key};
508 }
509 }
510  
511 0 $self->{config} = $config;
512  
513 0 ▶ if(!defined($self->{config}->{throttle}->{maxsleep})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"throttle"}{"maxsleep"}) 0 0 0
514 0 $self->{config}->{throttle}->{maxsleep} = 100;
515 }
516 0 ▶ if(!defined($self->{config}->{throttle}->{step})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"throttle"}{"step"}) 0 0 0
517 0 $self->{config}->{throttle}->{step} = 10;
518 }
519  
520 0 $self->{usleep} = 0;
521  
522 0 ▶ if(defined($config->{ip})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{"ip"}) 0 0 0
523 # SSL only needed for TCP. Unix domain sockets are unencrypted
524 0 ▶ if(!defined($self->{config}->{ssl}) ||
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"ssl"} and defined $self->{"config"}{"ssl"}{"cert"} and defined $self->{"config"}{"ssl"}{"key"}) 0 0 0
Condition0%0/6
defined $self->{"config"}{"ssl"} and defined $self->{"config"}{"ssl"}{"cert"} and defined $self->{"config"}{"ssl"}{"key"}
!ll&&!rl&&r
000
defined $self->{"config"}{"ssl"} and defined $self->{"config"}{"ssl"}{"cert"}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $self->{"config"}{"ssl"} and defined $self->{"config"}{"ssl"}{"cert"} and defined $self->{"config"}{"ssl"}{"key"}
defined $self->{"config"}{"ssl"} defined $self->{"config"}{"ssl"}{"cert"} defined $self->{"config"}{"ssl"}{"key"}
Truth table0%0/4
A and B and C
A= defined $self->{"config"}{"ssl"}B= defined $self->{"config"}{"ssl"}{"cert"}C= defined $self->{"config"}{"ssl"}{"key"}
ABCresult
0XX0
10X0
1100
1111
525 !defined($self->{config}->{ssl}->{cert}) ||
526 !defined($self->{config}->{ssl}->{key})) {
527 0 croak("Missing or incomplete SSL config!");
528 }
529 0 ▶ if(!-f $self->{config}->{ssl}->{cert}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $self->{"config"}{"ssl"}{"cert"}) 0 0 0
530 0 croak("SSL cert file " . $self->{config}->{ssl}->{cert} . " not found!");
531 }
532 0 ▶ if(!-f $self->{config}->{ssl}->{key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $self->{"config"}{"ssl"}{"key"}) 0 0 0
533 0 croak("SSL key file " . $self->{config}->{ssl}->{key} . " not found!");
534 }
535 }
536  
537 0 ▶ if(!defined($self->{config}->{username})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"username"}) 0 0 0
538 0 croak("Username not defined!");
539 }
540 0 ▶ if(!defined($self->{config}->{password})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"password"}) 0 0 0
541 0 croak("Password not defined!");
542 }
543 0 $self->{authtoken} = encode_base64($self->{config}->{username}, '') . ':' . encode_base64($self->{config}->{password}, '');
544  
545 # Add authtoken to the list of authorized users, giving it full permissions
546 0 $self->{userlist} = {};
547 $self->{userlist}->{$self->{authtoken}} = {
548 0 read => 1,
549 write => 1,
550 manage => 1,
551 interclacks => 1,
552 };
553  
554 # Configure additional users. They can NOT be used for interclacks connections, only the default user can
555 0 ▶ if(defined($self->{config}->{user})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"config"}{"user"}) 0 0 0
556 0 foreach my $user (@{$self->{config}->{user}}) {
557 0 ▶ if(!defined($user->{username}) || !defined($user->{password})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $user->{"username"} and defined $user->{"password"}) 0 0 0
Condition0%0/3
defined $user->{"username"} and defined $user->{"password"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $user->{"username"} and defined $user->{"password"}
defined $user->{"username"} defined $user->{"password"}
Truth table0%0/3
A and B
A= defined $user->{"username"}B= defined $user->{"password"}
ABresult
0X0
100
111
558 0 croak("User config is missing username/password");
559 }
560 0 my $authtoken = encode_base64($user->{username}, '') . ':' . encode_base64($user->{password}, '');
561 0 $self->{userlist}->{$authtoken} = {
562 read => 0,
563 write => 0,
564 manage => 0,
565 interclacks => 0,
566 };
567 0 foreach my $key (qw[read write manage]) {
568 0 ▶ if(defined($user->{$key}) && $user->{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $user->{$key} and $user->{$key}) 0 0 0
Condition0%0/3
defined $user->{$key} and $user->{$key}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $user->{$key} and $user->{$key}
defined $user->{$key} $user->{$key}
Truth table0%0/3
A and B
A= defined $user->{$key}B= $user->{$key}
ABresult
0X0
100
111
569 0 $self->{userlist}->{$authtoken}->{$key} = 1;
570 }
571 }
572 }
573 }
574  
575 0 ▶ if(defined($self->{config}->{persistancefile})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'config'}{'persistancefile'}) { } 0 0 0
576 0 $self->{persistance} = 1;
577 } else {
578 0 $self->{persistance} = 0;
579 }
580  
581 0 ▶ if(!defined($self->{config}->{persistanceinterval})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{'config'}{'persistanceinterval'}) { } 0 0 0
582 0 $self->{persistanceinterval} = 10;
583 } else {
584 0 $self->{persistanceinterval} = $self->{config}->{persistanceinterval};
585 }
586  
587 0 ▶ if(!defined($self->{config}->{interclacksreconnecttimeout})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"interclacksreconnecttimeout"}) 0 0 0
588 0 $self->{config}->{interclacksreconnecttimeout} = 30;
589 }
590  
591 0 ▶ if(!defined($self->{config}->{authtimeout})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"authtimeout"}) 0 0 0
592 0 $self->{config}->{authtimeout} = 15;
593 }
594  
595 # Sensible safety-net defaults so that a config which omits these still
596 # disconnects hung peers instead of leaking FDs forever. Operators should
597 # still set explicit values in their config; these only protect against
598 # accidental omission.
599 0 ▶ if(!defined($self->{config}->{pingtimeout})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"pingtimeout"}) 0 0 0
600 0 $self->{config}->{pingtimeout} = 180;
601 }
602 0 ▶ if(!defined($self->{config}->{interclackspingtimeout})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"interclackspingtimeout"}) 0 0 0
603 0 $self->{config}->{interclackspingtimeout} = 60;
604 }
605  
606 0 ▶ if(!defined($self->{config}->{deletedcachetime})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"deletedcachetime"}) 0 0 0
607 0 $self->{config}->{deletedcachetime} = 60 * 60; # 1 hour
608 }
609 0 ▶ if(!defined($self->{config}->{stalecachetime})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"stalecachetime"}) 0 0 0
610 0 $self->{config}->{stalecachetime} = 60 * 60 * 24; # 1 day
611 }
612  
613 0 ▶ if(!defined($self->{config}->{cachecleaninterval})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"cachecleaninterval"}) 0 0 0
614 0 $self->{config}->{cachecleaninterval} = 60; # 1 minute
615 }
616  
617 0 ▶ if(!defined($self->{config}->{readfailtimeout})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"readfailtimeout"}) 0 0 0
618 0 $self->{config}->{readfailtimeout} = 30; # 30 seconds - matches pingtimeout default
619 }
620  
621 0 ▶ if(!defined($self->{config}->{interclacksreadfailtimeout})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"interclacksreadfailtimeout"}) 0 0 0
622 0 $self->{config}->{interclacksreadfailtimeout} = 60; # 60 seconds for interclacks (higher latency)
623 }
624  
625 # Stalled-write detection: how long we'll keep a client around when we have
626 # data we want to send to them but every syswrite() returns EAGAIN (or 0
627 # bytes) — i.e., the kernel's send buffer is full and the peer isn't
628 # draining it. Distinct from readfailtimeout (which catches "selector says
629 # readable but no data") and pingtimeout (which the client can disable via
630 # NOPING). This one cannot be disabled by NOPING because it doesn't depend
631 # on the client sending us anything; it triggers when we cannot deliver
632 # data we already have queued.
633 0 ▶ if(!defined($self->{config}->{stalledwritetimeout})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"stalledwritetimeout"}) 0 0 0
634 0 $self->{config}->{stalledwritetimeout} = 60;
635 }
636 0 ▶ if(!defined($self->{config}->{interclacksstalledwritetimeout})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"config"}{"interclacksstalledwritetimeout"}) 0 0 0
637 0 $self->{config}->{interclacksstalledwritetimeout} = 120; # interclacks links may have higher latency
638 }
639  
640 # Init run() variables
641 0 $self->{savecache} = 0;
642 0 $self->{lastsavecache} = 0;
643 0 $self->{outbox} = [];
644 0 $self->{toremove} = [];
645 0 $self->{clients} = {};
646 0 $self->{shutdowntime} = 0;
647 0 $self->{selector} = IO::Select->new();
648 0 $self->{interclackslock} = 0;
649 0 $self->{nextinterclackscheck} = 0;
650 0 $self->{keepRunning} = 1;
651 0 $self->{nextcachecleanup} = 0;
652 0 $self->{initHasRun} = 1;
653 # Process-monotonic serial used to make every accepted client's CID unique,
654 # even when the kernel reuses ephemeral ports or many connections arrive in
655 # the same wall-clock second.
656 0 $self->{clientSerial} = 0;
657  
658 0 my @tcpsockets;
659  
660 0 ▶ if(defined($config->{ip})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{"ip"}) 0 0 0
661 0 ▶ if(!defined($config->{port})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $config->{"port"}) 0 0 0
662 0 croak("At least one IP defined, but no TCP port!");
663 }
664 0 foreach my $ip (@{$config->{ip}}) {
665 my $tcp = IO::Socket::IP->new(
666 LocalHost => $ip,
667 LocalPort => $config->{port},
668 0 ▶ Listen => 128, # Larger backlog so a burst of connects doesn't get rejected before the accept-drain loop runs
Branch: 1 branch
BranchTrueFalseTotal
my $tcp = "IO::Socket::IP"->new("LocalHost", $ip, "LocalPort", $config->{"port"}, "Listen", 128, "Blocking", 0, "ReuseAddr", 1, "Proto", "tcp") or croak($Net::Clacks::Server::ERRNO) 0 0 0
669 Blocking => 0,
670 ReuseAddr => 1,
671 Proto => 'tcp',
672 ) or croak($ERRNO);
673 #binmode($tcp, ':bytes');
674 0 push @tcpsockets, $tcp;
675 0 print "Listening on $ip:", $config->{port}, "/tcp\n";
676 }
677 }
678  
679 0 ▶ if(defined($config->{socket}) || defined($self->{config}->{master}->{socket})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{"socket"} or defined $self->{"config"}{"master"}{"socket"}) 0 0 0
Condition0%0/3
defined $config->{"socket"} or defined $self->{"config"}{"master"}{"socket"}
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $config->{"socket"} or defined $self->{"config"}{"master"}{"socket"}
defined $config->{"socket"} defined $self->{"config"}{"master"}{"socket"}
Truth table0%0/3
A or B
A= defined $config->{"socket"}B= defined $self->{"config"}{"master"}{"socket"}
ABresult
1X1
011
000
680 0 my $udsloaded = 0;
681 0 eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
682 0 require IO::Socket::UNIX;
683 0 $udsloaded = 1;
684 };
685 0 ▶ if(!$udsloaded) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($udsloaded) 0 0 0
686 0 croak("Specified a unix domain socket, but i couldn't load IO::Socket::UNIX!");
687 }
688  
689 # Add the ClientID stuff to Unix domain sockets as well. We don't do this in the BEGIN{} block
690 # since we are not yet sure we are going to load IO::Socket::UNIX in the first place
691 {
692 4 ▶ no strict 'refs'; ## no critic (TestingAndDebugging::ProhibitNoStrict)
Subroutine BEGIN: called CC=1 SCAR=0.2
693 0 *{"IO::Socket::UNIX::_setClientID"} = sub {
694 0 ▶ my ($self, $cid) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
695
696 0 ${*$self}{'__client_id'} = $cid; ## no critic (References::ProhibitDoubleSigils)
697 0 return;
698 0 };
699
700 0 *{"IO::Socket::UNIX::_getClientID"} = sub {
701 0 ▶ my ($self) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
702
703 0 ▶ return ${*$self}{'__client_id'} || ''; ## no critic (References::ProhibitDoubleSigils)
Condition0%0/2
do { *$self }->{'__client_id'} || ''
l!l
00
MC/DC0%0/1
do { *$self }->{'__client_id'} || ''
do { *$self }->{'__client_id'}
Truth table0%0/2
A
A= do { *$self }->{'__client_id'}
Aresult
11
00
704 0 };
705 }
706 }
707  
708 0 ▶ if(defined($config->{socket})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{"socket"}) 0 0 0
709 0 foreach my $socket (@{$config->{socket}}) {
710 0 ▶ if(-S $socket) {
Branch: 1 branch
BranchTrueFalseTotal
if (-S $socket) 0 0 0
711 0 print "Removing old unix domain socket file $socket\n";
712 0 unlink $socket;
713 }
714 0 ▶ my $tcp = IO::Socket::UNIX->new(
Branch: 1 branch
BranchTrueFalseTotal
my $tcp = "IO::Socket::UNIX"->new("Type", 1, "Local", $socket, "Listen", 128) or croak($Net::Clacks::Server::ERRNO) 0 0 0
715 Type => SOCK_STREAM(),
716 Local => $socket,
717 Listen => 128, # Larger backlog so a burst of connects doesn't get rejected before the accept-drain loop runs
718 #Blocking => 0,
719 ) or croak($ERRNO);
720 0 $tcp->blocking(0);
721 #binmode($tcp, ':bytes');
722 0 push @tcpsockets, $tcp;
723 0 print "Listening on Unix domain socket $socket\n";
724  
725 0 ▶ if(defined($config->{socketchmod}) && $config->{socketchmod} ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{"socketchmod"} and $config->{"socketchmod"} ne "") 0 0 0
Condition0%0/3
defined $config->{"socketchmod"} and $config->{"socketchmod"} ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $config->{"socketchmod"} and $config->{"socketchmod"} ne ""
defined $config->{"socketchmod"} $config->{"socketchmod"} ne ""
Truth table0%0/3
A and B
A= defined $config->{"socketchmod"}B= $config->{"socketchmod"} ne ""
ABresult
0X0
100
111
726 0 my $cmd = 'chmod ' . $config->{socketchmod} . ' ' . $socket;
727 0 print $cmd, "\n";
728 0 `$cmd`;
729 }
730  
731 0 ▶ if(defined($config->{socketcommands})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{"socketcommands"}) 0 0 0
732 0 foreach my $cmd (@{$config->{socketcommands}->{item}}) {
733 0 print "Running Socket command: $cmd\n";
734 0 `$cmd`;
735 }
736 }
737 }
738 }
739  
740 0 $self->{tcpsockets} = \@tcpsockets;
741  
742 # Need to ignore SIGPIPE, this can screw us over in certain circumstances
743 # while writing to the network. We can only detect certain types of disconnects
744 # after writing to the socket, but we will get a SIGPIPE if we try. So we just
745 # ignore the signal and carry on as usual...
746 0 $SIG{PIPE} = 'IGNORE';
747  
748  
749 # Weaken the captured $self so the signal handlers don't keep the server hash
750 # alive for the rest of the process. Without weakening, the closures stored in
751 # %SIG hold a strong reference to $self, which prevents GC of the top-level
752 # container even after the caller drops its reference. Inner contents (clients,
753 # sockets, cache) are unaffected either way; this only matters when a process
754 # creates/discards multiple Server instances (e.g. a supervised reload).
755 0 my $weakself = $self;
756 0 weaken($weakself);
757 0 ▶ $SIG{INT} = sub { $weakself->{keepRunning} = 0 if(defined($weakself)); };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if defined $weakself 0 0 0
758 0 ▶ $SIG{TERM} = sub { $weakself->{keepRunning} = 0 if(defined($weakself)); };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if defined $weakself 0 0 0
759  
760 # Restore persistance file if required
761 0 ▶ if($self->{persistance}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"persistance"}) 0 0 0
762 0 $self->_restorePersistanceFile();
763 }
764  
765 0 print "Ready.\n";
766  
767  
768 0 return;
769 }
770  
771 ▶sub _loadPersistanceFile($self, $fname) {
Subroutine _loadPersistanceFile: not called CC=10 SCAR=47.0
772 0 my $alreadyupgraded = 0;
773  
774 retry:
775 0 ▶ if(!-f $fname) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $fname) 0 0 0
776 # Does not exist
777 0 carp("$fname not found");
778 0 return false;
779 }
780  
781 0 my $data = $self->_slurpBinFile($fname);
782 0 ▶ if(length($data) < 11) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $data < 11) 0 0 0
783 0 carp("$fname too small");
784 # Invalid file
785 0 return false;
786 }
787 0 ▶ if(substr($data, 0, 9) ne chr(0) . 'CLACKSV3') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($data, 0, 9) ne "\0CLACKSV3") 0 0 0
788 0 ▶ if($alreadyupgraded) {
Branch: 1 branch
BranchTrueFalseTotal
if ($alreadyupgraded) 0 0 0
789 0 carp("Upgrade resulted in invalog file (wrong prefix)");
790 # Something went wrong with inplace upgrade
791 0 return;
792 }
793 0 $alreadyupgraded = 1;
794 0 ▶ if(!$self->_inplaceUpgrade($fname)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_inplaceUpgrade($fname)) 0 0 0
795 0 carp("Inplace upgrade failed");
796 # Could not upgrade
797 0 return false;
798 }
799 0 goto retry;
800 }
801  
802 0 ▶ if(length($data) < 18) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $data < 18) 0 0 0
803 0 carp("Incomplete V3 persistance file " . $fname . " (too small)!");
804 0 return false;
805 }
806  
807 0 substr($data, 0, 9, ''); # Remove header
808  
809 0 ▶ if(substr($data, -9, 9) ne chr(0) . 'CLACKSV3') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($data, -9, 9) ne "\0CLACKSV3") 0 0 0
810 # Missing end bytes
811 0 carp("Incomplete V3 persistance file " . $fname . " (missing end bytes)!");
812 0 return false; # Fail
813 }
814 0 substr($data, -9, 9, ''); # Remove end bytes
815  
816 0 $self->{cache} = {};
817 0 ▶ if(length($data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $data) 0 0 0
818 0 my $loadok = 0;
819 0 eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
820 0 $self->{cache} = Load($data);
821 0 $loadok = 1;
822 };
823 0 ▶ if(!$loadok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($loadok) 0 0 0
824 0 carp("Invalid V3 persistance file " . $fname . "!");
825 0 return false; # Fail
826 }
827 }
828  
829 0 return true;
830 }
831  
832 ▶sub _inplaceUpgrade($self, $fname) {
Subroutine _inplaceUpgrade: not called CC=23 SCAR=63.1
833 0 my %clackscache;
834 my %clackscachetime;
835 0 my %clackscacheaccesstime;
836  
837 0 print "Inplace-upgrading persistance file $fname...\n";
838  
839 0 my $now = $self->_getTime();
840  
841 # Use old loader algorithm to load file
842 0 ▶ if(open(my $ifh, '<', $fname)) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $ifh, '<', $fname) { } 0 0 0
843 0 my $line = <$ifh>;
844 0 my $timestampline = <$ifh>;
845 0 my $accesstimeline = <$ifh>;
846 0 my $endline = <$ifh>;
847 0 my $needupgrade = 0;
848 0 close $ifh;
849  
850 0 chomp $line;
851 0 chomp $timestampline;
852 0 chomp $accesstimeline;
853  
854 0 ▶ if(!defined($endline) && $accesstimeline eq 'ENDBYTES') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $endline and $accesstimeline eq 'ENDBYTES') { } 0 0 0
Condition0%0/3
not defined $endline and $accesstimeline eq "ENDBYTES"
!ll&&!rl&&r
000
MC/DC0%0/2
not defined $endline and $accesstimeline eq "ENDBYTES"
not defined $endline $accesstimeline eq "ENDBYTES"
Truth table0%0/3
not(A) and B
A= not defined $endlineB= $accesstimeline eq "ENDBYTES"
ABresult
0X0
100
111
855 0 $endline = 'ENDBYTES';
856 0 $accesstimeline = '';
857 0 $needupgrade = 1;
858 } else {
859 0 chomp $endline;
860 }
861  
862 0 ▶ if(!defined($line) || !defined($timestampline) || $endline ne 'ENDBYTES') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $line && defined $timestampline or $endline ne "ENDBYTES") 0 0 0
Condition0%0/6
not defined $line && defined $timestampline or $endline ne "ENDBYTES"
l!l&&r!l&&!r
000
defined $line && defined $timestampline
!ll&&!rl&&r
000
MC/DC0%0/3
not defined $line && defined $timestampline or $endline ne "ENDBYTES"
defined $line defined $timestampline $endline ne "ENDBYTES"
Truth table0%0/4
not(A && B) or C
A= defined $lineB= defined $timestamplineC= $endline ne "ENDBYTES"
ABCresult
0XX1
10X1
1111
1100
863 0 carp("Invalid persistance file " . $fname . "! File is incomplete!");
864 0 return false; # Fail
865 }
866  
867 0 my $loadok = 0;
868  
869 0 ▶ if($line ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($line ne "") 0 0 0
870 0 eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
871 0 $line = decode_base64($line);
872 0 $line = Load($line);
873 0 $loadok = 1;
874 };
875 0 ▶ if(!$loadok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($loadok) 0 0 0
876 0 carp("Invalid persistance file " . $fname . "! Failed to decode data line!");
877 0 return false; # Fail
878 }
879 }
880 0 %clackscache = %{$line};
881  
882 # Mark all data as current as a fallback
883 0 foreach my $key (keys %clackscache) {
884 0 $clackscachetime{$key} = $now;
885 }
886  
887 0 ▶ if($timestampline ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($timestampline ne "") 0 0 0
888 0 $loadok = 0;
889 0 eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
890 0 $timestampline = decode_base64($timestampline);
891 0 $timestampline = Load($timestampline);
892 0 $loadok = 1;
893 };
894 0 ▶ if(!$loadok) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $loadok) { } 0 0 0
895 0 carp("Invalid persistance file " . $fname . "! Failed to decode timestamp line, using current time!");
896 0 return false; # Fail
897 } else {
898 0 my %clackstemp = %{$timestampline};
899 0 foreach my $key (keys %clackstemp) {
900 0 $clackscachetime{$key} = $clackstemp{$key};
901 }
902 }
903 }
904  
905 0 ▶ if($needupgrade) {
Branch: 2 branches
BranchTrueFalseTotal
if ($needupgrade) { } 0 0 0
elsif ($accesstimeline ne '') { } 0 0 0
906 0 print "Pre-Version 22 persistance file detected. Upgrading automatically.\n";
907 0 foreach my $key (keys %clackscache) {
908 0 $clackscacheaccesstime{$key} = $now;
909 }
910 } elsif($accesstimeline ne '') {
911 0 $loadok = 0;
912 0 eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
913 0 $accesstimeline = decode_base64($accesstimeline);
914 0 $accesstimeline = Load($accesstimeline);
915 0 $loadok = 1;
916 };
917 0 ▶ if(!$loadok) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $loadok) { } 0 0 0
918 0 carp("Invalid persistance file " . $fname . "! Failed to decode timestamp line, using current time!");
919 0 return false; # Fail
920 } else {
921 0 %clackscacheaccesstime = %{$accesstimeline};
922 }
923 }
924 } else {
925 # Fail
926 0 return false;
927 }
928  
929 # Turn into new format
930 0 my %cache;
931 # not-deleted sets
932 0 foreach my $key (keys %clackscache) {
933 0 my $cachetime = $now;
934 0 my $accesstime = $now;
935 0 ▶ if(defined($clackscachetime{$key})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $clackscachetime{$key}) 0 0 0
936 0 $cachetime = $clackscachetime{$key};
937 }
938 0 ▶ if(defined($clackscacheaccesstime{$key})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $clackscacheaccesstime{$key}) 0 0 0
939 0 $accesstime = $clackscacheaccesstime{$key};
940 }
941 $cache{$key} = {
942 0 data => $clackscache{$key},
943 cachetime => $cachetime,
944 accesstime => $accesstime,
945 deleted => 0,
946 };
947 }
948  
949 # deleted sets
950 0 foreach my $key (keys %clackscachetime) {
951 0 ▶ if(defined($cache{$key})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cache{$key}) 0 0 0
952 # not deleted
953 0 next;
954 }
955  
956 0 my $cachetime = $clackscachetime{$key};
957 0 my $accesstime = $now;
958 0 ▶ if(defined($clackscacheaccesstime{$key})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $clackscacheaccesstime{$key}) 0 0 0
959 0 $accesstime = $clackscacheaccesstime{$key};
960 }
961 0 $cache{$key} = {
962 data => '',
963 cachetime => $cachetime,
964 accesstime => $accesstime,
965 deleted => 0,
966 };
967 }
968  
969 0 my $converted = chr(0) . 'CLACKSV3' . Dump(\%cache) . chr(0) . 'CLACKSV3';
970 0 $self->_writeBinFile($fname, $converted);
971  
972 0 print "...upgrade complete.\n";
973  
974 0 return true;
975 }
976  
977 ▶sub _addInterclacksLink($self) {
Subroutine _addInterclacksLink: not called CC=9 SCAR=45.0
978 0 my $now = $self->_getTime();
979  
980 0 my $mcid;
981 0 ▶ if(defined($self->{config}->{master}->{socket})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'config'}{'master'}{'socket'}) { } 0 0 0
982 0 $mcid = 'unixdomainsocket:interclacksmaster';
983 } else {
984 0 $mcid = $self->{config}->{master}->{ip}->[0] . ':' . $self->{config}->{master}->{port};
985 }
986 0 ▶ if(!defined($self->{clients}->{$mcid}) && $self->{nextinterclackscheck} < $now) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"clients"}{$mcid} and $self->{"nextinterclackscheck"} < $now) 0 0 0
Condition0%0/3
not defined $self->{"clients"}{$mcid} and $self->{"nextinterclackscheck"} < $now
!ll&&!rl&&r
000
MC/DC0%0/2
not defined $self->{"clients"}{$mcid} and $self->{"nextinterclackscheck"} < $now
not defined $self->{"clients"}{$mcid} $self->{"nextinterclackscheck"} < $now
Truth table0%0/3
not(A) and B
A= not defined $self->{"clients"}{$mcid}B= $self->{"nextinterclackscheck"} < $now
ABresult
0X0
100
111
987 0 $self->{nextinterclackscheck} = $now + $self->{config}->{interclacksreconnecttimeout} + int(rand(10));
988  
989 0 print "Connect to master\n";
990 0 my $msocket;
991  
992 0 ▶ if(defined($self->{config}->{master}->{socket})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'config'}{'master'}{'socket'}) { } 0 0 0
993 $msocket = IO::Socket::UNIX->new(
994 0 Peer => $self->{config}->{master}->{socket}->[0],
995 Type => SOCK_STREAM,
996 );
997 } else {
998 $msocket = IO::Socket::IP->new(
999 PeerHost => $self->{config}->{master}->{ip}->[0],
1000 PeerPort => $self->{config}->{master}->{port},
1001 0 Type => SOCK_STREAM,
1002 Timeout => 5,
1003 );
1004 }
1005 0 ▶ if(!defined($msocket)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $msocket) { } 0 0 0
1006 0 print STDERR "Can't connect to MASTER via interclacks!\n";
1007 } else {
1008 0 print "connected to master\n";
1009  
1010 0 ▶ if(ref $msocket ne 'IO::Socket::UNIX') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $msocket ne "IO::Socket::UNIX") 0 0 0
1011 # ONLY USE SSL WHEN RUNNING OVER THE NETWORK
1012 # There is simply no point in running it over a local socket.
1013 0 my $encrypted = IO::Socket::SSL->start_SSL($msocket,
1014 SSL_verify_mode => SSL_VERIFY_NONE,
1015 );
1016 0 ▶ if(!$encrypted) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($encrypted) 0 0 0
1017 # Bare `next` was a bug here — there is no enclosing loop. Without an
1018 # explicit close the failed-handshake $msocket leaks a file descriptor.
1019 # Return cleanly; the next reconnect attempt will be scheduled by
1020 # nextinterclackscheck below.
1021 0 print STDERR "startSSL failed (interclacks master): ", $SSL_ERROR, "\n";
1022 0 $self->_safeCloseSocket($msocket);
1023 0 return;
1024 }
1025 }
1026  
1027 0 $msocket->blocking(0);
1028 #binmode($msocket, ':bytes');
1029 my %tmp = (
1030 buffer => '',
1031 charbuffer => [],
1032 listening => {},
1033 socket => $msocket,
1034 lastping => $now,
1035 mirror => 0,
1036 outbuffer => "CLACKS PageCamel $VERSION in interclacks client mode\r\n" . # Tell the server we are using PageCamel Interclacks...
1037 "OVERHEAD A " . $self->{authtoken} . "\r\n" . # ...send Auth token
1038 "OVERHEAD I 1\r\n", # ...and turn interclacks master mode ON on remote side
1039 clientinfo => 'Interclacks link',
1040 client_timeoffset => 0,
1041 interclacks => 1,
1042 interclacksclient => 1,
1043 lastinterclacksping => $now,
1044 lastmessage => $now,
1045 authtimeout => $now + $self->{config}->{authtimeout},
1046 0 authok => 0,
1047 failtime => 0,
1048 writefailtime => 0, # streak-start time for stalled writes; 0 = no streak in progress
1049 outmessages => [],
1050 inmessages => [],
1051 messagedelay => 0,
1052 inmessagedelay => 0,
1053 outmessagedelay => 0,
1054 permissions => {
1055 read => 1,
1056 write => 1,
1057 manage => 1,
1058 interclacks => 1,
1059 },
1060 );
1061  
1062 0 ▶ if(defined($self->{config}->{master}->{ip})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"config"}{"master"}{"ip"}) 0 0 0
1063 0 $tmp{host} = $self->{config}->{master}->{ip}->[0];
1064 0 $tmp{port} = $self->{config}->{master}->{port};
1065 }
1066 0 $self->{clients}->{$mcid} = \%tmp;
1067 0 $msocket->_setClientID($mcid);
1068 0 $self->{selector}->add($msocket);
1069  
1070 0 $self->{workCount}++;
1071 }
1072 }
1073 0 return;
1074 }
1075  
1076 ▶sub _addNewClients($self) {
Subroutine _addNewClients: not called CC=10 SCAR=47.0
1077 0 my $now = $self->_getTime();
1078 0 foreach my $tcpsocket (@{$self->{tcpsockets}}) {
1079 # Drain the listen queue rather than accepting one connection per iteration.
1080 # The listener is non-blocking, so accept() returns undef once the queue is empty.
1081 # This prevents a burst of connects from being rejected at the kernel level when
1082 # the backlog fills up while the main loop is busy elsewhere.
1083 0 my $acceptedThisCycle = 0;
1084 0 while(1) {
1085 # Hard cap to keep one rogue burst from monopolising the loop and starving
1086 # existing clients. Any remaining pending connects will be picked up in the
1087 # next runOnce() iteration.
1088 0 ▶ last if($acceptedThisCycle >= 64);
Branch: 1 branch
BranchTrueFalseTotal
if $acceptedThisCycle >= 64 0 0 0
1089  
1090 0 my $clientsocket = $tcpsocket->accept;
1091 0 ▶ if(!defined($clientsocket)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $clientsocket) 0 0 0
1092 # EAGAIN/EWOULDBLOCK (no more pending) or a transient error like
1093 # ECONNABORTED (peer RST between the kernel queueing the connection
1094 # and our accept). Either way, stop draining this listener.
1095 0 last;
1096 }
1097 0 $acceptedThisCycle++;
1098  
1099 0 $clientsocket->blocking(0);
1100  
1101 # Build a guaranteed-unique CID. The previous "$now:$rand(1_000_000)" scheme
1102 # had a 50% birthday collision chance after ~1180 connects in the same
1103 # second, and TCP CIDs based on $peerhost:$peerport collide whenever the
1104 # kernel reuses an ephemeral port. A process-monotonic serial fixes both.
1105 0 my $serial = $self->_nextClientSerial();
1106 0 my ($cid, $chost, $cport);
1107 0 ▶ if(ref $tcpsocket eq 'IO::Socket::UNIX') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $tcpsocket eq 'IO::Socket::UNIX') { } 0 0 0
1108 0 $chost = 'unixdomainsocket';
1109 0 $cport = $now . ':' . $serial;
1110 } else {
1111 0 ($chost, $cport) = ($clientsocket->peerhost, $clientsocket->peerport);
1112 # Append the serial so a reused ephemeral port can never alias an
1113 # existing or recently-disconnected client.
1114 0 $cport .= ':' . $serial;
1115 }
1116 0 $cid = "$chost:$cport";
1117 0 print "Got a new client $cid!\n";
1118 0 foreach my $debugcid (keys %{$self->{clients}}) {
1119 0 ▶ if($self->{clients}->{$debugcid}->{mirror}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"clients"}{$debugcid}{"mirror"}) 0 0 0
1120 0 $self->{clients}->{$debugcid}->{outbuffer} .= "DEBUG CONNECTED=" . $cid . "\r\n";
1121 }
1122 }
1123  
1124 0 ▶ if(ref $clientsocket ne 'IO::Socket::UNIX') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $clientsocket ne "IO::Socket::UNIX") 0 0 0
1125 # ONLY USE SSL WHEN RUNNING OVER THE NETWORK
1126 # There is simply no point in running it over a local socket.
1127 my $encrypted = IO::Socket::SSL->start_SSL($clientsocket,
1128 SSL_server => 1,
1129 SSL_cert_file => $self->{config}->{ssl}->{cert},
1130 SSL_key_file => $self->{config}->{ssl}->{key},
1131 SSL_cipher_list => 'ALL:!ADH:!RC4:+HIGH:+MEDIUM:!LOW:!SSLv2:!SSLv3!EXPORT',
1132 SSL_create_ctx_callback => sub {
1133 0 ▶ my $ctx = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1134  
1135 # Enable workarounds for broken clients
1136 0 Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL); ## no critic (Subroutines::ProhibitAmpersandSigils)
1137  
1138 # Disable session resumption completely
1139 0 Net::SSLeay::CTX_set_session_cache_mode($ctx, $SSL_SESS_CACHE_OFF);
1140  
1141 # Disable session tickets
1142 0 Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_NO_TICKET); ## no critic (Subroutines::ProhibitAmpersandSigils)
1143 },
1144 0 );
1145 0 ▶ if(!$encrypted) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($encrypted) 0 0 0
1146 # Critical: must close the accepted FD here. Without this every
1147 # failed handshake (port scan, RST during handshake, mismatched
1148 # cert, slow client) leaks one OS file descriptor. After enough
1149 # leaks the process hits RLIMIT_NOFILE and accept() begins
1150 # returning undef forever, which looks like the server has hung.
1151 0 print STDERR "startSSL failed for $cid: ", $SSL_ERROR, "\n";
1152 0 $self->_safeCloseSocket($clientsocket);
1153 0 next;
1154 }
1155 }
1156  
1157 0 $clientsocket->blocking(0);
1158 my %tmp = (
1159 buffer => '',
1160 charbuffer => [],
1161 listening => {},
1162 socket => $clientsocket,
1163 lastping => $now,
1164 mirror => 0,
1165 outbuffer => "CLACKS PageCamel $VERSION\r\n" .
1166 "OVERHEAD M Authentication required\r\n", # Informal message
1167 clientinfo => 'UNKNOWN',
1168 client_timeoffset => 0,
1169 host => $chost,
1170 port => $cport,
1171 interclacks => 0,
1172 interclacksclient => 0,
1173 lastinterclacksping => 0,
1174 lastmessage => $now,
1175 authtimeout => $now + $self->{config}->{authtimeout},
1176 0 authok => 0,
1177 failtime => 0,
1178 writefailtime => 0, # streak-start time for stalled writes; 0 = no streak in progress
1179 outmessages => [],
1180 inmessages => [],
1181 inmessagedelay => 0,
1182 outmessagedelay => 0,
1183 permissions => {
1184 read => 0,
1185 write => 0,
1186 manage => 0,
1187 interclacks => 0,
1188 },
1189 );
1190 0 if(0 && $self->{isDebugging}) {
1191 $tmp{authok} = 1;
1192 $tmp{outbuffer} .= "OVERHEAD M debugmode_auth_not_really_required\r\n"
1193 }
1194  
1195 # Defence in depth: the serial counter already guarantees uniqueness, but if
1196 # something ever did produce a duplicate CID we must NOT silently overwrite
1197 # the existing entry — that would leak the previous socket from the selector
1198 # forever. Log loudly, close the new socket, and drop it. The server keeps
1199 # running (no die/croak — see feedback memory).
1200 0 ▶ if(defined($self->{clients}->{$cid})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"clients"}{$cid}) 0 0 0
1201 0 print STDERR "INTERNAL: duplicate CID $cid generated; dropping new connection to avoid orphaning the existing one.\n";
1202 0 $self->_safeCloseSocket($clientsocket);
1203 0 next;
1204 }
1205  
1206 0 $self->{clients}->{$cid} = \%tmp;
1207 0 $clientsocket->_setClientID($cid);
1208 0 $self->{selector}->add($clientsocket);
1209 0 $self->{workCount}++;
1210 }
1211 }
1212  
1213 0 return;
1214 }
1215  
1216 ▶sub _disconnectClients($self) {
Subroutine _disconnectClients: not called CC=28 SCAR=67.0
1217 0 my $now = $self->_getTime();
1218  
1219 # Check if there are any clients to disconnect...
1220 0 my $pingtime = $now - $self->{config}->{pingtimeout};
1221 0 my $interclackspingtime = $now - $self->{config}->{interclackspingtimeout};
1222 0 my $interclackspinginterval = $now - int($self->{config}->{interclackspingtimeout} / 3);
1223 0 foreach my $cid (keys %{$self->{clients}}) {
1224 # NOTE: We deliberately do NOT call $socket->connected here.
1225 #
1226 # IO::Socket::connected is a thin wrapper around getpeername(), which
1227 # returns the cached peer address as long as the kernel still has any
1228 # connection state for the socket. That means it returns TRUE in exactly
1229 # the cases we most want to detect:
1230 # - peer closed cleanly (TCP FIN / Unix EOF, socket in CLOSE_WAIT)
1231 # - peer process crashed (kernel sent FIN on its behalf)
1232 # - peer machine vanished without sending FIN (TCP only; getpeername
1233 # keeps returning the cached address indefinitely)
1234 # It only returns FALSE on RST (TCP) or never-connected sockets — and
1235 # those cases are already detected by the other three paths below:
1236 # - sysread() returning 0 in _clientInput -> EOF / FIN / EOF-on-RST
1237 # - syswrite() returning EPIPE/ECONNRESET in _clientOutput
1238 # - the 60s server-side NOP\r\n keepalive in _clientOutput, which
1239 # forces a syswrite even on idle connections so a dead peer is
1240 # surfaced within 60 seconds without depending on client traffic
1241 # Using $socket->connected here gave a misleading "alive" signal in
1242 # exactly the scenarios it was supposed to catch (FIN/CLOSE_WAIT),
1243 # so it's been removed. Both TCP and Unix-domain-socket peers are
1244 # now detected exclusively via the I/O paths.
1245 #if(!$self->{clients}->{$cid}->{socket}->connected) {
1246 # push @{$self->{toremove}}, $cid;
1247 # next;
1248 #}
1249 0 ▶ if(!$self->{clients}->{$cid}->{interclacks}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{'clients'}{$cid}{'interclacks'}) { } 0 0 0
1250 0 ▶ if($self->{clients}->{$cid}->{lastping} > 0 && $self->{clients}->{$cid}->{lastping} < $pingtime) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"clients"}{$cid}{"lastping"} > 0 and $self->{"clients"}{$cid}{"lastping"} < $pingtime) 0 0 0
Condition0%0/3
$self->{"clients"}{$cid}{"lastping"} > 0 and $self->{"clients"}{$cid}{"lastping"} < $pingtime
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"clients"}{$cid}{"lastping"} > 0 and $self->{"clients"}{$cid}{"lastping"} < $pingtime
$self->{"clients"}{$cid}{"lastping"} > 0 $self->{"clients"}{$cid}{"lastping"} < $pingtime
Truth table0%0/3
A and B
A= $self->{"clients"}{$cid}{"lastping"} > 0B= $self->{"clients"}{$cid}{"lastping"} < $pingtime
ABresult
0X0
100
111
1251 0 $self->_evalsyswrite($self->{clients}->{$cid}->{socket}, "\r\nTIMEOUT\r\n");
1252 0 push @{$self->{toremove}}, $cid;
1253 0 next;
1254 }
1255 } else {
1256 0 ▶ if($self->{clients}->{$cid}->{lastping} < $interclackspingtime) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"clients"}{$cid}{"lastping"} < $interclackspingtime) 0 0 0
1257 0 $self->_evalsyswrite($self->{clients}->{$cid}->{socket}, "\r\nTIMEOUT\r\n");
1258 0 push @{$self->{toremove}}, $cid;
1259 0 next;
1260 }
1261 }
1262  
1263 0 ▶ if($self->{clients}->{$cid}->{interclacks} && $self->{clients}->{$cid}->{lastinterclacksping} < $interclackspinginterval) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"clients"}{$cid}{"interclacks"} and $self->{"clients"}{$cid}{"lastinterclacksping"} < $interclackspinginterval) 0 0 0
Condition0%0/3
$self->{"clients"}{$cid}{"interclacks"} and $self->{"clients"}{$cid}{"lastinterclacksping"} < $interclackspinginterval
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"clients"}{$cid}{"interclacks"} and $self->{"clients"}{$cid}{"lastinterclacksping"} < $interclackspinginterval
$self->{"clients"}{$cid}{"interclacks"} $self->{"clients"}{$cid}{"lastinterclacksping"} < $interclackspinginterval
Truth table0%0/3
A and B
A= $self->{"clients"}{$cid}{"interclacks"}B= $self->{"clients"}{$cid}{"lastinterclacksping"} < $interclackspinginterval
ABresult
0X0
100
111
1264 0 $self->{clients}->{$cid}->{lastinterclacksping} = $now;
1265 0 $self->{clients}->{$cid}->{outbuffer} .= "PING\r\n";
1266 }
1267  
1268 # Stalled-write check: we have data we want to send but every syswrite
1269 # has been failing (EAGAIN / 0 bytes) since writefailtime — i.e., the
1270 # client isn't draining their kernel receive buffer. After
1271 # stalledwritetimeout seconds of no forward progress, give up. NOPING
1272 # does NOT bypass this: it's about delivery capacity, not heartbeat.
1273 0 ▶ if($self->{clients}->{$cid}->{writefailtime} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"clients"}{$cid}{"writefailtime"} > 0) 0 0 0
1274 my $stalledtimeout = $self->{clients}->{$cid}->{interclacks}
1275 ? $self->{config}->{interclacksstalledwritetimeout}
1276 0 ▶ : $self->{config}->{stalledwritetimeout};
Branch: 1 branch
BranchTrueFalseTotal
$self->{'clients'}{$cid}{'interclacks'} ? : 0 0 0
1277 0 ▶ if(($now - $self->{clients}->{$cid}->{writefailtime}) > $stalledtimeout) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now - $self->{"clients"}{$cid}{"writefailtime"} > $stalledtimeout) 0 0 0
1278 0 print STDERR "Client $cid stalled write for >${stalledtimeout}s — disconnecting\n";
1279 # _evalsyswrite is best-effort here; if the kernel buffer is
1280 # already full this notification will just be discarded, which
1281 # is fine — we're tearing the connection down anyway.
1282 0 $self->_evalsyswrite($self->{clients}->{$cid}->{socket}, "\r\nTIMEOUT\r\n");
1283 0 push @{$self->{toremove}}, $cid;
1284 0 next;
1285 }
1286 }
1287  
1288 0 ▶ if(!$self->{clients}->{$cid}->{authok} && $self->{clients}->{$cid}->{authtimeout} < $now) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{"clients"}{$cid}{"authok"} and $self->{"clients"}{$cid}{"authtimeout"} < $now) 0 0 0
Condition0%0/3
not $self->{"clients"}{$cid}{"authok"} and $self->{"clients"}{$cid}{"authtimeout"} < $now
!ll&&!rl&&r
000
MC/DC0%0/2
not $self->{"clients"}{$cid}{"authok"} and $self->{"clients"}{$cid}{"authtimeout"} < $now
not $self->{"clients"}{$cid}{"authok"} $self->{"clients"}{$cid}{"authtimeout"} < $now
Truth table0%0/3
not(A) and B
A= not $self->{"clients"}{$cid}{"authok"}B= $self->{"clients"}{$cid}{"authtimeout"} < $now
ABresult
0X0
100
111
1289 # Authentication timeout!
1290 0 push @{$self->{toremove}}, $cid;
1291 }
1292 }
1293  
1294 # ...and disconnect them
1295 0 ▶ if(scalar @{$self->{toremove}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$self->{"toremove"};}) 0 0 0
1296 # Make sure we handle any last messages, or at least try to. This should allow us to at least try to adhere to the
1297 # protocol in some cases (auth failure, etc)
1298 0 $self->_outboxToClientBuffer();
1299 0 for(1..5) {
1300 0 my $anyremaining = 0;
1301 0 my %flushed;
1302 0 foreach my $cid (@{$self->{toremove}}) {
1303 0 ▶ next if($flushed{$cid});
Branch: 1 branch
BranchTrueFalseTotal
if $flushed{$cid} 0 0 0
1304 0 $flushed{$cid} = 1;
1305 0 ▶ next if(!defined($self->{clients}->{$cid}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"clients"}{$cid} 0 0 0
1306 0 ▶ next if(!length($self->{clients}->{$cid}->{outbuffer}));
Branch: 1 branch
BranchTrueFalseTotal
unless length $self->{"clients"}{$cid}{"outbuffer"} 0 0 0
1307 0 $anyremaining = 1;
1308 0 print "Flushing $cid for removal...\n";
1309 0 $self->_clientOutput($cid);
1310 }
1311 # Break out of the flush loop as soon as every outbuffer is drained,
1312 # rather than always sleeping the full 5*20ms = 100ms per disconnect batch.
1313 0 ▶ last if(!$anyremaining);
Branch: 1 branch
BranchTrueFalseTotal
unless $anyremaining 0 0 0
1314 0 sleep(0.02);
1315 }
1316 }
1317  
1318 0 ▶ while((my $cid = shift @{$self->{toremove}})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cid = shift @{$$self{"toremove"};}) 0 0 0
1319 # In some circumstances, there may be multiple @{$self->{toremove}} entries for the same client. Ignore them...
1320 0 ▶ if(defined($self->{clients}->{$cid})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"clients"}{$cid}) 0 0 0
1321 0 print "Removing client $cid\n";
1322 0 foreach my $debugcid (keys %{$self->{clients}}) {
1323 0 ▶ if($self->{clients}->{$debugcid}->{mirror}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"clients"}{$debugcid}{"mirror"}) 0 0 0
1324 0 $self->{clients}->{$debugcid}->{outbuffer} .= "DEBUG DISCONNECTED=" . $cid . " (" . length($self->{clients}->{$cid}->{outbuffer}) . " bytes discarded from outbuffer)\r\n";
1325 0 ▶ if($self->{clients}->{$cid}->{interclacksclient} && $self->{interclackslock}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"clients"}{$cid}{"interclacksclient"} and $self->{"interclackslock"}) 0 0 0
Condition0%0/3
$self->{"clients"}{$cid}{"interclacksclient"} and $self->{"interclackslock"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"clients"}{$cid}{"interclacksclient"} and $self->{"interclackslock"}
$self->{"clients"}{$cid}{"interclacksclient"} $self->{"interclackslock"}
Truth table0%0/3
A and B
A= $self->{"clients"}{$cid}{"interclacksclient"}B= $self->{"interclackslock"}
ABresult
0X0
100
111
1326 0 $self->{clients}->{$debugcid}->{outbuffer} .= "DEBUG DISCONNECTED=" . $cid . " (Unlocking interclacks mid-sync)\r\n";
1327 }
1328 }
1329 }
1330  
1331 0 ▶ if($self->{clients}->{$cid}->{interclacksclient} && $self->{interclackslock}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"clients"}{$cid}{"interclacksclient"} and $self->{"interclackslock"}) 0 0 0
Condition0%0/3
$self->{"clients"}{$cid}{"interclacksclient"} and $self->{"interclackslock"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"clients"}{$cid}{"interclacksclient"} and $self->{"interclackslock"}
$self->{"clients"}{$cid}{"interclacksclient"} $self->{"interclackslock"}
Truth table0%0/3
A and B
A= $self->{"clients"}{$cid}{"interclacksclient"}B= $self->{"interclackslock"}
ABresult
0X0
100
111
1332 0 print "...this one is interclacks master and has us locked - UNLOCKING mid-sync!\n";
1333 0 $self->{interclackslock} = 0;
1334 }
1335  
1336 # Always remove from selector AND explicitly close. Without the close,
1337 # IO::Select keeps the handle reference alive (so GC never fires), the
1338 # OS FD stays open, and after enough churn the process hits its FD limit.
1339 0 my $socket = $self->{clients}->{$cid}->{socket};
1340 0 eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
1341 0 $self->{selector}->remove($socket);
1342 };
1343 0 $self->_safeCloseSocket($socket);
1344 0 delete $self->{clients}->{$cid};
1345 #print "# Clients left: ", scalar keys %{$self->{clients}}, "\n";
1346 }
1347  
1348 0 $self->{workCount}++;
1349 }
1350  
1351 0 return;
1352 }
1353  
1354 ▶sub _clientInput($self) {
Subroutine _clientInput: not called CC=17 SCAR=57.2
1355 0 my $now = $self->_getTime();
1356  
1357 # **** READ FROM CLIENTS ****
1358 0 my $hasoutbufferwork = 0;
1359 0 foreach my $cid (keys %{$self->{clients}}) {
1360 0 ▶ if(length($self->{clients}->{$cid}->{buffer}) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"clients"}{$cid}{"buffer"} > 0) 0 0 0
1361 # Found some work to do
1362 0 $hasoutbufferwork = 1;
1363 0 last;
1364 }
1365 }
1366 0 my $selecttimeout = 0.5; # Half a second
1367 0 ▶ if($hasoutbufferwork) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hasoutbufferwork) 0 0 0
1368 0 $selecttimeout = 0.05;
1369 }
1370  
1371 0 my @inclients = $self->{selector}->can_read($selecttimeout);
1372 0 foreach my $clientsocket (@inclients) {
1373 0 my $cid = $clientsocket->_getClientID();
1374  
1375 # Skip if client already marked for removal or doesn't exist
1376 0 ▶ next if(!defined($self->{clients}->{$cid}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"clients"}{$cid} 0 0 0
1377 0 ▶ next if(contains($cid, $self->{toremove}));
Branch: 1 branch
BranchTrueFalseTotal
if contains($cid, $self->{"toremove"}) 0 0 0
1378  
1379 0 my $totalread = 0;
1380 0 my $readchunksleft = 3;
1381 0 while(1) {
1382 0 my $rawbuffer;
1383 my $bytes;
1384 0 my $readok = 0;
1385 0 eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
1386 0 $bytes = sysread($self->{clients}->{$cid}->{socket}, $rawbuffer, 1_000_000); # Read at most 1 Meg at a time
1387 0 $readok = 1;
1388 };
1389 0 ▶ if(!$readok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($readok) 0 0 0
1390 # Exception during read - disconnect
1391 0 push @{$self->{toremove}}, $cid;
1392 0 last;
1393 }
1394 0 ▶ if(!defined($bytes)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $bytes) 0 0 0
1395 # undef = error, check if temporary (EAGAIN/EWOULDBLOCK) or permanent
1396 0 ▶ if(!$ERRNO{EAGAIN} && !$ERRNO{EWOULDBLOCK}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Net::Clacks::Server::ERRNO{"EAGAIN"} or $Net::Clacks::Server::ERRNO{"EWOULDBLOCK"}) 0 0 0
Condition0%0/3
$Net::Clacks::Server::ERRNO{"EAGAIN"} or $Net::Clacks::Server::ERRNO{"EWOULDBLOCK"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$Net::Clacks::Server::ERRNO{"EAGAIN"} or $Net::Clacks::Server::ERRNO{"EWOULDBLOCK"}
$Net::Clacks::Server::ERRNO{"EAGAIN"} $Net::Clacks::Server::ERRNO{"EWOULDBLOCK"}
Truth table0%0/3
A or B
A= $Net::Clacks::Server::ERRNO{"EAGAIN"}B= $Net::Clacks::Server::ERRNO{"EWOULDBLOCK"}
ABresult
1X1
011
000
1397 # Permanent error - disconnect
1398 0 push @{$self->{toremove}}, $cid;
1399 }
1400 0 last;
1401 }
1402 0 ▶ if($bytes == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bytes == 0) 0 0 0
1403 # EOF - peer closed connection, disconnect immediately
1404 0 push @{$self->{toremove}}, $cid;
1405 0 last;
1406 }
1407 # $bytes > 0, we have data
1408 0 $totalread += $bytes;
1409 0 push @{$self->{clients}->{$cid}->{charbuffer}}, split//, $rawbuffer;
1410 0 $readchunksleft--;
1411 0 ▶ if(!$readchunksleft) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($readchunksleft) 0 0 0
1412 0 last;
1413 }
1414 }
1415
1416 # Check if we could read data from a socket that was marked as readable.
1417 # Thanks to SSL, this might occasionally fail. Don't bail out at the first
1418 # error, only if the condition persists for readfailtimeout seconds.
1419 # Note: EOF and permanent errors are now handled above, so this failtime
1420 # is mainly for SSL renegotiation edge cases and slow connections.
1421 0 ▶ if($totalread) {
Branch: 1 branch
BranchTrueFalseTotal
if ($totalread) { } 0 0 0
1422 # Data received - reset fail timer
1423 0 $self->{clients}->{$cid}->{failtime} = 0;
1424 } else {
1425 # Socket marked readable but no data
1426 # Use longer timeout for interclacks connections (higher latency, more critical)
1427 my $failtimeout = $self->{clients}->{$cid}->{interclacks}
1428 ? $self->{config}->{interclacksreadfailtimeout}
1429 0 ▶ : $self->{config}->{readfailtimeout};
Branch: 1 branch
BranchTrueFalseTotal
$self->{'clients'}{$cid}{'interclacks'} ? : 0 0 0
1430  
1431 0 ▶ if($self->{clients}->{$cid}->{failtime} == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'clients'}{$cid}{'failtime'} == 0) { } 0 0 0
elsif ($now - $self->{'clients'}{$cid}{'failtime'} > $failtimeout) { } 0 0 0
1432 # First failure in this streak - record the time
1433 0 $self->{clients}->{$cid}->{failtime} = $now;
1434 } elsif(($now - $self->{clients}->{$cid}->{failtime}) > $failtimeout) {
1435 # Failure streak has exceeded timeout threshold
1436 0 push @{$self->{toremove}}, $cid;
1437 }
1438 }
1439 }
1440  
1441 0 return;
1442 }
1443  
1444 # $forceclientid let's us "force" working on a specific client only
1445 0 ▶sub _clientOutput($self, $forceclientid = '') {
Subroutine _clientOutput: not called CC=24 SCAR=64.0
1446 0 my $now = $self->_getTime();
1447
1448 # **** WRITE TO CLIENTS ****
1449 0 foreach my $cid (keys %{$self->{clients}}) {
1450 0 ▶ if($forceclientid ne '' && $forceclientid ne $cid) {
Branch: 1 branch
BranchTrueFalseTotal
if ($forceclientid ne "" and $forceclientid ne $cid) 0 0 0
Condition0%0/3
$forceclientid ne "" and $forceclientid ne $cid
!ll&&!rl&&r
000
MC/DC0%0/2
$forceclientid ne "" and $forceclientid ne $cid
$forceclientid ne "" $forceclientid ne $cid
Truth table0%0/3
A and B
A= $forceclientid ne ""B= $forceclientid ne $cid
ABresult
0X0
100
111
1451 0 next;
1452 }
1453 0 ▶ if($cid ne $forceclientid && contains($cid, $self->{toremove})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cid ne $forceclientid and contains($cid, $self->{"toremove"})) 0 0 0
Condition0%0/3
$cid ne $forceclientid and contains($cid, $self->{"toremove"})
!ll&&!rl&&r
000
MC/DC0%0/2
$cid ne $forceclientid and contains($cid, $self->{"toremove"})
$cid ne $forceclientid contains($cid, $self->{"toremove"})
Truth table0%0/3
A and B
A= $cid ne $forceclientidB= contains($cid, $self->{"toremove"})
ABresult
0X0
100
111
1454 0 next;
1455 }
1456 0 ▶ if(length($self->{clients}->{$cid}->{outbuffer})) {
Branch: 2 branches
BranchTrueFalseTotal
if (length $self->{'clients'}{$cid}{'outbuffer'}) { } 0 0 0
elsif ($self->{'clients'}{$cid}{'lastmessage'} + 60 < $now) { } 0 0 0
1457 0 $self->{clients}->{$cid}->{lastmessage} = $now;
1458 } elsif(($self->{clients}->{$cid}->{lastmessage} + 60) < $now) {
1459 0 $self->{clients}->{$cid}->{lastmessage} = $now;
1460 0 $self->{clients}->{$cid}->{outbuffer} .= "NOP\r\n"; # send "No OPerations" command, just to
1461 # check if socket is still open
1462 }
1463  
1464 0 ▶ next if(!length($self->{clients}->{$cid}->{outbuffer}));
Branch: 1 branch
BranchTrueFalseTotal
unless length $self->{"clients"}{$cid}{"outbuffer"} 0 0 0
1465  
1466 # Output bandwidth-limited stuff, in as big chunks as possible
1467 0 my $written;
1468 0 $self->{workCount}++;
1469 0 eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
1470 0 $written = syswrite($self->{clients}->{$cid}->{socket}, $self->{clients}->{$cid}->{outbuffer});
1471 };
1472 0 ▶ if($EVAL_ERROR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Net::Clacks::Server::EVAL_ERROR) 0 0 0
1473 0 print STDERR "Write error: $EVAL_ERROR\n";
1474 # Peer is unreachable; discard any pending bytes so the flush loop
1475 # in _disconnectClients() doesn't burn its full 5*20ms budget
1476 # retrying syswrites that will never succeed.
1477 0 $self->{clients}->{$cid}->{outbuffer} = '';
1478 0 push @{$self->{toremove}}, $cid;
1479 0 next;
1480 }
1481 0 ▶ if(!defined($written)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $written) 0 0 0
1482 # syswrite returned undef - check error type
1483 0 ▶ if($ERRNO{EPIPE}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($Net::Clacks::Server::ERRNO{'EPIPE'}) { } 0 0 0
elsif (not $Net::Clacks::Server::ERRNO{'EAGAIN'} || $Net::Clacks::Server::ERRNO{'EWOULDBLOCK'}) { } 0 0 0
1484 # Peer closed connection — discard the outbuffer for the same
1485 # reason as above (no point trying to deliver to a dead peer
1486 # 5 times in the upcoming flush loop).
1487 0 print STDERR "Client $cid: connection closed by peer (EPIPE)\n";
1488 0 $self->{clients}->{$cid}->{outbuffer} = '';
1489 0 push @{$self->{toremove}}, $cid;
1490 0 next;
1491 ▶ } elsif(!$ERRNO{EAGAIN} && !$ERRNO{EWOULDBLOCK}) {
Condition0%0/3
$Net::Clacks::Server::ERRNO{'EAGAIN'} || $Net::Clacks::Server::ERRNO{'EWOULDBLOCK'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$Net::Clacks::Server::ERRNO{'EAGAIN'} || $Net::Clacks::Server::ERRNO{'EWOULDBLOCK'}
$Net::Clacks::Server::ERRNO{'EAGAIN'} $Net::Clacks::Server::ERRNO{'EWOULDBLOCK'}
Truth table0%0/3
A || B
A= $Net::Clacks::Server::ERRNO{'EAGAIN'}B= $Net::Clacks::Server::ERRNO{'EWOULDBLOCK'}
ABresult
1X1
011
000
1492 # Other permanent error (ECONNRESET, ENOTCONN, etc.) — same
1493 # treatment: connection is gone, drop pending data.
1494 0 print STDERR "Write error for $cid: $ERRNO\n";
1495 0 $self->{clients}->{$cid}->{outbuffer} = '';
1496 0 push @{$self->{toremove}}, $cid;
1497 0 next;
1498 }
1499 # EAGAIN/EWOULDBLOCK - kernel send buffer is full and the peer
1500 # isn't draining it right now. Start (or continue) the stalled-
1501 # write streak; _disconnectClients() will pull the plug if it
1502 # exceeds stalledwritetimeout. We don't reset it here — only a
1503 # successful (>0 byte) write resets the counter.
1504 0 ▶ if($self->{clients}->{$cid}->{writefailtime} == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"clients"}{$cid}{"writefailtime"} == 0) 0 0 0
1505 0 $self->{clients}->{$cid}->{writefailtime} = $now;
1506 }
1507 0 next;
1508 }
1509 0 ▶ if(!$self->{clients}->{$cid}->{socket}->opened || $self->{clients}->{$cid}->{socket}->error) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{"clients"}{$cid}{"socket"}->opened or $self->{"clients"}{$cid}{"socket"}->error) 0 0 0
Condition0%0/3
not $self->{"clients"}{$cid}{"socket"}->opened or $self->{"clients"}{$cid}{"socket"}->error
l!l&&r!l&&!r
000
MC/DC0%0/2
not $self->{"clients"}{$cid}{"socket"}->opened or $self->{"clients"}{$cid}{"socket"}->error
not $self->{"clients"}{$cid}{"socket"}->opened $self->{"clients"}{$cid}{"socket"}->error
Truth table0%0/3
not(A) or B
A= not $self->{"clients"}{$cid}{"socket"}->openedB= $self->{"clients"}{$cid}{"socket"}->error
ABresult
1X1
011
000
1510 0 print STDERR "Socket error for $cid\n";
1511 # Socket is in an error state; discard the outbuffer.
1512 0 $self->{clients}->{$cid}->{outbuffer} = '';
1513 0 push @{$self->{toremove}}, $cid;
1514 0 next;
1515 }
1516  
1517 0 ▶ if(defined($written) && $written) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $written and $written) { } 0 0 0
elsif (defined $written and $written == 0) { } 0 0 0
Condition0%0/3
defined $written and $written
!ll&&!rl&&r
000
MC/DC0%0/2
defined $written and $written
defined $written $written
Truth table0%0/3
A and B
A= defined $writtenB= $written
ABresult
0X0
100
111
1518 # Forward progress (any number of bytes accepted by the kernel)
1519 # clears the stalled-write streak. Even a small partial write means
1520 # the peer is reading.
1521 0 $self->{clients}->{$cid}->{writefailtime} = 0;
1522 0 ▶ if(length($self->{clients}->{$cid}->{outbuffer}) == $written) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{'clients'}{$cid}{'outbuffer'} == $written) { } 0 0 0
1523 0 $self->{clients}->{$cid}->{outbuffer} = '';
1524 } else {
1525 0 $self->{clients}->{$cid}->{outbuffer} = substr($self->{clients}->{$cid}->{outbuffer}, $written);
1526 }
1527 ▶ } elsif(defined($written) && $written == 0) {
Condition0%0/3
defined $written and $written == 0
!ll&&!rl&&r
000
MC/DC0%0/2
defined $written and $written == 0
defined $written $written == 0
Truth table0%0/3
A and B
A= defined $writtenB= $written == 0
ABresult
0X0
100
111
1528 # Defined but zero bytes is rare on Linux but possible on some
1529 # platforms (treat as "no progress" — same semantics as EAGAIN).
1530 0 ▶ if($self->{clients}->{$cid}->{writefailtime} == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"clients"}{$cid}{"writefailtime"} == 0) 0 0 0
1531 0 $self->{clients}->{$cid}->{writefailtime} = $now;
1532 }
1533 }
1534 }
1535  
1536 0 return;
1537 }
1538  
1539 ▶sub _cacheCleanup($self) {
Subroutine _cacheCleanup: not called CC=6 SCAR=37.4
1540 0 my $now = $self->_getTime();
1541  
1542 0 my $deletedtime = $now - $self->{config}->{deletedcachetime};
1543 0 my $staletime = $now - $self->{config}->{stalecachetime};
1544 0 foreach my $ckey (keys %{$self->{cache}}) {
1545 # Clean deleted entries. Ignore any non-"DELETED" entries as these are run from a different timer
1546 0 ▶ if($self->{cache}->{$ckey}->{deleted} && $self->{cache}->{$ckey}->{cachetime} < $deletedtime) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}{$ckey}{"deleted"} and $self->{"cache"}{$ckey}{"cachetime"} < $deletedtime) 0 0 0
Condition0%0/3
$self->{"cache"}{$ckey}{"deleted"} and $self->{"cache"}{$ckey}{"cachetime"} < $deletedtime
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"cache"}{$ckey}{"deleted"} and $self->{"cache"}{$ckey}{"cachetime"} < $deletedtime
$self->{"cache"}{$ckey}{"deleted"} $self->{"cache"}{$ckey}{"cachetime"} < $deletedtime
Truth table0%0/3
A and B
A= $self->{"cache"}{$ckey}{"deleted"}B= $self->{"cache"}{$ckey}{"cachetime"} < $deletedtime
ABresult
0X0
100
111
1547 0 delete $self->{cache}->{$ckey};
1548  
1549 0 my %tmp = (
1550 sender => 'SERVERCACHE',
1551 type => 'DEBUG',
1552 data => 'CLEANDELETED=' . $ckey,
1553 );
1554  
1555 0 push @{$self->{outbox}}, \%tmp;
1556 0 $self->{savecache} = 1;
1557 0 next;
1558 }
1559  
1560 # Forget entries that have not been accesses in a long time (stale entries).
1561 # Ignore any "DELETED" entries, as these are run from a different timer
1562 0 ▶ if(!$self->{cache}->{$ckey}->{deleted} && $self->{cache}->{$ckey}->{accesstime} < $staletime) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{"cache"}{$ckey}{"deleted"} and $self->{"cache"}{$ckey}{"accesstime"} < $staletime) 0 0 0
Condition0%0/3
not $self->{"cache"}{$ckey}{"deleted"} and $self->{"cache"}{$ckey}{"accesstime"} < $staletime
!ll&&!rl&&r
000
MC/DC0%0/2
not $self->{"cache"}{$ckey}{"deleted"} and $self->{"cache"}{$ckey}{"accesstime"} < $staletime
not $self->{"cache"}{$ckey}{"deleted"} $self->{"cache"}{$ckey}{"accesstime"} < $staletime
Truth table0%0/3
not(A) and B
A= not $self->{"cache"}{$ckey}{"deleted"}B= $self->{"cache"}{$ckey}{"accesstime"} < $staletime
ABresult
0X0
100
111
1563 0 delete $self->{cache}->{$ckey};
1564  
1565 0 my %tmp = (
1566 sender => 'SERVERCACHE',
1567 type => 'DEBUG',
1568 data => 'CLEANSTALE=' . $ckey,
1569 );
1570  
1571 0 push @{$self->{outbox}}, \%tmp;
1572 0 $self->{savecache} = 1;
1573 0 next;
1574 }
1575 }
1576  
1577 0 return;
1578 }
1579  
1580 ▶sub _outboxToClientBuffer($self) {
Subroutine _outboxToClientBuffer: not called CC=16 SCAR=56.1
1581 0 my $now = $self->_getTime();
1582  
1583 # Outbox contains the messages that have to be forwarded to the clients when listening (or when the connection is in interclacks mode)
1584 # We iterate over the outbox and put those messages into the output buffers of the corresponding client connection
1585 0 ▶ while((my $line = shift @{$self->{outbox}})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $line = shift @{$$self{"outbox"};}) 0 0 0
1586 0 $self->{workCount}++;
1587 0 foreach my $cid (keys %{$self->{clients}}) {
1588 0 ▶ if($line->{type} eq 'DEBUG' && $self->{clients}->{$cid}->{mirror}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line->{"type"} eq "DEBUG" and $self->{"clients"}{$cid}{"mirror"}) 0 0 0
Condition0%0/3
$line->{"type"} eq "DEBUG" and $self->{"clients"}{$cid}{"mirror"}
!ll&&!rl&&r
000
MC/DC0%0/2
$line->{"type"} eq "DEBUG" and $self->{"clients"}{$cid}{"mirror"}
$line->{"type"} eq "DEBUG" $self->{"clients"}{$cid}{"mirror"}
Truth table0%0/3
A and B
A= $line->{"type"} eq "DEBUG"B= $self->{"clients"}{$cid}{"mirror"}
ABresult
0X0
100
111
1589 0 $self->{clients}->{$cid}->{outbuffer} .= "DEBUG " . $line->{sender} . "=". $line->{data} . "\r\n";
1590 }
1591  
1592 0 ▶ if($cid eq $line->{sender}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cid eq $line->{"sender"}) 0 0 0
1593 0 next;
1594 }
1595  
1596 0 ▶ if($line->{type} ne 'DEBUG' && defined($self->{clients}->{$cid}->{listening}->{$line->{name}})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line->{"type"} ne "DEBUG" and defined $self->{"clients"}{$cid}{"listening"}{$line->{"name"}}) 0 0 0
Condition0%0/3
$line->{"type"} ne "DEBUG" and defined $self->{"clients"}{$cid}{"listening"}{$line->{"name"}}
!ll&&!rl&&r
000
MC/DC0%0/2
$line->{"type"} ne "DEBUG" and defined $self->{"clients"}{$cid}{"listening"}{$line->{"name"}}
$line->{"type"} ne "DEBUG" defined $self->{"clients"}{$cid}{"listening"}{$line->{"name"}}
Truth table0%0/3
A and B
A= $line->{"type"} ne "DEBUG"B= defined $self->{"clients"}{$cid}{"listening"}{$line->{"name"}}
ABresult
0X0
100
111
1597 # Just buffer in the clients outbuffers
1598 0 ▶ if($line->{type} eq 'NOTIFY') {
Branch: 3 branches
BranchTrueFalseTotal
if ($line->{'type'} eq 'NOTIFY') { } 0 0 0
elsif ($line->{'type'} eq 'SET') { } 0 0 0
elsif ($line->{'type'} eq 'SETANDSTORE') { } 0 0 0
1599 0 $self->{clients}->{$cid}->{outbuffer} .= "NOTIFY ". $line->{name} . "\r\n";
1600 } elsif($line->{type} eq 'SET') {
1601 0 $self->{clients}->{$cid}->{outbuffer} .= "SET ". $line->{name} . "=" . $line->{value} . "\r\n";
1602 } elsif($line->{type} eq 'SETANDSTORE') {
1603 # We forward SETANDSTORE as such only over interclacks connections. Basic clients don't have a cache,
1604 # so we only send a SET command
1605 0 ▶ if($self->{clients}->{$cid}->{interclacks}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'clients'}{$cid}{'interclacks'}) { } 0 0 0
1606 0 $self->{clients}->{$cid}->{outbuffer} .= "SETANDSTORE ". $line->{name} . "=" . $line->{value} . "\r\n";
1607 } else {
1608 0 $self->{clients}->{$cid}->{outbuffer} .= "SET ". $line->{name} . "=" . $line->{value} . "\r\n";
1609 }
1610 }
1611 }
1612 }
1613 }
1614  
1615  
1616 # Push all messages that can be released at this time into the corresponding char based output for each client
1617 0 foreach my $cid (keys %{$self->{clients}}) {
1618 0 ▶ while(scalar @{$self->{clients}->{$cid}->{outmessages}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$self->{"clients"}{$cid}{"outmessages"};}) 0 0 0
1619 0 ▶ last if($self->{clients}->{$cid}->{outmessages}->[0]->{releasetime} > $now);
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"clients"}{$cid}{"outmessages"}[0]{"releasetime"} > $now 0 0 0
1620  
1621 0 my $outmsg = shift @{$self->{clients}->{$cid}->{outmessages}};
1622 0 ▶ if($outmsg->{message} eq 'EXIT') {
Branch: 1 branch
BranchTrueFalseTotal
if ($outmsg->{'message'} eq 'EXIT') { } 0 0 0
1623 0 push @{$self->{toremove}}, $cid; # Disconnect the client
1624 } else {
1625 0 $self->{clients}->{$cid}->{outbuffer} .= $outmsg->{message} . "\r\n";
1626 }
1627 }
1628 }
1629  
1630 0 return;
1631 }
1632  
1633 ▶sub _requirePermission($self, $cid, $type) {
Subroutine _requirePermission: not called CC=3 SCAR=24.8
1634 0 ▶ if(defined($self->{clients}->{$cid}->{permissions}->{$type}) && $self->{clients}->{$cid}->{permissions}->{$type}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"clients"}{$cid}{"permissions"}{$type} and $self->{"clients"}{$cid}{"permissions"}{$type}) 0 0 0
Condition0%0/3
defined $self->{"clients"}{$cid}{"permissions"}{$type} and $self->{"clients"}{$cid}{"permissions"}{$type}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"clients"}{$cid}{"permissions"}{$type} and $self->{"clients"}{$cid}{"permissions"}{$type}
defined $self->{"clients"}{$cid}{"permissions"}{$type} $self->{"clients"}{$cid}{"permissions"}{$type}
Truth table0%0/3
A and B
A= defined $self->{"clients"}{$cid}{"permissions"}{$type}B= $self->{"clients"}{$cid}{"permissions"}{$type}
ABresult
0X0
100
111
1635 # Permission OK
1636 0 return 1;
1637 }
1638  
1639 0 my $now = $self->_getTime();
1640 0 push @{$self->{clients}->{$cid}->{outmessages}}, {releasetime => $now + $self->{clients}->{$cid}->{outmessagedelay}, message => 'OVERHEAD E permission_denied'};
1641  
1642 0 return 0;
1643 }
1644  
1645 ▶sub _handleMessageOverhead($self, $cid, $inmsg) {
Subroutine _handleMessageOverhead: not called CC=55 SCAR=80.3
1646 0 my $now = $self->_getTime();
1647  
1648 0 ▶ if($inmsg =~ /^OVERHEAD\ (.+?)\ (.+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inmsg =~ /^OVERHEAD\ (.+?)\ (.+)/u) 0 0 0
1649 0 my ($flags, $value) = ($1, $2);
1650 0 $self->{sendinterclacks} = 0;
1651 0 my @flagparts = split//, $flags;
1652 0 my %parsedflags;
1653 my %newflags;
1654 0 foreach my $key (sort keys %overheadflags) {
1655 0 ▶ if(contains($key, \@flagparts)) {
Branch: 1 branch
BranchTrueFalseTotal
if (contains($key, \@flagparts)) { } 0 0 0
1656 0 $parsedflags{$overheadflags{$key}} = 1;
1657 0 $newflags{$overheadflags{$key}} = 1;
1658 } else {
1659 0 $parsedflags{$overheadflags{$key}} = 0;
1660 0 $newflags{$overheadflags{$key}} = 0;
1661 }
1662 }
1663  
1664 0 ▶ if($parsedflags{auth_token}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsedflags{"auth_token"}) 0 0 0
1665 0 ▶ if(defined($self->{userlist}->{$value})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'userlist'}{$value}) { } 0 0 0
1666 0 $self->{clients}->{$cid}->{authok} = 1;
1667  
1668 # Copy user permissions to client session
1669 0 foreach my $key (qw[read write manage interclacks]) {
1670 0 $self->{clients}->{$cid}->{permissions}->{$key} = $self->{userlist}->{$value}->{$key};
1671 }
1672  
1673 #$self->{clients}->{$cid}->{outbuffer} .= "OVERHEAD O Welcome!\r\n";
1674 0 push @{$self->{clients}->{$cid}->{outmessages}}, {releasetime => $now + $self->{clients}->{$cid}->{outmessagedelay}, message => 'OVERHEAD O Welcome!'};
1675 0 return true; # NO LOGGING OF CREDENTIALS
1676 } else {
1677 0 $self->{clients}->{$cid}->{authok} = 0;
1678 #$self->{clients}->{$cid}->{outbuffer} .= "OVERHEAD F Login failed!\r\n";
1679 0 push @{$self->{clients}->{$cid}->{outmessages}}, {releasetime => $now + $self->{clients}->{$cid}->{outmessagedelay}, message => 'OVERHEAD F Login failed!'};
1680 0 push @{$self->{clients}->{$cid}->{outmessages}}, {releasetime => $now + $self->{clients}->{$cid}->{outmessagedelay}, message => 'EXIT'};
1681 0 push @{$self->{toremove}}, $cid; # Disconnect the client
1682 0 return true; # NO LOGGING OF CREDENTIALS
1683 }
1684 }
1685  
1686 # Ignore other command when not authenticated
1687 0 ▶ if(!$self->{clients}->{$cid}->{authok}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"clients"}{$cid}{"authok"}) 0 0 0
1688 0 return true;
1689 }
1690  
1691 0 ▶ if($parsedflags{timestamp}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsedflags{"timestamp"}) 0 0 0
1692 0 $now = $self->_getTime(); # Make sure we are at the "latest" $now. This is one of the very few critical sections
1693 0 $self->{clients}->{$cid}->{client_timeoffset} = $now - $value;
1694 0 print "**** CLIENT TIME OFFSET: ", $self->{clients}->{$cid}->{client_timeoffset}, "\n";
1695 0 return true;
1696 }
1697  
1698 0 ▶ if($parsedflags{lock_for_sync} && $self->{clients}->{$cid}->{interclacksclient}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsedflags{"lock_for_sync"} and $self->{"clients"}{$cid}{"interclacksclient"}) 0 0 0
Condition0%0/3
$parsedflags{"lock_for_sync"} and $self->{"clients"}{$cid}{"interclacksclient"}
!ll&&!rl&&r
000
MC/DC0%0/2
$parsedflags{"lock_for_sync"} and $self->{"clients"}{$cid}{"interclacksclient"}
$parsedflags{"lock_for_sync"} $self->{"clients"}{$cid}{"interclacksclient"}
Truth table0%0/3
A and B
A= $parsedflags{"lock_for_sync"}B= $self->{"clients"}{$cid}{"interclacksclient"}
ABresult
0X0
100
111
1699 0 ▶ return true unless($self->_requirePermission($cid, 'interclacks'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "interclacks") 0 0 0
1700 0 ▶ if($value) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value) { } 0 0 0
1701 0 print "Interclacks sync lock ON.\n";
1702 0 $self->{interclackslock} = 1;
1703 } else {
1704 0 print "Interclacks sync lock OFF.\n";
1705 0 $self->{interclackslock} = 0;
1706  
1707 # Send server our keys AFTER we got everything FROM the server (e.g. after unlock)
1708 0 $self->{clients}->{$cid}->{outbuffer} .= "OVERHEAD T " . $self->_getTime() . "\r\n"; # Send local time to server for offset calculation
1709  
1710 0 $now = $self->_getTime();
1711 0 foreach my $ckey (sort keys %{$self->{cache}}) {
1712 # Sanity checks
1713 0 ▶ if(!defined($self->{cache}->{$ckey}->{cachetime}) || !looks_like_number($self->{cache}->{$ckey}->{cachetime})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"cache"}{$ckey}{"cachetime"} and &looks_like_number($self->{"cache"}{$ckey}{"cachetime"})) 0 0 0
Condition0%0/3
defined $self->{"cache"}{$ckey}{"cachetime"} and &looks_like_number($self->{"cache"}{$ckey}{"cachetime"})
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"cache"}{$ckey}{"cachetime"} and &looks_like_number($self->{"cache"}{$ckey}{"cachetime"})
defined $self->{"cache"}{$ckey}{"cachetime"} &looks_like_number($self->{"cache"}{$ckey}{"cachetime"})
Truth table0%0/3
A and B
A= defined $self->{"cache"}{$ckey}{"cachetime"}B= &looks_like_number($self->{"cache"}{$ckey}{"cachetime"})
ABresult
0X0
100
111
1714 0 $self->{cache}->{$ckey}->{cachetime} = $now;
1715 }
1716 0 ▶ if(!defined($self->{cache}->{$ckey}->{accesstime}) || !looks_like_number($self->{cache}->{$ckey}->{accesstime})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"cache"}{$ckey}{"accesstime"} and &looks_like_number($self->{"cache"}{$ckey}{"accesstime"})) 0 0 0
Condition0%0/3
defined $self->{"cache"}{$ckey}{"accesstime"} and &looks_like_number($self->{"cache"}{$ckey}{"accesstime"})
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"cache"}{$ckey}{"accesstime"} and &looks_like_number($self->{"cache"}{$ckey}{"accesstime"})
defined $self->{"cache"}{$ckey}{"accesstime"} &looks_like_number($self->{"cache"}{$ckey}{"accesstime"})
Truth table0%0/3
A and B
A= defined $self->{"cache"}{$ckey}{"accesstime"}B= &looks_like_number($self->{"cache"}{$ckey}{"accesstime"})
ABresult
0X0
100
111
1717 0 $self->{cache}->{$ckey}->{accesstime} = $now;
1718 }
1719 0 ▶ if(!defined($self->{cache}->{$ckey}->{deleted}) || !$self->{cache}->{$ckey}->{deleted}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"cache"}{$ckey}{"deleted"} and $self->{"cache"}{$ckey}{"deleted"}) 0 0 0
Condition0%0/3
defined $self->{"cache"}{$ckey}{"deleted"} and $self->{"cache"}{$ckey}{"deleted"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"cache"}{$ckey}{"deleted"} and $self->{"cache"}{$ckey}{"deleted"}
defined $self->{"cache"}{$ckey}{"deleted"} $self->{"cache"}{$ckey}{"deleted"}
Truth table0%0/3
A and B
A= defined $self->{"cache"}{$ckey}{"deleted"}B= $self->{"cache"}{$ckey}{"deleted"}
ABresult
0X0
100
111
1720 0 $self->{cache}->{$ckey}->{deleted} = 0;
1721 }
1722 0 ▶ if(!defined($self->{cache}->{$ckey}->{data})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"cache"}{$ckey}{"data"}) 0 0 0
1723 0 $self->{cache}->{$ckey}->{data} = '';
1724 }
1725
1726 # Send KEYSYNC commands
1727 0 ▶ if(!$self->{cache}->{$ckey}->{deleted}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{'cache'}{$ckey}{'deleted'}) { } 0 0 0
1728 0 $self->{clients}->{$cid}->{outbuffer} .= "KEYSYNC " . $self->{cache}->{$ckey}->{cachetime} . " " . $self->{cache}->{$ckey}->{accesstime} . " U $ckey=" . $self->{cache}->{$ckey}->{data} . "\r\n";
1729 } else {
1730 0 $self->{clients}->{$cid}->{outbuffer} .= "KEYSYNC " . $self->{cache}->{$ckey}->{cachetime} . " 0 D $ckey=REMOVED\r\n";
1731 }
1732 }
1733 }
1734 0 $parsedflags{forward_message} = 0; # Don't forward
1735 0 $newflags{return_to_sender} = 0; # Don't return to sender
1736 }
1737  
1738 0 ▶ if($parsedflags{close_all_connections} && $value) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsedflags{"close_all_connections"} and $value) 0 0 0
Condition0%0/3
$parsedflags{"close_all_connections"} and $value
!ll&&!rl&&r
000
MC/DC0%0/2
$parsedflags{"close_all_connections"} and $value
$parsedflags{"close_all_connections"} $value
Truth table0%0/3
A and B
A= $parsedflags{"close_all_connections"}B= $value
ABresult
0X0
100
111
1739 0 ▶ return true unless($self->_requirePermission($cid, 'manage'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "manage") 0 0 0
1740 0 foreach my $closecid (keys %{$self->{clients}}) {
1741 0 ▶ if($self->{clients}->{$closecid}->{interclacks} && $parsedflags{forward_message}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"clients"}{$closecid}{"interclacks"} and $parsedflags{"forward_message"}) 0 0 0
Condition0%0/3
$self->{"clients"}{$closecid}{"interclacks"} and $parsedflags{"forward_message"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"clients"}{$closecid}{"interclacks"} and $parsedflags{"forward_message"}
$self->{"clients"}{$closecid}{"interclacks"} $parsedflags{"forward_message"}
Truth table0%0/3
A and B
A= $self->{"clients"}{$closecid}{"interclacks"}B= $parsedflags{"forward_message"}
ABresult
0X0
100
111
1742 0 $self->_evalsyswrite($self->{clients}->{$closecid}->{socket}, "\r\nOVERHEAD GC 1\r\n");
1743 }
1744 0 $self->_evalsyswrite($self->{clients}->{$closecid}->{socket}, "\r\nQUIT\r\n");
1745 0 push @{$self->{toremove}}, $closecid;
1746 }
1747 0 $parsedflags{forward_message} = 0; # Already forwarded where needed
1748 }
1749  
1750 0 ▶ if($parsedflags{shutdown_service}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsedflags{"shutdown_service"}) 0 0 0
1751 0 ▶ return true unless($self->_requirePermission($cid, 'manage'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "manage") 0 0 0
1752 0 $value = 0 + $value;
1753 0 ▶ if($value > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value > 0) 0 0 0
1754 0 $self->{shutdowntime} = $value + $now;
1755 0 print STDERR "Shutting down in $value seconds\n";
1756 }
1757 }
1758 0 ▶ if($parsedflags{discard_message}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsedflags{"discard_message"}) 0 0 0
1759 0 $self->{discardafterlogging} = 1;
1760 }
1761 0 ▶ if($parsedflags{no_logging}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsedflags{"no_logging"}) 0 0 0
1762 0 $self->{nodebug} = 1;
1763 }
1764  
1765 0 ▶ if($parsedflags{error_message}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsedflags{"error_message"}) 0 0 0
1766 0 print STDERR 'ERROR from ', $cid, ': ', $value, "\n";
1767 }
1768  
1769 0 ▶ if($parsedflags{set_interclacks_mode}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsedflags{"set_interclacks_mode"}) 0 0 0
1770 0 ▶ return true unless($self->_requirePermission($cid, 'interclacks'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "interclacks") 0 0 0
1771 0 $newflags{forward_message} = 0;
1772 0 $newflags{return_to_sender} = 0;
1773  
1774 0 ▶ if($value) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value) { } 0 0 0
1775 0 $self->{clients}->{$cid}->{interclacks} = 1;
1776 0 $self->{clients}->{$cid}->{lastping} = $now;
1777  
1778  
1779 $self->{clients}->{$cid}->{outbuffer} .= "CLACKS PageCamel $VERSION in interclacks master mode\r\n" . # Tell client we are in interclacks master mode
1780 "OVERHEAD M Authentication required\r\n" . # Informal message
1781 0 "OVERHEAD A " . $self->{authtoken} . "\r\n" . # ...and send Auth token...
1782 "OVERHEAD L 1\r\n" . # ...and lock client for sync
1783 "OVERHEAD T " . time . "\r\n"; # ... and send local timestamp
1784  
1785 # Make sure our new interclacks client has an *exact* copy of our buffer
1786 #$self->{clients}->{$cid}->{outbuffer} .= "CLEARCACHE\r\n";
1787
1788 0 $now = $self->_getTime();
1789 0 foreach my $ckey (sort keys %{$self->{cache}}) {
1790 # Sanity checks
1791 0 ▶ if(!defined($self->{cache}->{$ckey}->{cachetime}) || !looks_like_number($self->{cache}->{$ckey}->{cachetime})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"cache"}{$ckey}{"cachetime"} and &looks_like_number($self->{"cache"}{$ckey}{"cachetime"})) 0 0 0
Condition0%0/3
defined $self->{"cache"}{$ckey}{"cachetime"} and &looks_like_number($self->{"cache"}{$ckey}{"cachetime"})
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"cache"}{$ckey}{"cachetime"} and &looks_like_number($self->{"cache"}{$ckey}{"cachetime"})
defined $self->{"cache"}{$ckey}{"cachetime"} &looks_like_number($self->{"cache"}{$ckey}{"cachetime"})
Truth table0%0/3
A and B
A= defined $self->{"cache"}{$ckey}{"cachetime"}B= &looks_like_number($self->{"cache"}{$ckey}{"cachetime"})
ABresult
0X0
100
111
1792 0 $self->{cache}->{$ckey}->{cachetime} = $now;
1793 }
1794 0 ▶ if(!defined($self->{cache}->{$ckey}->{accesstime}) || !looks_like_number($self->{cache}->{$ckey}->{accesstime})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"cache"}{$ckey}{"accesstime"} and &looks_like_number($self->{"cache"}{$ckey}{"accesstime"})) 0 0 0
Condition0%0/3
defined $self->{"cache"}{$ckey}{"accesstime"} and &looks_like_number($self->{"cache"}{$ckey}{"accesstime"})
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"cache"}{$ckey}{"accesstime"} and &looks_like_number($self->{"cache"}{$ckey}{"accesstime"})
defined $self->{"cache"}{$ckey}{"accesstime"} &looks_like_number($self->{"cache"}{$ckey}{"accesstime"})
Truth table0%0/3
A and B
A= defined $self->{"cache"}{$ckey}{"accesstime"}B= &looks_like_number($self->{"cache"}{$ckey}{"accesstime"})
ABresult
0X0
100
111
1795 0 $self->{cache}->{$ckey}->{accesstime} = $now;
1796 }
1797 0 ▶ if(!defined($self->{cache}->{$ckey}->{deleted}) || !$self->{cache}->{$ckey}->{deleted}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"cache"}{$ckey}{"deleted"} and $self->{"cache"}{$ckey}{"deleted"}) 0 0 0
Condition0%0/3
defined $self->{"cache"}{$ckey}{"deleted"} and $self->{"cache"}{$ckey}{"deleted"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"cache"}{$ckey}{"deleted"} and $self->{"cache"}{$ckey}{"deleted"}
defined $self->{"cache"}{$ckey}{"deleted"} $self->{"cache"}{$ckey}{"deleted"}
Truth table0%0/3
A and B
A= defined $self->{"cache"}{$ckey}{"deleted"}B= $self->{"cache"}{$ckey}{"deleted"}
ABresult
0X0
100
111
1798 0 $self->{cache}->{$ckey}->{deleted} = 0;
1799 }
1800 0 ▶ if(!defined($self->{cache}->{$ckey}->{data})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"cache"}{$ckey}{"data"}) 0 0 0
1801 0 $self->{cache}->{$ckey}->{data} = '';
1802 }
1803  
1804 # Send KEYSYNC commands
1805 0 ▶ if(!$self->{cache}->{$ckey}->{deleted}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{'cache'}{$ckey}{'deleted'}) { } 0 0 0
1806 0 $self->{clients}->{$cid}->{outbuffer} .= "KEYSYNC " . $self->{cache}->{$ckey}->{cachetime} . " " . $self->{cache}->{$ckey}->{accesstime} . " U $ckey=" . $self->{cache}->{$ckey}->{data} . "\r\n";
1807 } else {
1808 0 $self->{clients}->{$cid}->{outbuffer} .= "KEYSYNC " . $self->{cache}->{$ckey}->{cachetime} . " 0 D $ckey=REMOVED\r\n";
1809 }
1810 }
1811 0 $self->{clients}->{$cid}->{outbuffer} .= "OVERHEAD L 0\r\n"; # unlock client after sync
1812 0 $self->{clients}->{$cid}->{outbuffer} .= "PING\r\n";
1813 0 $self->{clients}->{$cid}->{lastinterclacksping} = $now;
1814 } else {
1815 0 $self->{clients}->{$cid}->{interclacks} = 0;
1816 0 $self->{clients}->{$cid}->{lastping} = $now;
1817 }
1818 }
1819  
1820 0 my $newflagstring = '';
1821 0 $newflags{return_to_sender} = 0;
1822  
1823 0 foreach my $key (sort keys %overheadflags) {
1824 0 ▶ next if($key eq 'Z');
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "Z" 0 0 0
1825 0 ▶ if($newflags{$overheadflags{$key}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($newflags{$overheadflags{$key}}) 0 0 0
1826 0 $newflagstring .= $key;
1827 }
1828 }
1829 0 ▶ if($newflagstring eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($newflagstring eq "") 0 0 0
1830 0 $newflagstring = 'Z';
1831 }
1832  
1833 0 ▶ if($parsedflags{forward_message}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsedflags{"forward_message"}) 0 0 0
1834 0 ▶ return true unless($self->_requirePermission($cid, 'write'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "write") 0 0 0
1835 0 foreach my $overheadcid (keys %{$self->{clients}}) {
1836 0 ▶ next if($cid eq $overheadcid && !$parsedflags{return_to_sender});
Branch: 1 branch
BranchTrueFalseTotal
if $cid eq $overheadcid and not $parsedflags{"return_to_sender"} 0 0 0
Condition0%0/3
$cid eq $overheadcid and not $parsedflags{"return_to_sender"}
!ll&&!rl&&r
000
MC/DC0%0/2
$cid eq $overheadcid and not $parsedflags{"return_to_sender"}
$cid eq $overheadcid not $parsedflags{"return_to_sender"}
Truth table0%0/3
A and not(B)
A= $cid eq $overheadcidB= not $parsedflags{"return_to_sender"}
ABresult
0X0
100
111
1837  
1838 0 $self->{clients}->{$overheadcid}->{outbuffer} .= "OVERHEAD $newflagstring $value\r\n";
1839 }
1840 }
1841  
1842 0 return true;
1843 }
1844  
1845 0 return false;
1846 }
1847  
1848 ▶sub _handleMessageCaching($self, $cid, $inmsg) {
Subroutine _handleMessageCaching: not called CC=34 SCAR=70.8
1849 0 my $now = $self->_getTime();
1850  
1851 0 ▶ if($inmsg =~ /^KEYSYNC\ (.+?)\ (.+?)\ (.+?)\ (.+?)\=(.*)/) {
Branch: 9 branches
BranchTrueFalseTotal
if ($inmsg =~ /^KEYSYNC\ (.+?)\ (.+?)\ (.+?)\ (.+?)\=(.*)/u) { } 0 0 0
elsif ($inmsg =~ /^STORE\ (.+?)\=(.*)/u) { } 0 0 0
elsif ($inmsg =~ /^SETANDSTORE\ (.+?)\=(.*)/u) { } 0 0 0
elsif ($inmsg =~ /^RETRIEVE\ (.+)/u) { } 0 0 0
elsif ($inmsg =~ /^REMOVE\ (.+)/u) { } 0 0 0
elsif ($inmsg =~ /^INCREMENT\ (.+)/u) { } 0 0 0
elsif ($inmsg =~ /^DECREMENT\ (.+)/u) { } 0 0 0
elsif ($inmsg =~ /^KEYLIST/u) { } 0 0 0
elsif ($inmsg =~ /^CLEARCACHE/u) { } 0 0 0
1852 0 ▶ return true unless($self->_requirePermission($cid, 'interclacks'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "interclacks") 0 0 0
1853 #print "***** ", $inmsg, "\n";
1854 0 my ($ctimestamp, $atimestamp, $cmode, $ckey, $cval) = ($1, $2, $3, $4, $5);
1855 0 $self->{clients}->{$cid}->{lastping} = $now; # KEYSYNC acts as a PING as well
1856  
1857 0 $ctimestamp += $self->{clients}->{$cid}->{client_timeoffset}; # Take client time offset into account
1858 0 ▶ if($atimestamp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($atimestamp) 0 0 0
1859 0 $atimestamp += $self->{clients}->{$cid}->{client_timeoffset}; # Take client time offset into account
1860 }
1861  
1862 0 ▶ if(!defined($self->{cache}->{$ckey}) || $ctimestamp > $self->{cache}->{$ckey}->{cachetime}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"cache"}{$ckey} or $ctimestamp > $self->{"cache"}{$ckey}{"cachetime"}) 0 0 0
Condition0%0/3
not defined $self->{"cache"}{$ckey} or $ctimestamp > $self->{"cache"}{$ckey}{"cachetime"}
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $self->{"cache"}{$ckey} or $ctimestamp > $self->{"cache"}{$ckey}{"cachetime"}
not defined $self->{"cache"}{$ckey} $ctimestamp > $self->{"cache"}{$ckey}{"cachetime"}
Truth table0%0/3
not(A) or B
A= not defined $self->{"cache"}{$ckey}B= $ctimestamp > $self->{"cache"}{$ckey}{"cachetime"}
ABresult
1X1
011
000
1863 # If *we* have the older entry (or none at all), *only* then work on the keysync command
1864 0 $self->{cache}->{$ckey} = {
1865 data => $cval,
1866 cachetime => $ctimestamp,
1867 accesstime => $atimestamp,
1868 deleted => 0,
1869 };
1870 0 ▶ if($cmode eq 'D') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmode eq "D") 0 0 0
1871 0 $self->{cache}->{$ckey}->{data} = '';
1872 0 $self->{cache}->{$ckey}->{deleted} = 1;
1873 }
1874 }
1875  
1876 0 $self->{savecache} = 1;
1877 0 $self->{sendinterclacks} = 1;
1878 } elsif($inmsg =~ /^STORE\ (.+?)\=(.*)/) {
1879 0 ▶ return true unless($self->_requirePermission($cid, 'write'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "write") 0 0 0
1880 0 my ($ckey, $cval) = ($1, $2);
1881 0 $self->{cache}->{$ckey} = {
1882 data => $cval,
1883 cachetime => $now,
1884 accesstime => $now,
1885 deleted => 0,
1886 };
1887 0 $self->{savecache} = 1;
1888 } elsif($inmsg =~ /^SETANDSTORE\ (.+?)\=(.*)/) {
1889 0 ▶ return true unless($self->_requirePermission($cid, 'write'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "write") 0 0 0
1890 0 my ($ckey, $cval) = ($1, $2);
1891 0 my %tmp = (
1892 sender => $cid,
1893 type => 'SETANDSTORE',
1894 name => $ckey,
1895 value => $cval,
1896 );
1897 0 push @{$self->{outbox}}, \%tmp;
1898 0 $self->{cache}->{$ckey} = {
1899 data => $cval,
1900 cachetime => $now,
1901 accesstime => $now,
1902 deleted => 0,
1903 };
1904 0 $self->{savecache} = 1;
1905 } elsif($inmsg =~ /^RETRIEVE\ (.+)/) {
1906 0 ▶ return true unless($self->_requirePermission($cid, 'read'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "read") 0 0 0
1907 #$self->{clients}->{$cid}->{outbuffer} .= "SET ". $line->{name} . "=" . $line->{value} . "\r\n";
1908 0 my $ckey = $1;
1909 0 ▶ if(defined($self->{cache}->{$ckey}) && !$self->{cache}->{$ckey}->{deleted}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'cache'}{$ckey} and not $self->{'cache'}{$ckey}{'deleted'}) { } 0 0 0
Condition0%0/3
defined $self->{"cache"}{$ckey} and not $self->{"cache"}{$ckey}{"deleted"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"cache"}{$ckey} and not $self->{"cache"}{$ckey}{"deleted"}
defined $self->{"cache"}{$ckey} not $self->{"cache"}{$ckey}{"deleted"}
Truth table0%0/3
A and not(B)
A= defined $self->{"cache"}{$ckey}B= not $self->{"cache"}{$ckey}{"deleted"}
ABresult
0X0
100
111
1910 0 $self->{clients}->{$cid}->{outbuffer} .= "RETRIEVED $ckey=" . $self->{cache}->{$ckey}->{data} . "\r\n";
1911 0 $self->{cache}->{$ckey}->{accesstime} = $now;
1912 0 $self->{savecache} = 1;
1913 } else {
1914 0 $self->{clients}->{$cid}->{outbuffer} .= "NOTRETRIEVED $ckey\r\n";
1915 }
1916 0 $self->{sendinterclacks} = 0;
1917 } elsif($inmsg =~ /^REMOVE\ (.+)/) {
1918 0 ▶ return true unless($self->_requirePermission($cid, 'write'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "write") 0 0 0
1919 0 my $ckey = $1;
1920 0 $self->{cache}->{$ckey} = {
1921 data => '',
1922 cachetime => $now,
1923 accesstime => $now,
1924 deleted => 1,
1925 };
1926 0 $self->{savecache} = 1;
1927 } elsif($inmsg =~ /^INCREMENT\ (.+)/) {
1928 0 ▶ return true unless($self->_requirePermission($cid, 'write'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "write") 0 0 0
1929 0 my $ckey = $1;
1930 0 my $cval = 1;
1931 0 ▶ if($ckey =~ /(.+)\=(.+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ckey =~ /(.+)\=(.+)/u) 0 0 0
1932 0 ($ckey, $cval) = ($1, $2);
1933 0 $cval = 0 + $cval;
1934 }
1935  
1936 0 my $oldval = 0;
1937 0 ▶ if(defined($self->{cache}->{$ckey}) && !$self->{cache}->{$ckey}->{deleted} && looks_like_number($self->{cache}->{$ckey}->{data})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"cache"}{$ckey} and not $self->{"cache"}{$ckey}{"deleted"} and &looks_like_number($self->{"cache"}{$ckey}{"data"})) 0 0 0
Condition0%0/6
defined $self->{"cache"}{$ckey} and not $self->{"cache"}{$ckey}{"deleted"} and &looks_like_number($self->{"cache"}{$ckey}{"data"})
!ll&&!rl&&r
000
defined $self->{"cache"}{$ckey} and not $self->{"cache"}{$ckey}{"deleted"}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $self->{"cache"}{$ckey} and not $self->{"cache"}{$ckey}{"deleted"} and &looks_like_number($self->{"cache"}{$ckey}{"data"})
defined $self->{"cache"}{$ckey} not $self->{"cache"}{$ckey}{"deleted"} &looks_like_number($self->{"cache"}{$ckey}{"data"})
Truth table0%0/4
A and not(B) and C
A= defined $self->{"cache"}{$ckey}B= not $self->{"cache"}{$ckey}{"deleted"}C= &looks_like_number($self->{"cache"}{$ckey}{"data"})
ABCresult
0XX0
10X0
1100
1111
1938 0 $oldval = $self->{cache}->{$ckey}->{data};
1939 }
1940  
1941 0 $self->{cache}->{$ckey} = {
1942 data => $oldval + $cval,
1943 cachetime => $now,
1944 accesstime => $now,
1945 deleted => 0,
1946 };
1947  
1948 0 $self->{savecache} = 1;
1949 } elsif($inmsg =~ /^DECREMENT\ (.+)/) {
1950 0 ▶ return true unless($self->_requirePermission($cid, 'write'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "write") 0 0 0
1951 0 my $ckey = $1;
1952 0 my $cval = 1;
1953 0 ▶ if($ckey =~ /(.+)\=(.+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ckey =~ /(.+)\=(.+)/u) 0 0 0
1954 0 ($ckey, $cval) = ($1, $2);
1955 0 $cval = 0 + $cval;
1956 }
1957  
1958 0 my $oldval = 0;
1959 0 ▶ if(defined($self->{cache}->{$ckey}) && !$self->{cache}->{$ckey}->{deleted} && looks_like_number($self->{cache}->{$ckey}->{data})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"cache"}{$ckey} and not $self->{"cache"}{$ckey}{"deleted"} and &looks_like_number($self->{"cache"}{$ckey}{"data"})) 0 0 0
Condition0%0/6
defined $self->{"cache"}{$ckey} and not $self->{"cache"}{$ckey}{"deleted"} and &looks_like_number($self->{"cache"}{$ckey}{"data"})
!ll&&!rl&&r
000
defined $self->{"cache"}{$ckey} and not $self->{"cache"}{$ckey}{"deleted"}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $self->{"cache"}{$ckey} and not $self->{"cache"}{$ckey}{"deleted"} and &looks_like_number($self->{"cache"}{$ckey}{"data"})
defined $self->{"cache"}{$ckey} not $self->{"cache"}{$ckey}{"deleted"} &looks_like_number($self->{"cache"}{$ckey}{"data"})
Truth table0%0/4
A and not(B) and C
A= defined $self->{"cache"}{$ckey}B= not $self->{"cache"}{$ckey}{"deleted"}C= &looks_like_number($self->{"cache"}{$ckey}{"data"})
ABCresult
0XX0
10X0
1100
1111
1960 0 $oldval = $self->{cache}->{$ckey}->{data};
1961 }
1962  
1963 0 $self->{cache}->{$ckey} = {
1964 data => $oldval - $cval,
1965 cachetime => $now,
1966 accesstime => $now,
1967 deleted => 0,
1968 };
1969  
1970 0 $self->{savecache} = 1;
1971 } elsif($inmsg =~ /^KEYLIST/) {
1972 0 ▶ return true unless($self->_requirePermission($cid, 'read'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "read") 0 0 0
1973 0 $self->{clients}->{$cid}->{outbuffer} .= "KEYLISTSTART\r\n";
1974 0 foreach my $ckey (sort keys %{$self->{cache}}) {
1975 0 $self->{clients}->{$cid}->{outbuffer} .= "KEY $ckey\r\n";
1976 }
1977 0 $self->{clients}->{$cid}->{outbuffer} .= "KEYLISTEND\r\n";
1978 0 $self->{sendinterclacks} = 0;
1979 } elsif($inmsg =~ /^CLEARCACHE/) {
1980 0 ▶ return true unless $self->_requirePermission($cid, 'manage');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "manage") 0 0 0
1981 0 $self->{cache} = {};
1982 0 $self->{savecache} = 1;
1983 } else {
1984 # "not handled in this sub"
1985 0 return false;
1986 }
1987  
1988 0 return true;
1989 }
1990  
1991 ▶sub _handleMessageControl($self, $cid, $inmsg) {
Subroutine _handleMessageControl: not called CC=22 SCAR=62.3
1992 0 my $now = $self->_getTime();
1993  
1994 0 ▶ if($inmsg =~ /^LISTEN\ (.*)/) {
Branch: 11 branches
BranchTrueFalseTotal
if ($inmsg =~ /^LISTEN\ (.*)/u) { } 0 0 0
elsif ($inmsg =~ /^UNLISTEN\ (.*)/u) { } 0 0 0
elsif ($inmsg =~ /^MONITOR/u) { } 0 0 0
elsif ($inmsg =~ /^UNMONITOR/u) { } 0 0 0
elsif ($inmsg =~ /^QUIT/u) { } 0 0 0
elsif ($inmsg =~ /^TIMEOUT/u and $self->{'clients'}{$cid}{'interclacks'}) { } 0 0 0
elsif ($inmsg =~ /^PING/u) { } 0 0 0
elsif ($inmsg =~ /^NOPING/u) { } 0 0 0
elsif ($inmsg =~ /^CLIENTLIST/u) { } 0 0 0
elsif ($inmsg =~ /^CLIENTDISCONNECT\ (.+)/u) { } 0 0 0
elsif ($inmsg =~ /^FLUSH\ (.+)/u) { } 0 0 0
1995 0 ▶ return true unless($self->_requirePermission($cid, 'read'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "read") 0 0 0
1996 0 $self->{clients}->{$cid}->{listening}->{$1} = 1;
1997 0 $self->{sendinterclacks} = 0;
1998 } elsif($inmsg =~ /^UNLISTEN\ (.*)/) {
1999 0 ▶ return true unless($self->_requirePermission($cid, 'read'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "read") 0 0 0
2000 0 delete $self->{clients}->{$cid}->{listening}->{$1};
2001 0 $self->{sendinterclacks} = 0;
2002 } elsif($inmsg =~ /^MONITOR/) {
2003 0 ▶ return true unless($self->_requirePermission($cid, 'manage'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "manage") 0 0 0
2004 0 $self->{clients}->{$cid}->{mirror} = 1;
2005 0 $self->{sendinterclacks} = 0;
2006 } elsif($inmsg =~ /^UNMONITOR/) {
2007 0 ▶ return true unless($self->_requirePermission($cid, 'manage'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "manage") 0 0 0
2008 0 $self->{clients}->{$cid}->{mirror} = 0;
2009 0 $self->{sendinterclacks} = 0;
2010 } elsif($inmsg =~ /^QUIT/) {
2011 0 print STDERR "Client disconnected cleanly!\n";
2012 0 push @{$self->{toremove}}, $cid;
2013 0 $self->{sendinterclacks} = 0;
2014 ▶ } elsif($inmsg =~ /^TIMEOUT/ && $self->{clients}->{$cid}->{interclacks}) {
Condition0%0/3
$inmsg =~ /^TIMEOUT/u and $self->{"clients"}{$cid}{"interclacks"}
!ll&&!rl&&r
000
MC/DC0%0/2
$inmsg =~ /^TIMEOUT/u and $self->{"clients"}{$cid}{"interclacks"}
$inmsg =~ /^TIMEOUT/u $self->{"clients"}{$cid}{"interclacks"}
Truth table0%0/3
A and B
A= $inmsg =~ /^TIMEOUT/uB= $self->{"clients"}{$cid}{"interclacks"}
ABresult
0X0
100
111
2015 0 ▶ return true unless($self->_requirePermission($cid, 'interclacks'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "interclacks") 0 0 0
2016 0 print STDERR "Ooops, didn't send timely PINGS through interclacks link!\n";
2017 0 push @{$self->{toremove}}, $cid;
2018 0 $self->{sendinterclacks} = 0;
2019 } elsif($inmsg =~ /^PING/) {
2020 0 $self->{clients}->{$cid}->{lastping} = $now;
2021 0 $self->{sendinterclacks} = 0;
2022 } elsif($inmsg =~ /^NOPING/) {
2023 # Disable PING check until next PING recieved
2024 0 $self->{clients}->{$cid}->{lastping} = 0;
2025 0 $self->{sendinterclacks} = 0;
2026 } elsif($inmsg =~ /^CLIENTLIST/) {
2027 0 ▶ return true unless($self->_requirePermission($cid, 'manage'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "manage") 0 0 0
2028 0 $self->{clients}->{$cid}->{outbuffer} .= "CLIENTLISTSTART\r\n";
2029 0 foreach my $lmccid (sort keys %{$self->{clients}}) {
2030 $self->{clients}->{$cid}->{outbuffer} .= "CLIENT CID=$lmccid;" .
2031 "HOST=" . $self->{clients}->{$lmccid}->{host} . ";" .
2032 "PORT=" . $self->{clients}->{$lmccid}->{port} . ";" .
2033 "CLIENTINFO=" . $self->{clients}->{$lmccid}->{clientinfo} . ";" .
2034 "OUTBUFFER_LENGTH=" . length($self->{clients}->{$lmccid}->{outbuffer}) . ";" .
2035 "INBUFFER_LENGTH=" . length($self->{clients}->{$lmccid}->{buffer}) . ";" .
2036 "INTERCLACKS=" . $self->{clients}->{$lmccid}->{interclacks} . ";" .
2037 "MONITOR=" . $self->{clients}->{$lmccid}->{mirror} . ";" .
2038 "LASTPING=" . $self->{clients}->{$lmccid}->{lastping} . ";" .
2039 "LASTINTERCLACKSPING=" . $self->{clients}->{$lmccid}->{lastinterclacksping} . ";" .
2040 0 "WRITEFAILTIME=" . $self->{clients}->{$lmccid}->{writefailtime} . ";" .
2041 "\r\n";
2042 }
2043 0 $self->{clients}->{$cid}->{outbuffer} .= "CLIENTLISTEND\r\n";
2044 0 $self->{sendinterclacks} = 0;
2045 } elsif($inmsg =~ /^CLIENTDISCONNECT\ (.+)/) {
2046 0 ▶ return true unless($self->_requirePermission($cid, 'manage'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "manage") 0 0 0
2047 0 my $lmccid = $1;
2048 0 ▶ if(defined($self->{clients}->{$lmccid})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"clients"}{$lmccid}) 0 0 0
2049 # Try to notify the client (may or may not work);
2050 0 $self->_evalsyswrite($self->{clients}->{$lmccid}->{socket}, "\r\nQUIT\r\n");
2051 0 push @{$self->{toremove}}, $lmccid;
2052 }
2053 0 $self->{sendinterclacks} = 0;
2054 } elsif($inmsg =~ /^FLUSH\ (.+)/) {
2055 0 my $retid = $1;
2056 0 $self->{clients}->{$cid}->{outbuffer} .= "FLUSHED $retid\r\n";
2057 0 $self->{sendinterclacks} = 0;
2058 } else {
2059 # "not handled in this sub"
2060 0 return false;
2061 }
2062  
2063 0 return true;
2064 }
2065  
2066  
2067 ▶sub _handleMessageDirect($self, $cid, $inmsg) {
Subroutine _handleMessageDirect: not called CC=5 SCAR=34.0
2068 0 ▶ if($inmsg =~ /^NOTIFY\ (.*)/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($inmsg =~ /^NOTIFY\ (.*)/u) { } 0 0 0
elsif ($inmsg =~ /^SET\ (.+?)\=(.*)/u) { } 0 0 0
2069 0 ▶ return true unless($self->_requirePermission($cid, 'write'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "write") 0 0 0
2070 0 my %tmp = (
2071 sender => $cid,
2072 type => 'NOTIFY',
2073 name => $1,
2074 );
2075 0 push @{$self->{outbox}}, \%tmp;
2076 } elsif($inmsg =~ /^SET\ (.+?)\=(.*)/) {
2077 0 ▶ return true unless($self->_requirePermission($cid, 'write'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_requirePermission($cid, "write") 0 0 0
2078 0 my %tmp = (
2079 sender => $cid,
2080 type => 'SET',
2081 name => $1,
2082 value => $2,
2083 );
2084 0 push @{$self->{outbox}}, \%tmp;
2085 } else {
2086 # "not handled in this sub"
2087 0 return false;
2088 }
2089  
2090 0 return true;
2091 }
2092  
2093 4 1;
2094 __END__
↑ Summary Clacks/Client.pm »