Clacks/Server.pm

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