blib/lib/App/FileSync/Server.pm

filter: Statementstmt 99.0% 599 / 605 Branchbran 74.5% 149 / 200 Conditioncond 46.6% 62 / 133 MC/DCmcdc 14.1% 11 / 78 Subroutinesub 100% 96 / 96 Podpod 100% 3 / 3 totaltotal 82.5% 920 / 1115 CC 159 SCAR 18.8
CC
159
Cov
86%
_commit_upload
15.8
validate_forced_command
15.0
_manifest
13.7
CRAP 6.5
« blib/lib/App/FileSync/Trash.pm ↑ Summary blib/lib/App/FileSync/I18N.pm »
1 package App::FileSync::Server;
2  
3 # The server end of one sync session. It is started by sshd (or the local
4 # transport) with the repo, client and role pinned on its command line, speaks
5 # the lock-step protocol on its connection, and only ever does what its own
6 # plan allows: a client cannot write, read, delete or acknowledge a path the
7 # server did not plan for it.
8  
9 313 ▶use App::FileSync::Platform;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 313 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 313 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 313 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 313 ▶use Digest::SHA ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 313 ▶use File::Temp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 313 ▶use List::Util qw(any);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 313 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 313 ▶use Sub::Private { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
20 313 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 313 ▶use parent 'App::FileSync::Base';
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 313 ▶use App::FileSync qw(validate_relpath validate_client_id validate_repo_name name_with_suffix);
Subroutine BEGIN: called CC=1 SCAR=0.0
25 313 ▶use App::FileSync::Args qw(named);
Subroutine BEGIN: called CC=1 SCAR=0.0
26 313 ▶use App::FileSync::Constants qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
27 $PROTOCOL_VERSION $ROLE_CLIENT @ROLES $TYPE_FILE $TYPE_DIR
28 $MODE_MASK $DEFAULT_FILE_MODE $MAX_CHUNK_BYTES $SHA256_HEX
29 $EXIT_OK $EXIT_FATAL $EXIT_LOCKED $EXIT_WARNINGS $SERVER_PROGRAM
30 $STAT_MODE $STAT_SIZE $STAT_MTIME $SHA_BITS
31 313 );
32 313 ▶use App::FileSync::Delta;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 313 ▶use App::FileSync::I18N qw(message os_error strip_location);
Subroutine BEGIN: called CC=1 SCAR=0.0
34 313 ▶use App::FileSync::Merge;
Subroutine BEGIN: called CC=1 SCAR=0.0
35 313 ▶use App::FileSync::Protocol;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 313 ▶use App::FileSync::Settings;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 313 ▶use App::FileSync::Store;
Subroutine BEGIN: called CC=1 SCAR=0.0
38  
39 313 ▶use version; our $VERSION = version->declare('0.002.1');
Subroutine BEGIN: called CC=1 SCAR=0.0
40  
41 # Package variables for compatibility: the CLI checks $PROTO, and tests may
42 # localise $CHUNK.
43 313 our $CHUNK = 262_144;
44 313 our $PROTO = $PROTOCOL_VERSION;
45  
46 # Bounds on a pull signature the client uploads, so a hostile client cannot
47 # make the server allocate or hash without limit.
48 313 Readonly::Scalar my $MAX_SIGNATURE_BLOCKS => 16_384;
49 313 Readonly::Scalar my $MIN_SIGNATURE_BLOCK => 1024;
50 313 Readonly::Scalar my $MAX_SIGNATURE_BLOCK => 1024 * 1024;
51  
52 # Wire cost of one delta record, for deciding whether a delta is worth it;
53 # the constant covers the reply headers.
54 313 Readonly::Scalar my $DELTA_OP_BYTES => 12;
55 313 Readonly::Scalar my $DELTA_OVERHEAD => 64;
56  
57 # Unsigned decimal integers, and mtimes (which may be fractional or, for a
58 # file dated before 1970, negative).
59 313 Readonly my $UINT => qr/\A\d+\z/;
60 313 Readonly my $MTIME => qr/\A-?\d+(?:\.\d+)?\z/;
61  
62 # The protocol's commands and the method that serves each.
63 313 Readonly my %COMMANDS => (
64 manifest => '_manifest',
65 plan => '_plan',
66 get => '_get',
67 put => '_put',
68 chunk => '_chunk',
69 chunk_end => '_chunk_end',
70 sig => '_signature',
71 delta => '_delta_start',
72 dcopy => '_delta_copy',
73 dlit => '_delta_literal',
74 delta_end => '_delta_end',
75 dsig => '_pull_signature',
76 dop => '_pull_op',
77 mkdir => '_mkdir',
78 del => '_delete',
79 ack => '_ack',
80 done => '_finish',
81 );
82  
83 # Which planned actions each kind of request may serve. "conflict:client"
84 # is a conflict the client's version won; "conflict:remote" one the master's won.
85 313 Readonly my %MAY => (
86 read => [ 'pull', 'conflict:remote' ],
87 write => [ 'push', 'conflict:client' ],
88 delta => [ 'push' ],
89 pull => [ 'pull' ],
90 mkdir => [ 'push', 'conflict:client' ],
91 delete => [ 'delete_remote' ],
92 ack => [ 'pull', 'delete_local', 'conflict:remote' ],
93 );
94  
95 # The flags a forced command may carry, and the pinned field each must match.
96 313 Readonly my %FORCED_FLAGS => (repo => 'repo', client => 'client', role => 'role', proto => 'proto');
97  
98 =encoding utf8
99  
100 =head1 NAME
101  
102 App::FileSync::Server - serve one sync session against a repo's master
103  
104 =head1 SYNOPSIS
105  
106 my $server = App::FileSync::Server->new(
107 root => '/srv/filesync', repo => 'docs', client => 'laptop', role => 'client',
108 connection => App::FileSync::Protocol->new(in => \*STDIN, out => \*STDOUT),
109 );
110 exit($server->run ? 0 : 1);
111  
112 =head1 DESCRIPTION
113  
114 A session is: hello, manifest, plan, then the transfers the plan lists, then
115 C<done>. The server holds the repo lock throughout, so sessions on one repo
116 never interleave. It updates the master index and the client's base only in
117 C<done>, after every planned action has been applied; a session that dies part
118 way leaves both as they were, and the next session replans from the tree.
119  
120 =head1 METHODS
121  
122 =head2 new
123  
124 Purpose: prepare a session.
125  
126 Args: C<root>, C<repo>, C<client>, C<role> (C<client> or C<replica>),
127 C<connection> (an L<App::FileSync::Protocol>), optional C<logger> and
128 C<language>.
129  
130 Returns: the server object.
131  
132 Side Effects: builds a logger from the settings when none is given.
133  
134 Usage:
135  
136 my $server = App::FileSync::Server->new(%pinned, connection => $connection);
137  
138 =head3 EXAMPLE
139  
140 my $server = App::FileSync::Server->new(
141 root => $root, repo => 'docs', client => 'laptop', role => 'client', connection => $conn,
142 );
143  
144 =head3 API SPECIFICATION
145  
146 =head4 INPUT
147  
148 {
149 root => { type => 'string', min => 1 },
150 repo => { type => 'string', min => 1, max => 64 },
151 client => { type => 'string', min => 1, max => 64 },
152 role => { type => 'string', memberof => [ 'client', 'replica' ] },
153 connection => { type => 'object', can => [ 'send', 'recv' ] },
154 logger => { type => 'object', optional => 1 },
155 language => { type => 'string', optional => 1 },
156 }
157  
158 =head4 OUTPUT
159  
160 { type => 'object', isa => 'App::FileSync::Server' }
161  
162 =head3 MESSAGES
163  
164 Key Meaning Resolution
165 server.missing a required argument is absent pass it
166 server.bad_role role is not client or replica fix the forced command
167 server.bad_id repo or client is not an id fix the forced command
168 server.no_connection no connection was given pass connection
169  
170 =head3 FORMAL SPECIFICATION
171  
172 pre root ≠ "" ∧ repo ∈ Id ∧ client ∈ Id ∧ role ∈ {client, replica} ∧ connection ≠ ⊥
173 post finished = 0 ∧ plan = ∅ ∧ uploads = ∅
174  
175 =cut
176  
177 179 ▶sub new {
Subroutine new: called CC=9 SCAR=23.9
Pod documented
178 179 my $class = shift;
179 179 my $args = named(\@_, {
180 root => { type => 'string', optional => 1 },
181 repo => { type => 'string', optional => 1 },
182 client => { type => 'string', optional => 1 },
183 role => { type => 'string', optional => 1 },
184 connection => { type => 'object', optional => 1 },
185 logger => { type => 'object', optional => 1 },
186 language => { type => 'string', optional => 1 },
187 }, 'Server->new');
188  
189 # Checked here rather than by the schema so the messages read as a
190 # server refusal rather than an argument error.
191 179 for my $required (qw(root repo client role)) {
192 App::FileSync::I18N::throw('server.missing', { what => $required })
193 716 ▶ unless defined $args->{$required} && length $args->{$required};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args->{$required} and length $args->{$required} 0 716 716
Condition33%1/3
defined $args->{$required} and length $args->{$required}
!ll&&!rl&&r
00716
MC/DC0%0/2
defined $args->{$required} and length $args->{$required}
defined $args->{$required} length $args->{$required}
Truth table33%1/3
A and B
A= defined $args->{$required}B= length $args->{$required}
ABresult
0X0
100
111
194 }
195 App::FileSync::I18N::throw('server.bad_role', { role => $args->{role} })
196 179 ▶ unless any { $_ eq $args->{role} } @ROLES;
Subroutine __ANON__: called CC=1 SCAR=0.2
Branch: 1 branch
BranchTrueFalseTotal
unless &any(sub { $_ eq $args->{"role"}; } , @App::FileSync::Server::ROLES) 0 179 179
197  
198 179 for my $check ([ repo => \&validate_repo_name ], [ client => \&validate_client_id ]) {
199 358 my ($field, $validate) = @{$check};
200 358 my ($ok, $reason) = $validate->($args->{$field});
201 358 ▶ App::FileSync::I18N::throw('server.bad_id', { reason => $reason }) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 358 358
202 }
203 179 ▶ App::FileSync::I18N::throw('server.no_connection') unless $args->{connection};
Branch: 1 branch
BranchTrueFalseTotal
unless $args->{"connection"} 0 179 179
204  
205 return bless {
206 895 ▶ (map { $_ => $args->{$_} } qw(root repo client role language)),
Condition33%1/3
$args->{'logger'} || App::FileSync::Settings::logger()
l!l&&r!l&&!r
17900
MC/DC0%0/2
$args->{'logger'} || App::FileSync::Settings::logger()
$args->{'logger'} App::FileSync::Settings::logger()
Truth table33%1/3
A || B
A= $args->{'logger'}B= App::FileSync::Settings::logger()
ABresult
1X1
011
000
207 conn => $args->{connection},
208 179 logger => $args->{logger} || App::FileSync::Settings::logger(),
209 dry_run => 0,
210 force => 0,
211 finished => 0,
212 uploads => {},
213 pull_deltas => {},
214 client_manifest => {},
215 plan => {},
216 index => {},
217 base => {},
218 base_after => {},
219 applied => {},
220 }, $class;
221 }
222  
223 =head2 run
224  
225 Purpose: serve the whole session.
226  
227 Args: none.
228  
229 Returns: 1 when the session finished, 0 when it failed (the client has been
230 sent the error).
231  
232 Side Effects: takes the repo lock; reads and writes the master, its index, the
233 client's base, the trash and the journal; prunes the trash and removes stale
234 temporaries. A failed session is journalled (exit 2 for a lock refusal,
235 otherwise 1) unless it never got as far as opening the repo.
236  
237 Usage:
238  
239 exit($server->run ? 0 : 1);
240  
241 =head3 EXAMPLE
242  
243 my $ok = $server->run;
244 warn "session failed\n" unless $ok;
245  
246 =head3 API SPECIFICATION
247  
248 =head4 INPUT
249  
250 [ { name => 'self', type => 'object' } ]
251  
252 =head4 OUTPUT
253  
254 { type => 'integer', memberof => [ 0, 1 ] }
255  
256 =head3 MESSAGES
257  
258 Key Meaning Resolution
259 server.locked another session holds the lock the client retries later
260 server.not_allowed the client is not registered filesync-admin client allow
261 server.wrong_role the client is registered otherwise fix the key's --role
262 server.proto the client speaks another protocol upgrade one side
263 server.pinned the hello disagrees with the pin fix the client config
264 server.unknown an unknown command arrived upgrade one side
265  
266 Raised once the session is open. Each ends the session: the open uploads
267 are discarded, the failure is journalled, and the text (without Perl's
268 file and line) reaches the client as C<< { ok => 0, fatal => 1, error => ... } >>.
269 Most mean a client bug or a hostile client; the resolution is to fix the
270 client, or simply to rerun the sync.
271  
272 Key Meaning
273 server.manifest_list the manifest is not a list
274 server.manifest_entry a manifest entry is not an object
275 server.manifest_path a manifest path is unsafe
276 server.manifest_field a manifest t, h, s, m or mode field is malformed
277 server.refused the deletion guard stopped the plan (rerun with --force if intended)
278 server.unplanned an operation names a path that is not in the plan
279 server.not_planned the path's planned action does not allow this operation
280 server.bad_field an off, max, len, s, mode or h field is malformed
281 server.conflict_name the conflict copy is named other than the plan says
282 server.conflict_unsafe the planned conflict name is not a safe path
283 server.conflict_same the planned conflict name equals the path
284 server.conflict_exists something already exists at the conflict name
285 server.conflict_move the master's copy could not be moved aside
286 server.bad_ack an ack disagrees with the planned action
287 server.busy a second put for a path already being received
288 server.no_put chunk or chunk_end without a put
289 server.too_large one chunk is larger than the chunk limit
290 server.overflow the upload is larger than its announced size
291 server.hash_mismatch the received content does not have the announced hash
292 server.size_mismatch the received content does not have the announced size
293 server.no_delta delta data without a delta start
294 server.bad_copy a delta copy reaches outside the base file
295 server.bad_signature a pull signature is malformed
296 server.no_signature a pull delta operation without a signature
297 server.cannot_stat a planned file vanished from the master
298 server.not_file a get for a path that is a directory
299 server.unfinished done arrived before every planned action completed
300  
301 =head3 FORMAL SPECIFICATION
302  
303 ΔFS
304 run = 1 ⇔ hello ⨾ open ⨾ lock ⨾ loop ⨾ done succeed
305 run = 0 ⇒ index' = index ∧ base' = base
306  
307 =head3 PSEUDOCODE
308  
309 read and check the hello against the pinned arguments
310 open the repo; check the client is allowed in its role
311 take the lock (refuse with code "locked" otherwise)
312 load the index and the client's base; tidy temporaries and the trash
313 send the policy, then serve commands until done
314 on any error: log it, journal the failed session, discard partial
315 uploads, and send the error to the client
316  
317 =cut
318  
319 179 ▶sub run {
Subroutine run: called CC=6 SCAR=17.9
Pod documented
320 179 my ($self) = @_;
321  
322 179 my $connection = $self->{conn};
323  
324 179 my $ok = eval {
325 179 $self->_validate_hello($connection->recv());
326  
327 my $store = $self->{store} = App::FileSync::Store->new(
328 root => $self->{root}, repo => $self->{repo}, language => $self->{language},
329 178 );
330 178 $self->_check_client_allowed();
331  
332 177 $self->{lock} = $store->acquire_lock();
333 177 ▶ unless ($self->{lock}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"lock"}) 3 174 177
334 3 $self->{refusal} = 'locked';
335 3 $self->_throw('server.locked', { repo => $self->{repo} });
336 }
337  
338 174 $self->{index} = $store->load_index();
339 174 $self->{base} = $store->load_base($self->{client});
340 174 $store->clean_stale_temps();
341 174 ▶ $store->prune_trash() unless $self->{dry_run};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"dry_run"} 166 8 174
342  
343 174 $self->{logger}->info('session opened', { map { $_ => $self->{$_} } qw(repo client role) });
344  
345 174 my $policy = $store->config();
346 $connection->send({
347 ok => 1,
348 proto => $PROTO,
349 server => { os => $^O },
350 repo => { name => $self->{repo} },
351 174 policy => { map { $_ => $policy->{$_} } qw(ignore trash_days max_deletes max_delete_percent) },
352 });
353  
354 174 $self->_loop();
355 155 1;
356 };
357  
358 179 ▶ return 1 if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 155 24 179
359  
360 # The client shows this text to a person, so no Perl file and line.
361 24 ▶ my $error = strip_location($@) || $self->i18n('server.unknown_error');
Condition33%1/3
strip_location($@) || $self->i18n('server.unknown_error')
l!l&&r!l&&!r
2400
MC/DC0%0/2
strip_location($@) || $self->i18n('server.unknown_error')
strip_location($@) $self->i18n('server.unknown_error')
Truth table33%1/3
A || B
A= strip_location($@)B= $self->i18n('server.unknown_error')
ABresult
1X1
011
000
362 24 $self->{logger}->error($error);
363 24 $self->_discard_uploads();
364 24 $self->_journal_failed_session($error);
365  
366 24 eval {
367 24 ▶ $connection->send({ ok => 0, error => $error, fatal => 1, ($self->{refusal} ? (code => $self->{refusal}) : ()) });
Branch: 1 branch
BranchTrueFalseTotal
$self->{'refusal'} ? : 3 21 24
368 };
369 24 return 0;
370 }
371  
372 =head2 validate_forced_command
373  
374 Purpose: check the command a client asked sshd to run against the arguments
375 pinned in F<authorized_keys>.
376  
377 The pinned arguments are the authority for a session. sshd passes the command
378 the client asked for in C<SSH_ORIGINAL_COMMAND>; it must agree with the pinned
379 repo, client, role and protocol and ask for nothing else: in particular it may
380 not choose its own C<--root>.
381  
382 Args: C<$original> (the requested command; undef or blank is accepted),
383 C<\%pinned> (C<repo>, C<client>, C<role>).
384  
385 Returns: C<(1, undef)> or C<(0, $reason)>. A list, deliberately: callers
386 write C<my ($ok, $why) = ...>, matching L<App::FileSync/validate_relpath>.
387  
388 Side Effects: none.
389  
390 Usage:
391  
392 my ($ok, $reason) = App::FileSync::Server::validate_forced_command($ENV{SSH_ORIGINAL_COMMAND}, \%pinned);
393  
394 =head3 EXAMPLE
395  
396 my ($ok, $why) = App::FileSync::Server::validate_forced_command(
397 'filesync-server --repo docs --client laptop --role client --proto 2',
398 { repo => 'docs', client => 'laptop', role => 'client' },
399 ); # (1, undef)
400  
401 =head3 API SPECIFICATION
402  
403 =head4 INPUT
404  
405 [
406 { name => 'original', type => 'string', optional => 1 },
407 { name => 'pinned', type => 'hashref' },
408 ]
409  
410 =head4 OUTPUT
411  
412 { type => 'arrayref', min => 2, max => 2 } # returned as a two-element list
413  
414 =head3 MESSAGES
415  
416 Key Meaning
417 forced.program the command runs some other program
418 forced.argument a token is not a --flag
419 forced.no_value a flag has no value
420 forced.flag the flag is not repo, client, role or proto
421 forced.proto the protocol differs from this server's
422 forced.pinned the value differs from the pinned one
423  
424 =head3 FORMAL SPECIFICATION
425  
426 let ts = tokens(original)
427 ok ⇔ (ts = ⟨⟩) ∨ ((head ts ∈ FLAG ∨ basename(head ts) = filesync-server) ∧
428 ∀ (f, v) : flags(ts) • f ∈ {repo, client, role, proto} ∧
429 (f = proto ⇒ v = PROTO) ∧ (f ≠ proto ⇒ v = pinned(f)))
430  
431 =head3 PSEUDOCODE
432  
433 accept an empty command
434 split on white space; allow a leading filesync-server path
435 for each --flag[=value] (value from the next token if not attached):
436 reject an unknown flag, a missing value, a wrong protocol
437 reject a value that differs from the pinned one
438  
439 =cut
440  
441 28 ▶sub validate_forced_command {
Subroutine validate_forced_command: called CC=15 SCAR=27.1
Pod documented
442 28 my ($original, $pinned) = @_;
443  
444 28 ▶ my @tokens = defined $original ? split(' ', $original) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $original ? : 27 1 28
445 28 ▶ return (1, undef) unless @tokens;
Branch: 1 branch
BranchTrueFalseTotal
unless @tokens 3 25 28
446  
447 25 ▶ if ($tokens[0] !~ /\A--/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tokens[0] =~ /\A--/) 24 1 25
448 24 my $program = shift @tokens;
449 24 ▶ return (0, message('forced.program', { program => $program }))
Branch: 1 branch
BranchTrueFalseTotal
unless $program =~ m[(?:\A|/)\Q$App::FileSync::Server::SERVER_PROGRAM\E\z] 1 23 24
450 unless $program =~ m{(?:\A|/)\Q$SERVER_PROGRAM\E\z};
451 }
452  
453 24 ▶ while (@tokens) {
Branch: 1 branch
BranchTrueFalseTotal
if (@tokens) 75 13 88
454 75 my $token = shift @tokens;
455 75 ▶ return (0, message('forced.argument', { token => $token }))
Branch: 1 branch
BranchTrueFalseTotal
unless $token =~ /\A--([a-z][a-z-]*)(?:=(.*))?\z/s 1 74 75
456 unless $token =~ /\A--([a-z][a-z-]*)(?:=(.*))?\z/s;
457  
458 74 my ($flag, $value) = ($1, $2);
459 74 ▶ unless (defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value) 69 5 74
460 69 ▶ return (0, message('forced.no_value', { flag => $flag })) unless @tokens;
Branch: 1 branch
BranchTrueFalseTotal
unless @tokens 1 68 69
461 68 $value = shift @tokens;
462 }
463  
464 73 ▶ my $field = $FORCED_FLAGS{$flag} or return (0, message('forced.flag', { flag => $flag }));
Branch: 1 branch
BranchTrueFalseTotal
my $field = $FORCED_FLAGS{$flag} or return 0, message("forced.flag", {"flag", $flag}) 70 3 73
465  
466 70 ▶ if ($field eq 'proto') {
Branch: 1 branch
BranchTrueFalseTotal
if ($field eq "proto") 13 57 70
467 13 ▶ return (0, message('forced.proto', { proto => $value })) unless $value eq $PROTO;
Branch: 1 branch
BranchTrueFalseTotal
unless $value eq $App::FileSync::Server::PROTO 1 12 13
468 12 next;
469 }
470  
471 57 my $expected = $pinned->{$field};
472 57 ▶ return (0, message('forced.pinned', { field => $field, value => $value, expected => $expected // '' }))
Branch: 1 branch
BranchTrueFalseTotal
unless defined $expected and $value eq $expected 5 52 57
Condition60%3/5
defined $expected and $value eq $expected
!ll&&!rl&&r
0552
$expected // ""
l!l
50
MC/DC50%1/2
defined $expected and $value eq $expected
defined $expected $value eq $expected
MC/DC0%0/1
$expected // ""
$expected
Truth table66%2/3
A and B
A= defined $expectedB= $value eq $expected
ABresult
0X0
100
111
Truth table50%1/2
A
A= $expected
Aresult
11
00
473 unless defined $expected && $value eq $expected;
474 }
475  
476 13 return (1, undef);
477 }
478  
479 # _journal_failed_session
480 # Purpose: record a session that never reached done, so the admin sees
481 # the attempt with the same exit code the client records.
482 # Entry: $error is the message sent to the client.
483 # Exit: returns 1 if journalled, else 0.
484 # Side effects: appends to the journal. Nothing is journalled without a store
485 # (a bad hello, say) or on a dry run, and a journal write that
486 # fails is logged, never allowed to mask the original error.
487 24 ▶sub _journal_failed_session :Private {
Subroutine _journal_failed_session: called CC=10 SCAR=24.3
488 24 my ($self, $error) = @_;
489  
490 24 ▶ return 0 if $self->{finished} || $self->{session_journalled} || $self->{dry_run} || !$self->{store};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"finished"} or $self->{"session_journalled"} or $self->{"dry_run"} or not $self->{"store"} 1 23 24
Condition44%4/9
$self->{"finished"} or $self->{"session_journalled"} or $self->{"dry_run"} or not $self->{"store"}
l!l&&r!l&&!r
0123
$self->{"finished"} or $self->{"session_journalled"} or $self->{"dry_run"}
l!l&&r!l&&!r
0024
$self->{"finished"} or $self->{"session_journalled"}
l!l&&r!l&&!r
0024
MC/DC25%1/4
$self->{"finished"} or $self->{"session_journalled"} or $self->{"dry_run"} or not $self->{"store"}
$self->{"finished"} $self->{"session_journalled"} $self->{"dry_run"} not $self->{"store"}
Truth table40%2/5
A or B or C or not(D)
A= $self->{"finished"}B= $self->{"session_journalled"}C= $self->{"dry_run"}D= not $self->{"store"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
491  
492 23 ▶ my $locked = ($self->{refusal} || '') eq 'locked';
Condition100%2/2
$self->{'refusal'} || ''
l!l
320
MC/DC100%1/1
$self->{'refusal'} || ''
$self->{'refusal'}
Truth table100%2/2
A
A= $self->{'refusal'}
Aresult
11
00
493 23 my $ok = eval {
494 23 ▶ $self->_journal({
Branch: 2 branches
BranchTrueFalseTotal
$locked ? : 3 20 23
$locked ? : 3 20 23
495 action => 'session',
496 result => 'error',
497 exit => $locked ? $EXIT_LOCKED : $EXIT_FATAL,
498 error => $error,
499 ($locked ? (locked => 1) : ()),
500 });
501 23 1;
502 };
503 23 ▶ $self->{logger}->warn($self->i18n('server.journal_failed', { error => strip_location($@) })) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 23 23
504  
505 23 ▶ return $ok ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 23 0 23
506 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
507  
508 # _validate_hello
509 # Purpose: check the client's hello against the pinned session.
510 # Entry: $hello is the first message.
511 # Exit: returns 1.
512 # Side effects: records dry_run and force; raises server.proto or
513 # server.pinned.
514 178 ▶sub _validate_hello :Private {
Subroutine _validate_hello: called CC=8 SCAR=21.8
515 178 my ($self, $hello) = @_;
516  
517 178 ▶ $self->_throw('server.proto') unless defined $hello->{proto} && $hello->{proto} eq $PROTO;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hello->{"proto"} and $hello->{"proto"} eq $App::FileSync::Server::PROTO 0 178 178
Condition33%1/3
defined $hello->{"proto"} and $hello->{"proto"} eq $App::FileSync::Server::PROTO
!ll&&!rl&&r
00178
MC/DC0%0/2
defined $hello->{"proto"} and $hello->{"proto"} eq $App::FileSync::Server::PROTO
defined $hello->{"proto"} $hello->{"proto"} eq $App::FileSync::Server::PROTO
Truth table33%1/3
A and B
A= defined $hello->{"proto"}B= $hello->{"proto"} eq $App::FileSync::Server::PROTO
ABresult
0X0
100
111
518  
519 178 for my $field (qw(client repo role)) {
520 534 ▶ my $given = $hello->{$field} // '';
Condition50%1/2
$hello->{$field} // ""
l!l
5340
MC/DC0%0/1
$hello->{$field} // ""
$hello->{$field}
Truth table50%1/2
A
A= $hello->{$field}
Aresult
11
00
521 $self->_throw('server.pinned', { field => $field, expected => $self->{$field}, given => $given })
522 534 ▶ unless $given eq $self->{$field};
Branch: 1 branch
BranchTrueFalseTotal
unless $given eq $self->{$field} 0 534 534
523 }
524  
525 # case_insensitive is part of the hello but only the client acts on it.
526 178 ▶ $self->{dry_run} = $hello->{dry_run} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$hello->{'dry_run'} ? : 8 170 178
527 178 ▶ $self->{force} = $hello->{force} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$hello->{'force'} ? : 8 170 178
528 178 return 1;
529 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
530  
531 # _check_client_allowed
532 # Purpose: enforce the repo's client list.
533 # Entry: the store is open.
534 # Exit: returns 1.
535 # Side effects: raises server.not_allowed or server.wrong_role. An empty
536 # list allows everyone (a repo nobody has restricted yet).
537 178 ▶sub _check_client_allowed :Private {
Subroutine _check_client_allowed: called CC=7 SCAR=21.5
538 178 my ($self) = @_;
539  
540 178 ▶ my $clients = $self->{store}->config()->{clients} || {};
Condition50%1/2
$self->{'store'}->config->{'clients'} || {}
l!l
1780
MC/DC0%0/1
$self->{'store'}->config->{'clients'} || {}
$self->{'store'}->config->{'clients'}
Truth table50%1/2
A
A= $self->{'store'}->config->{'clients'}
Aresult
11
00
541 178 ▶ return 1 unless %{$clients};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$clients;} 0 178 178
542  
543 my $entry = $clients->{ $self->{client} }
544 178 ▶ or $self->_throw('server.not_allowed', { client => $self->{client}, repo => $self->{repo} });
Branch: 1 branch
BranchTrueFalseTotal
my $entry = $$clients{$self->{"client"}} or $self->_throw("server.not_allowed", {"client", $self->{"client"}, "repo", $self->{"repo"}}) 177 1 178
545  
546 177 ▶ my $role = (ref($entry) eq 'HASH' && $entry->{role}) || $ROLE_CLIENT;
Condition33%2/6
ref $entry eq 'HASH' && $entry->{'role'} || $App::FileSync::Server::ROLE_CLIENT
l!l&&r!l&&!r
17700
ref $entry eq "HASH" and $entry->{"role"}
!ll&&!rl&&r
00177
MC/DC0%0/3
ref $entry eq 'HASH' && $entry->{'role'} || $App::FileSync::Server::ROLE_CLIENT
ref $entry eq "HASH" $entry->{"role"} $App::FileSync::Server::ROLE_CLIENT
Truth table20%1/5
A and B || C
A= ref $entry eq "HASH"B= $entry->{"role"}C= $App::FileSync::Server::ROLE_CLIENT
ABCresult
11X1
0X11
1011
0X00
1000
547 $self->_throw('server.wrong_role', { client => $self->{client}, registered => $role, asked => $self->{role} })
548 177 ▶ unless $role eq $self->{role};
Branch: 1 branch
BranchTrueFalseTotal
unless $role eq $self->{"role"} 0 177 177
549  
550 177 return 1;
551 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
552  
553 # _loop
554 # Purpose: serve commands until done.
555 # Entry: the hello has been answered.
556 # Exit: returns 1 once _finish has run.
557 # Side effects: whatever the commands do; raises server.unknown.
558 174 ▶sub _loop :Private {
Subroutine _loop: called CC=4 SCAR=14.0
559 174 my ($self) = @_;
560  
561 174 ▶ until ($self->{finished}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"finished"}) 1348 155 1503
562 1348 my $message = $self->{conn}->recv();
563 1345 ▶ my $command = $message->{cmd} // '';
Condition50%1/2
$message->{"cmd"} // ""
l!l
13450
MC/DC0%0/1
$message->{"cmd"} // ""
$message->{"cmd"}
Truth table50%1/2
A
A= $message->{"cmd"}
Aresult
11
00
564 1345 ▶ my $method = $COMMANDS{$command} or $self->_throw('server.unknown', { command => $command });
Branch: 1 branch
BranchTrueFalseTotal
my $method = $COMMANDS{$command} or $self->_throw("server.unknown", {"command", $command}) 1345 0 1345
565 1345 $self->$method($message);
566 }
567  
568 155 return 1;
569 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
570  
571 # _manifest
572 # Purpose: accept (part of) the client's manifest.
573 # Entry: $message->{entries} is an arrayref of { p, t, s, m, h, mode }.
574 # Exit: returns 1 after replying ok.
575 # Side effects: adds normalised entries to client_manifest; raises
576 # server.manifest_* for anything malformed, so the plan never
577 # sees an unchecked path or field.
578 174 ▶sub _manifest :Private {
Subroutine _manifest: called CC=12 SCAR=26.2
579 174 my ($self, $message) = @_;
580  
581 174 my $entries = $message->{entries};
582 174 ▶ $self->_throw('server.manifest_list') unless ref($entries) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entries eq "ARRAY" 0 174 174
583  
584 174 for my $entry (@{$entries}) {
585 646 ▶ $self->_throw('server.manifest_entry') unless ref($entry) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 0 646 646
586  
587 646 my $path = $entry->{p};
588 646 my ($safe, $reason) = validate_relpath($path);
589 646 ▶ $self->_throw('server.manifest_path', { reason => $reason }) unless $safe;
Branch: 1 branch
BranchTrueFalseTotal
unless $safe 0 646 646
590  
591 646 ▶ my $type = $entry->{t} // $TYPE_FILE;
Condition33%1/3
$entry->{"t"} // $App::FileSync::Server::TYPE_FILE
l!l&&r!l&&!r
64600
MC/DC0%0/2
$entry->{"t"} // $App::FileSync::Server::TYPE_FILE
$entry->{"t"} $App::FileSync::Server::TYPE_FILE
Truth table33%1/3
A // B
A= $entry->{"t"}B= $App::FileSync::Server::TYPE_FILE
ABresult
1X1
011
000
592 646 ▶ $self->_throw('server.manifest_field', { field => 't', path => $path })
Branch: 1 branch
BranchTrueFalseTotal
unless $type eq $App::FileSync::Server::TYPE_FILE or $type eq $App::FileSync::Server::TYPE_DIR 0 646 646
Condition66%2/3
$type eq $App::FileSync::Server::TYPE_FILE or $type eq $App::FileSync::Server::TYPE_DIR
l!l&&r!l&&!r
622240
MC/DC0%0/2
$type eq $App::FileSync::Server::TYPE_FILE or $type eq $App::FileSync::Server::TYPE_DIR
$type eq $App::FileSync::Server::TYPE_FILE $type eq $App::FileSync::Server::TYPE_DIR
Truth table66%2/3
A or B
A= $type eq $App::FileSync::Server::TYPE_FILEB= $type eq $App::FileSync::Server::TYPE_DIR
ABresult
1X1
011
000
593 unless $type eq $TYPE_FILE || $type eq $TYPE_DIR;
594  
595 646 ▶ if ($type eq $TYPE_DIR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq $App::FileSync::Server::TYPE_DIR) 24 622 646
596 24 $self->{client_manifest}{$path} = { t => $TYPE_DIR };
597 24 next;
598 }
599  
600 622 my %field = (h => $SHA256_HEX, s => $UINT, m => $MTIME, mode => $UINT);
601 622 my %entry = (m => 0, mode => $DEFAULT_FILE_MODE, %{$entry});
602 622 for my $name (sort keys %field) {
603 $self->_throw('server.manifest_field', { field => $name, path => $path })
604 2488 ▶ unless defined $entry{$name} && $entry{$name} =~ $field{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry{$name} and $entry{$name} =~ /$field{$name}/ 0 2488 2488
Condition33%1/3
defined $entry{$name} and $entry{$name} =~ /$field{$name}/
!ll&&!rl&&r
002488
MC/DC0%0/2
defined $entry{$name} and $entry{$name} =~ /$field{$name}/
defined $entry{$name} $entry{$name} =~ /$field{$name}/
Truth table33%1/3
A and B
A= defined $entry{$name}B= $entry{$name} =~ /$field{$name}/
ABresult
0X0
100
111
605 }
606  
607 $self->{client_manifest}{$path} = {
608 t => $TYPE_FILE,
609 h => $entry{h},
610 622 (map { $_ => $entry{$_} + 0 } qw(s m mode)),
611 };
612 }
613  
614 174 $self->{conn}->send({ ok => 1 });
615 174 return 1;
616 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
617  
618 # _plan
619 # Purpose: plan the session and send it to the client.
620 # Entry: the manifest has arrived.
621 # Exit: returns 1 after sending the actions.
622 # Side effects: rescans the master (reusing the index's hashes); stores the
623 # plan; journals it unless dry run; raises the delete guard's
624 # refusal when the plan deletes too much.
625 174 ▶sub _plan :Private {
Subroutine _plan: called CC=3 SCAR=11.0
626 174 my ($self) = @_;
627  
628 174 my $store = $self->{store};
629 174 my $master = $self->{index} = $store->walk_master($self->{index})->{manifest};
630 174 my $config = $store->config();
631  
632 my $plan = App::FileSync::Merge::plan(
633 base => $self->{base},
634 client => $self->{client_manifest},
635 master => $master,
636 client_id => $self->{client},
637 role => $self->{role},
638 174 now => time,
639 );
640  
641 my $refusal = App::FileSync::Merge::check_delete_limit(
642 deletions => $plan->{deletions},
643 174 base_size => scalar(keys %{ $self->{base} }),
644 max_deletes => $config->{max_deletes},
645 max_delete_percent => $config->{max_delete_percent},
646 force => $self->{force},
647 174 );
648 174 ▶ $self->_throw('server.refused', { reason => $refusal }) if defined $refusal;
Branch: 1 branch
BranchTrueFalseTotal
if defined $refusal 6 168 174
649  
650 168 $self->_unique_loser_names($plan->{actions});
651  
652 168 $self->{plan} = { map { $_->{p} => $_ } @{ $plan->{actions} } };
653 168 $self->{base_after} = { %{ $self->{client_manifest} } };
654  
655 my %counts = (
656 168 actions => scalar @{ $plan->{actions} },
657 deletions => $plan->{deletions},
658 conflicts => $plan->{conflicts},
659 dry_run => $self->{dry_run},
660 168 );
661 168 $self->{logger}->debug('plan', { repo => $self->{repo}, client => $self->{client}, %counts });
662 168 ▶ $self->_journal({ action => 'plan', %counts }) unless $self->{dry_run};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"dry_run"} 160 8 168
663  
664 168 $self->{conn}->send({ ok => 1, actions => $plan->{actions}, warnings => $plan->{warnings} });
665 168 return 1;
666 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
667  
668 # _unique_loser_names
669 # Purpose: make every conflict-copy name unique against the master and
670 # the rest of the plan.
671 # Entry: $actions from Merge::plan.
672 # Exit: returns 1.
673 # Side effects: rewrites loser_name in place. Two conflicts resolved in the
674 # same second would otherwise pick the same name.
675 168 ▶sub _unique_loser_names :Private {
Subroutine _unique_loser_names: called CC=5 SCAR=16.6
676 168 my ($self, $actions) = @_;
677  
678 168 my %used;
679 168 ▶ for my $action (grep { $_->{a} eq 'conflict' && defined $_->{loser_name} } @{$actions}) {
Condition66%2/3
$_->{'a'} eq 'conflict' && defined $_->{'loser_name'}
!ll&&!rl&&r
342015
MC/DC50%1/2
$_->{'a'} eq 'conflict' && defined $_->{'loser_name'}
$_->{'a'} eq 'conflict' defined $_->{'loser_name'}
Truth table66%2/3
A && B
A= $_->{'a'} eq 'conflict'B= defined $_->{'loser_name'}
ABresult
0X0
100
111
680 15 my ($name, $suffix) = ($action->{loser_name}, 1);
681 $name = name_with_suffix($action->{loser_name}, ++$suffix)
682 15 ▶ while $used{$name} || exists $self->{index}{$name};
Branch: 1 branch
BranchTrueFalseTotal
$used{$name} || exists $self->{"index"}{$name} and do { $name = name_with_suffix($action->{"loser_name"}, ++$suffix) } 0 15 15
Condition33%1/3
$used{$name} or exists $self->{"index"}{$name}
l!l&&r!l&&!r
0015
MC/DC0%0/2
$used{$name} or exists $self->{"index"}{$name}
$used{$name} exists $self->{"index"}{$name}
Truth table33%1/3
A or B
A= $used{$name}B= exists $self->{"index"}{$name}
ABresult
1X1
011
000
683 15 $used{$name} = 1;
684 15 $action->{loser_name} = $name;
685 }
686  
687 168 return 1;
688 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
689  
690 # _expect
691 # Purpose: the one gate every path-bearing request passes.
692 # Entry: $kind is a key of %MAY; $path is from the client.
693 # Exit: returns the planned action for $path.
694 # Side effects: raises server.unplanned when the plan has no such path and
695 # server.not_planned when it does not allow this request.
696 433 ▶sub _expect :Private {
Subroutine _expect: called CC=7 SCAR=20.4
697 433 my ($self, $kind, $path) = @_;
698  
699 433 my $what = $self->i18n("server.op.$kind");
700 433 ▶ my $action = defined $path ? $self->{plan}{$path} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $path ? : 433 0 433
701 433 ▶ $self->_throw('server.unplanned', { what => $what, path => $path // '' }) unless $action;
Branch: 1 branch
BranchTrueFalseTotal
unless $action 0 433 433
Condition0%0/2
$path // ""
l!l
00
MC/DC0%0/1
$path // ""
$path
Truth table0%0/2
A
A= $path
Aresult
11
00
702  
703 433 ▶ my $label = $action->{a} eq 'conflict' ? "conflict:" . ($action->{winner} // '') : $action->{a};
Branch: 1 branch
BranchTrueFalseTotal
$action->{'a'} eq 'conflict' ? : 19 414 433
Condition50%1/2
$action->{"winner"} // ""
l!l
190
MC/DC0%0/1
$action->{"winner"} // ""
$action->{"winner"}
Truth table50%1/2
A
A= $action->{"winner"}
Aresult
11
00
704 $self->_throw('server.not_planned', { what => $what, path => $path })
705 433 ▶ unless any { $_ eq $label } @{ $MAY{$kind} };
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless &any(sub { $_ eq $label; } , @{$MAY{$kind};}) 2 431 433
706  
707 431 return $action;
708 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
709  
710 # _get
711 # Purpose: send one chunk of a master file the client is pulling.
712 # Entry: $message has p, optional off and max.
713 # Exit: returns 1 after sending the chunk.
714 # Side effects: reads the master; raises server.bad_field for a malformed
715 # offset or size, server.not_file and io.* errors. max is
716 # clamped to MAX_CHUNK_BYTES so a client cannot ask the server to
717 # buffer an entire large file.
718 95 ▶sub _get :Private {
Subroutine _get: called CC=6 SCAR=17.9
719 95 my ($self, $message) = @_;
720  
721 95 my $path = $message->{p};
722 95 $self->_expect('read', $path);
723  
724 95 my $offset = $self->_uint($message, 'off', 0);
725 93 my $max = $self->_uint($message, 'max', $CHUNK);
726 92 ▶ $max = $MAX_CHUNK_BYTES if $max > $MAX_CHUNK_BYTES;
Branch: 1 branch
BranchTrueFalseTotal
if $max > $App::FileSync::Server::MAX_CHUNK_BYTES 1 91 92
727  
728 92 my $abs = $self->{store}->abs_path($path);
729 92 my $file = $self->_file_stat($abs, $path);
730 92 ▶ $self->_throw('server.bad_field', { field => 'off', path => $path }) if $offset > $file->{s};
Branch: 1 branch
BranchTrueFalseTotal
if $offset > $file->{"s"} 1 91 92
731  
732 91 my $length = $file->{s} - $offset;
733 91 ▶ $length = $max if $length > $max;
Branch: 1 branch
BranchTrueFalseTotal
if $length > $max 2 89 91
734  
735 91 my $bytes = '';
736 91 ▶ if ($length > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($length > 0) 91 0 91
737 91 my $fh = App::FileSync::IO::open_file($abs, '<:raw');
738 91 seek($fh, $offset, 0);
739 91 $bytes = App::FileSync::Delta::read_exact($fh, $length, $abs);
740 91 close $fh;
741 }
742  
743 91 ▶ $self->{conn}->send_data({ ok => 1, eof => ($offset + $length >= $file->{s}) ? 1 : 0, %{$file} }, $bytes);
Branch: 1 branch
BranchTrueFalseTotal
$offset + $length >= $file->{'s'} ? : 89 2 91
744 91 return 1;
745 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
746  
747 # _put
748 # Purpose: start receiving a whole file the client is pushing.
749 # Entry: $message has p, s, h, m, mode; conflict_name is optional and,
750 # when sent, must equal the plan's loser_name.
751 # Exit: returns 1 after replying ok with off 0.
752 # Side effects: for a conflict the client won, moves the master's version
753 # aside under the plan's name first - whatever the client
754 # sends, so a client that omits the name cannot overwrite the
755 # master's losing version. Opens a temporary file.
756 180 ▶sub _put :Private {
Subroutine _put: called CC=5 SCAR=16.1
757 180 my ($self, $message) = @_;
758  
759 180 my $path = $message->{p};
760 180 my $action = $self->_expect('write', $path);
761  
762 179 ▶ if ($action->{a} eq 'conflict' && defined $action->{loser_name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($action->{"a"} eq "conflict" and defined $action->{"loser_name"}) 7 172 179
Condition66%2/3
$action->{"a"} eq "conflict" and defined $action->{"loser_name"}
!ll&&!rl&&r
17207
MC/DC50%1/2
$action->{"a"} eq "conflict" and defined $action->{"loser_name"}
$action->{"a"} eq "conflict" defined $action->{"loser_name"}
Truth table66%2/3
A and B
A= $action->{"a"} eq "conflict"B= defined $action->{"loser_name"}
ABresult
0X0
100
111
763 $self->_throw('server.conflict_name', { path => $path, expected => $action->{loser_name} })
764 7 ▶ if defined $message->{conflict_name} && $message->{conflict_name} ne $action->{loser_name};
Branch: 1 branch
BranchTrueFalseTotal
if defined $message->{"conflict_name"} and $message->{"conflict_name"} ne $action->{"loser_name"} 1 6 7
Condition100%3/3
defined $message->{"conflict_name"} and $message->{"conflict_name"} ne $action->{"loser_name"}
!ll&&!rl&&r
241
MC/DC100%2/2
defined $message->{"conflict_name"} and $message->{"conflict_name"} ne $action->{"loser_name"}
defined $message->{"conflict_name"} $message->{"conflict_name"} ne $action->{"loser_name"}
Truth table100%3/3
A and B
A= defined $message->{"conflict_name"}B= $message->{"conflict_name"} ne $action->{"loser_name"}
ABresult
0X0
100
111
765 6 $self->_preserve_loser($path, $action->{loser_name}, { sha256 => $message->{h}, mtime => $message->{m} });
766 }
767  
768 178 $self->_open_upload($path, $message);
769 178 $self->{conn}->send({ ok => 1, off => 0 });
770 178 return 1;
771 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
772  
773 # _chunk
774 # Purpose: receive one chunk of a whole-file upload.
775 # Entry: a put for $message->{p} is open; len gives the payload size.
776 # Exit: returns 1 after replying with the new offset.
777 # Side effects: appends to the temporary file and the running hash.
778 181 ▶sub _chunk :Private {
Subroutine _chunk: called CC=5 SCAR=16.8
779 181 my ($self, $message) = @_;
780  
781 181 ▶ my $path = $message->{p} // '';
Condition50%1/2
$message->{"p"} // ""
l!l
1810
MC/DC0%0/1
$message->{"p"} // ""
$message->{"p"}
Truth table50%1/2
A
A= $message->{"p"}
Aresult
11
00
782 181 ▶ my $upload = $self->{uploads}{$path} or $self->_throw('server.no_put', { path => $path });
Branch: 1 branch
BranchTrueFalseTotal
my $upload = $self->{"uploads"}{$path} or $self->_throw("server.no_put", {"path", $path}) 181 0 181
783  
784 181 my $length = $self->_uint($message, 'len', 0);
785 181 ▶ $self->_throw('server.too_large', { path => $path }) if $length > $MAX_CHUNK_BYTES;
Branch: 1 branch
BranchTrueFalseTotal
if $length > $App::FileSync::Server::MAX_CHUNK_BYTES 0 181 181
786  
787 181 ▶ $self->_append_upload($path, $upload, $length ? $self->{conn}->read_data($message) : '');
Branch: 1 branch
BranchTrueFalseTotal
$length ? : 181 0 181
788 180 $self->{conn}->send({ ok => 1, off => $upload->{got} });
789 180 return 1;
790 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
791  
792 # _chunk_end
793 # Purpose: finish a whole-file upload.
794 # Entry: a put for $message->{p} is open.
795 # Exit: returns 1 after replying ok.
796 # Side effects: verifies and installs the file (see _commit_upload).
797 175 ▶sub _chunk_end :Private {
Subroutine _chunk_end: called CC=3 SCAR=11.2
798 175 my ($self, $message) = @_;
799  
800 175 ▶ my $path = $message->{p} // '';
Condition50%1/2
$message->{"p"} // ""
l!l
1750
MC/DC0%0/1
$message->{"p"} // ""
$message->{"p"}
Truth table50%1/2
A
A= $message->{"p"}
Aresult
11
00
801 175 ▶ my $upload = delete $self->{uploads}{$path} or $self->_throw('server.no_put', { path => $path });
Branch: 1 branch
BranchTrueFalseTotal
my $upload = delete $self->{"uploads"}{$path} or $self->_throw("server.no_put", {"path", $path}) 175 0 175
802  
803 175 $self->_commit_upload($path, $upload);
804 175 $self->{conn}->send({ ok => 1 });
805 175 return 1;
806 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
807  
808 # _signature
809 # Purpose: describe the master's current version so the client can push
810 # only the blocks that differ.
811 # Entry: $message->{p} is a planned push.
812 # Exit: returns 1 after replying; delta 0 when the file is too small
813 # or absent.
814 # Side effects: reads the master file.
815 4 ▶sub _signature :Private {
Subroutine _signature: called CC=4 SCAR=13.9
816 4 my ($self, $message) = @_;
817  
818 4 my $path = $message->{p};
819 4 $self->_expect('delta', $path);
820  
821 4 my $abs = $self->{store}->abs_path($path);
822 4 ▶ my $signature = (-f $abs && (-s _) >= $App::FileSync::Delta::MIN_SIZE)
Branch: 1 branch
BranchTrueFalseTotal
-f $abs && -s _ >= $App::FileSync::Delta::MIN_SIZE ? : 1 3 4
Condition66%2/3
-f $abs and -s _ >= $App::FileSync::Delta::MIN_SIZE
!ll&&!rl&&r
301
MC/DC50%1/2
-f $abs and -s _ >= $App::FileSync::Delta::MIN_SIZE
-f $abs -s _ >= $App::FileSync::Delta::MIN_SIZE
Truth table66%2/3
A and B
A= -f $absB= -s _ >= $App::FileSync::Delta::MIN_SIZE
ABresult
0X0
100
111
823 ? App::FileSync::Delta::signature($abs)
824 : undef;
825  
826 4 ▶ return $self->_reply({ ok => 1, delta => 0 }) unless $signature;
Branch: 1 branch
BranchTrueFalseTotal
unless $signature 3 1 4
827  
828 $self->{conn}->send_data({
829 ok => 1,
830 delta => 1,
831 s => $signature->{size},
832 b => $signature->{blocklen},
833 1 n => scalar @{ $signature->{blocks} },
834 }, App::FileSync::Delta::encode_signature($signature));
835 1 return 1;
836 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
837  
838 # _delta_start
839 # Purpose: start receiving a pushed file as a delta against the master.
840 # Entry: $message has p, h, s, m, mode.
841 # Exit: returns 1 after replying ok.
842 # Side effects: opens a temporary file and, when the master has the file,
843 # a read handle on it for copy records.
844 1 ▶sub _delta_start :Private {
Subroutine _delta_start: called CC=4 SCAR=14.2
845 1 my ($self, $message) = @_;
846  
847 1 my $path = $message->{p};
848 1 $self->_expect('delta', $path);
849 $self->_throw('server.bad_field', { field => 'h', path => $path })
850 1 ▶ unless defined $message->{h} && $message->{h} =~ $SHA256_HEX;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $message->{"h"} and $message->{"h"} =~ /$App::FileSync::Server::SHA256_HEX/ 0 1 1
Condition33%1/3
defined $message->{"h"} and $message->{"h"} =~ /$App::FileSync::Server::SHA256_HEX/
!ll&&!rl&&r
001
MC/DC0%0/2
defined $message->{"h"} and $message->{"h"} =~ /$App::FileSync::Server::SHA256_HEX/
defined $message->{"h"} $message->{"h"} =~ /$App::FileSync::Server::SHA256_HEX/
Truth table33%1/3
A and B
A= defined $message->{"h"}B= $message->{"h"} =~ /$App::FileSync::Server::SHA256_HEX/
ABresult
0X0
100
111
851 1 $self->_uint($message, 's');
852  
853 1 my $upload = $self->_open_upload($path, $message);
854 1 $upload->{delta} = 1;
855  
856 1 my $old = $self->{store}->abs_path($path);
857 1 ▶ if (-f $old) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $old) 1 0 1
858 1 @{$upload}{qw(old old_fh old_size)} = ($old, App::FileSync::IO::open_file($old, '<:raw'), -s _);
859 }
860  
861 1 $self->{conn}->send({ ok => 1 });
862 1 return 1;
863 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
864  
865 # _delta_copy
866 # Purpose: apply a copy record: bytes from the master's old version.
867 # Entry: a delta for p is open; off and len are integers, len > 0.
868 # Exit: returns 1 after replying with the new offset.
869 # Side effects: appends to the upload; raises server.bad_copy for a range
870 # outside the old file.
871 23 ▶sub _delta_copy :Private {
Subroutine _delta_copy: called CC=4 SCAR=14.8
872 23 my ($self, $message) = @_;
873  
874 23 my ($path, $upload) = $self->_open_delta($message);
875 23 my $offset = $self->_uint($message, 'off');
876 23 my $length = $self->_uint($message, 'len');
877  
878 $self->_throw('server.bad_copy', { path => $path })
879 23 ▶ unless $length > 0 && $upload->{old_fh} && $offset + $length <= $upload->{old_size};
Branch: 1 branch
BranchTrueFalseTotal
unless $length > 0 and $upload->{"old_fh"} and $offset + $length <= $upload->{"old_size"} 0 23 23
Condition33%2/6
$length > 0 and $upload->{"old_fh"} and $offset + $length <= $upload->{"old_size"}
!ll&&!rl&&r
0023
$length > 0 and $upload->{"old_fh"}
!ll&&!rl&&r
0023
MC/DC0%0/3
$length > 0 and $upload->{"old_fh"} and $offset + $length <= $upload->{"old_size"}
$length > 0 $upload->{"old_fh"} $offset + $length <= $upload->{"old_size"}
Truth table25%1/4
A and B and C
A= $length > 0B= $upload->{"old_fh"}C= $offset + $length <= $upload->{"old_size"}
ABCresult
0XX0
10X0
1100
1111
880  
881 23 seek($upload->{old_fh}, $offset, 0);
882 23 $self->_append_upload($path, $upload, App::FileSync::Delta::read_exact($upload->{old_fh}, $length, $upload->{old}));
883 23 $self->{conn}->send({ ok => 1, off => $upload->{got} });
884 23 return 1;
885 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
886  
887 # _delta_literal
888 # Purpose: apply a literal record: bytes sent by the client.
889 # Entry: a delta for p is open.
890 # Exit: returns 1 after replying with the new offset.
891 # Side effects: appends to the upload.
892 2 ▶sub _delta_literal :Private {
Subroutine _delta_literal: called CC=1 SCAR=0.0
893 2 my ($self, $message) = @_;
894  
895 2 my ($path, $upload) = $self->_open_delta($message);
896 2 $self->_append_upload($path, $upload, $self->{conn}->read_data($message));
897 2 $self->{conn}->send({ ok => 1, off => $upload->{got} });
898 2 return 1;
899 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
900  
901 # _delta_end
902 # Purpose: finish a delta upload.
903 # Entry: a delta for p is open.
904 # Exit: returns 1 after replying ok.
905 # Side effects: verifies and installs the file; journals it as a delta push.
906 1 ▶sub _delta_end :Private {
Subroutine _delta_end: called CC=1 SCAR=0.0
907 1 my ($self, $message) = @_;
908  
909 1 my ($path, $upload) = $self->_open_delta($message);
910 1 delete $self->{uploads}{$path};
911  
912 1 $self->_commit_upload($path, $upload, delta => 1);
913 1 $self->{conn}->send({ ok => 1, delta => 1 });
914 1 return 1;
915 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
916  
917 # _pull_signature
918 # Purpose: take the client's description of its old version and spool a
919 # delta from the master's current one.
920 # Entry: $message->{p} is a planned pull; n and b describe the blocks.
921 # Exit: returns 1 after replying; delta 0 when a delta is not worth it.
922 # Side effects: reads the master file; keeps the spool for _pull_op.
923 1 ▶sub _pull_signature :Private {
Subroutine _pull_signature: called CC=6 SCAR=18.4
924 1 my ($self, $message) = @_;
925  
926 1 my $path = $message->{p};
927 1 $self->_expect('pull', $path);
928  
929 1 my $count = $self->_uint($message, 'n');
930 1 my $block = $self->_uint($message, 'b');
931 1 ▶ $self->_throw('server.bad_signature', { path => $path })
Branch: 1 branch
BranchTrueFalseTotal
unless $count <= $MAX_SIGNATURE_BLOCKS and $block >= $MIN_SIGNATURE_BLOCK and $block <= $MAX_SIGNATURE_BLOCK 0 1 1
Condition33%2/6
$count <= $MAX_SIGNATURE_BLOCKS and $block >= $MIN_SIGNATURE_BLOCK and $block <= $MAX_SIGNATURE_BLOCK
!ll&&!rl&&r
001
$count <= $MAX_SIGNATURE_BLOCKS and $block >= $MIN_SIGNATURE_BLOCK
!ll&&!rl&&r
001
MC/DC0%0/3
$count <= $MAX_SIGNATURE_BLOCKS and $block >= $MIN_SIGNATURE_BLOCK and $block <= $MAX_SIGNATURE_BLOCK
$count <= $MAX_SIGNATURE_BLOCKS $block >= $MIN_SIGNATURE_BLOCK $block <= $MAX_SIGNATURE_BLOCK
Truth table25%1/4
A and B and C
A= $count <= $MAX_SIGNATURE_BLOCKSB= $block >= $MIN_SIGNATURE_BLOCKC= $block <= $MAX_SIGNATURE_BLOCK
ABCresult
0XX0
10X0
1100
1111
932 unless $count <= $MAX_SIGNATURE_BLOCKS && $block >= $MIN_SIGNATURE_BLOCK && $block <= $MAX_SIGNATURE_BLOCK;
933  
934 1 my $blocks = App::FileSync::Delta::decode_signature($self->{conn}->read_data($message), $count);
935  
936 1 my $abs = $self->{store}->abs_path($path);
937 1 my $file = $self->_file_stat($abs, $path);
938 1 ▶ return $self->_reply({ ok => 1, delta => 0 }) if $file->{s} < $App::FileSync::Delta::MIN_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
if $file->{"s"} < $App::FileSync::Delta::MIN_SIZE 0 1 1
939  
940 1 my $spool = File::Temp->new(UNLINK => 1);
941 1 binmode $spool;
942 1 my $stats = App::FileSync::Delta::diff($abs, { blocklen => $block, blocks => $blocks }, $spool);
943 1 $spool->flush();
944  
945 # Only the literal bytes and record headers go on the wire; compression can
946 # shrink them further, so this is a conservative estimate.
947 1 my $estimated = $stats->{literal} + $DELTA_OP_BYTES * $stats->{ops} + $DELTA_OVERHEAD;
948 1 ▶ return $self->_reply({ ok => 1, delta => 0 }) if $estimated >= $file->{s};
Branch: 1 branch
BranchTrueFalseTotal
if $estimated >= $file->{"s"} 0 1 1
949  
950 1 seek($spool, 0, 0);
951 1 $self->{pull_deltas}{$path} = { spool => $spool, %{$file} };
952 1 $self->{conn}->send({ ok => 1, delta => 1, %{$file}, b => $block });
953 1 return 1;
954 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
955  
956 # _pull_op
957 # Purpose: serve the next record of a spooled pull delta.
958 # Entry: _pull_signature spooled a delta for p.
959 # Exit: returns 1 after sending a copy, a literal, or done.
960 # Side effects: advances the spool; forgets it at the end.
961 26 ▶sub _pull_op :Private {
Subroutine _pull_op: called CC=5 SCAR=16.2
962 26 my ($self, $message) = @_;
963  
964 26 ▶ my $path = $message->{p} // '';
Condition50%1/2
$message->{"p"} // ""
l!l
260
MC/DC0%0/1
$message->{"p"} // ""
$message->{"p"}
Truth table50%1/2
A
A= $message->{"p"}
Aresult
11
00
965 26 ▶ my $state = $self->{pull_deltas}{$path} or $self->_throw('server.no_signature', { path => $path });
Branch: 1 branch
BranchTrueFalseTotal
my $state = $self->{"pull_deltas"}{$path} or $self->_throw("server.no_signature", {"path", $path}) 26 0 26
966  
967 26 my ($type, @rest) = App::FileSync::Delta::read_op($state->{spool});
968 26 ▶ unless ($type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($type) 1 25 26
969 1 delete $self->{pull_deltas}{$path};
970 1 return $self->_reply({ ok => 1, done => 1 });
971 }
972  
973 25 ▶ return $self->_reply({ ok => 1, op => 'copy', off => $rest[0], len => $rest[1] }) if $type eq 'copy';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "copy" 23 2 25
974  
975 2 $self->{conn}->send_data({ ok => 1, op => 'lit' }, $rest[0]);
976 2 return 1;
977 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
978  
979 # _mkdir
980 # Purpose: create a directory the client pushed.
981 # Entry: $message->{p} is a planned push of a directory.
982 # Exit: returns 1 after replying ok.
983 # Side effects: creates the directory in the master; records it.
984 5 ▶sub _mkdir :Private {
Subroutine _mkdir: called CC=1 SCAR=0.0
985 5 my ($self, $message) = @_;
986  
987 5 my $path = $message->{p};
988 5 $self->_expect('mkdir', $path);
989  
990 5 App::FileSync::IO::ensure_dir($self->{store}->abs_path($path));
991 5 $self->{index}{$path} = { t => $TYPE_DIR };
992 5 $self->{base_after}{$path} = { t => $TYPE_DIR };
993 5 $self->_journal({ action => 'mkdir', path => $path, result => 'ok' });
994  
995 5 $self->{applied}{$path} = 1;
996 5 return $self->_reply({ ok => 1 });
997 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
998  
999 # _delete
1000 # Purpose: move a master path the client deleted into the trash.
1001 # Entry: $message->{p} is a planned delete_remote.
1002 # Exit: returns 1 after replying with the trash path.
1003 # Side effects: moves the path to the trash; records it.
1004 17 ▶sub _delete :Private {
Subroutine _delete: called CC=1 SCAR=0.0
1005 17 my ($self, $message) = @_;
1006  
1007 17 my $path = $message->{p};
1008 17 $self->_expect('delete', $path);
1009  
1010 17 my $trashed = $self->{store}->move_to_trash($path, time);
1011 17 delete $self->{index}{$path};
1012 17 delete $self->{base_after}{$path};
1013 17 $self->_journal({ action => 'delete', path => $path, trash => $trashed, result => 'ok' });
1014  
1015 17 $self->{applied}{$path} = 1;
1016 17 return $self->_reply({ ok => 1, trash => $trashed });
1017 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1018  
1019 # _ack
1020 # Purpose: record what the client now holds after a change on its side.
1021 # Entry: $message->{p} is a planned pull, delete_local or conflict the
1022 # master won. deleted is only valid for delete_local, and only
1023 # a delete_local may omit the file description.
1024 # Exit: returns 1 after replying ok.
1025 # Side effects: updates base_after; journals a conflict the master won.
1026 # Restricting acks to these actions stops a client from writing
1027 # arbitrary entries into its own base, which would make the
1028 # next plan delete or skip master files.
1029 130 ▶sub _ack :Private {
Subroutine _ack: called CC=9 SCAR=22.1
1030 130 my ($self, $message) = @_;
1031  
1032 130 my $path = $message->{p};
1033 130 my $action = $self->_expect('ack', $path);
1034 129 my $deleting = $action->{a} eq 'delete_local';
1035  
1036 129 ▶ $self->_throw('server.bad_ack', { path => $path }) unless !$message->{deleted} == !$deleting;
Branch: 1 branch
BranchTrueFalseTotal
unless !$message->{"deleted"} == !$deleting 1 128 129
1037  
1038 128 ▶ if ($deleting) {
Branch: 2 branches
BranchTrueFalseTotal
if ($deleting) { } 33 95 128
elsif (($message->{'t'} // '') eq $App::FileSync::Server::TYPE_DIR) { } 6 89 95
1039 33 delete $self->{base_after}{$path};
1040 ▶ } elsif (($message->{t} // '') eq $TYPE_DIR) {
Condition100%2/2
$message->{"t"} // ""
l!l
689
MC/DC100%1/1
$message->{"t"} // ""
$message->{"t"}
Truth table100%2/2
A
A= $message->{"t"}
Aresult
11
00
1041 6 $self->{base_after}{$path} = { t => $TYPE_DIR };
1042 } else {
1043 $self->_throw('server.bad_field', { field => 'h', path => $path })
1044 89 ▶ unless defined $message->{h} && $message->{h} =~ $SHA256_HEX;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $message->{"h"} and $message->{"h"} =~ /$App::FileSync::Server::SHA256_HEX/ 0 89 89
Condition33%1/3
defined $message->{"h"} and $message->{"h"} =~ /$App::FileSync::Server::SHA256_HEX/
!ll&&!rl&&r
0089
MC/DC0%0/2
defined $message->{"h"} and $message->{"h"} =~ /$App::FileSync::Server::SHA256_HEX/
defined $message->{"h"} $message->{"h"} =~ /$App::FileSync::Server::SHA256_HEX/
Truth table33%1/3
A and B
A= defined $message->{"h"}B= $message->{"h"} =~ /$App::FileSync::Server::SHA256_HEX/
ABresult
0X0
100
111
1045 $self->{base_after}{$path} = {
1046 t => $TYPE_FILE,
1047 h => $message->{h},
1048 s => $self->_uint($message, 's', 0),
1049 89 ▶ m => ($message->{m} // 0) + 0,
Condition50%1/2
$message->{"m"} // 0
l!l
890
MC/DC0%0/1
$message->{"m"} // 0
$message->{"m"}
Truth table50%1/2
A
A= $message->{"m"}
Aresult
11
00
1050 mode => $self->_uint($message, 'mode', $DEFAULT_FILE_MODE),
1051 };
1052 }
1053  
1054 128 ▶ if ($action->{a} eq 'conflict') {
Branch: 1 branch
BranchTrueFalseTotal
if ($action->{"a"} eq "conflict") 6 122 128
1055 $self->_journal_conflict($path, 'remote', $action->{loser_name},
1056 6 $self->{index}{$path}, $self->{client_manifest}{$path});
1057 }
1058  
1059 128 $self->{applied}{$path} = 1;
1060 128 delete $self->{pull_deltas}{$path};
1061 128 return $self->_reply({ ok => 1 });
1062 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1063  
1064 # _preserve_loser
1065 # Purpose: move the master's losing version aside before the client's
1066 # version is written.
1067 # Entry: $conflict_rel is the plan's loser_name for $path.
1068 # Exit: returns 1.
1069 # Side effects: renames the master file; moves its index entry; journals the
1070 # copy and the conflict. Does nothing if the master no longer
1071 # has the file.
1072 6 ▶sub _preserve_loser :Private {
Subroutine _preserve_loser: called CC=10 SCAR=25.2
1073 6 my ($self, $path, $conflict_rel, $winner) = @_;
1074  
1075 6 my ($safe, $reason) = validate_relpath($conflict_rel);
1076 6 ▶ $self->_throw('server.conflict_unsafe', { reason => $reason }) unless $safe;
Branch: 1 branch
BranchTrueFalseTotal
unless $safe 0 6 6
1077 6 ▶ $self->_throw('server.conflict_same', { path => $path }) if $conflict_rel eq $path;
Branch: 1 branch
BranchTrueFalseTotal
if $conflict_rel eq $path 0 6 6
1078  
1079 6 my $store = $self->{store};
1080 6 my $abs = $store->abs_path($path);
1081 6 ▶ return 1 unless -e $abs || -l $abs;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $abs or -l $abs 0 6 6
Condition33%1/3
-e $abs or -l $abs
l!l&&r!l&&!r
600
MC/DC0%0/2
-e $abs or -l $abs
-e $abs -l $abs
Truth table33%1/3
A or B
A= -e $absB= -l $abs
ABresult
1X1
011
000
1082  
1083 6 my $destination = $store->abs_path($conflict_rel);
1084 6 ▶ $self->_throw('server.conflict_exists', { path => $conflict_rel }) if -e $destination || -l $destination;
Branch: 1 branch
BranchTrueFalseTotal
if -e $destination or -l $destination 0 6 6
Condition33%1/3
-e $destination or -l $destination
l!l&&r!l&&!r
006
MC/DC0%0/2
-e $destination or -l $destination
-e $destination -l $destination
Truth table33%1/3
A or B
A= -e $destinationB= -l $destination
ABresult
1X1
011
000
1085  
1086 6 $store->ensure_parent($conflict_rel);
1087 6 ▶ eval { rename $abs, $destination; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &App::FileSync::Server::rename($abs, $destination); 1 } } or $self->_throw("server.conflict_move", {"path", $path, "to", $conflict_rel, "error", os_error($@)}) 6 0 6
1088 or $self->_throw('server.conflict_move', { path => $path, to => $conflict_rel, error => os_error($@) });
1089  
1090 6 my $old = delete $self->{index}{$path};
1091 6 ▶ $self->{index}{$conflict_rel} = $old if $old;
Branch: 1 branch
BranchTrueFalseTotal
if $old 6 0 6
1092  
1093 6 ▶ $self->_journal({ action => 'conflict_copy', path => $conflict_rel, from => $path, sha256 => $old ? $old->{h} : undef, result => 'ok' });
Branch: 1 branch
BranchTrueFalseTotal
$old ? : 6 0 6
1094 6 $self->_journal_conflict($path, 'client', $conflict_rel, { h => $winner->{sha256}, m => $winner->{mtime} }, $old);
1095  
1096 6 return 1;
1097 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1098  
1099 # _journal_conflict
1100 # Purpose: record how a conflict was resolved.
1101 # Entry: $side is client or remote; entries may be undef.
1102 # Exit: returns 1.
1103 # Side effects: appends a conflict event.
1104 12 ▶sub _journal_conflict :Private {
Subroutine _journal_conflict: called CC=3 SCAR=11.7
1105 12 my ($self, $path, $side, $loser_name, $winner, $loser) = @_;
1106  
1107 12 ▶ ($winner, $loser) = ($winner || {}, $loser || {});
Condition50%2/4
$winner || {}
l!l
120
$loser || {}
l!l
120
MC/DC0%0/1
$winner || {}
$winner
MC/DC0%0/1
$loser || {}
$loser
Truth table50%1/2
A
A= $winner
Aresult
11
00
Truth table50%1/2
A
A= $loser
Aresult
11
00
1108 return $self->_journal({
1109 action => 'conflict',
1110 path => $path,
1111 winner => $side,
1112 loser_name => $loser_name,
1113 winner_sha256 => $winner->{h},
1114 winner_mtime => $winner->{m},
1115 loser_sha256 => $loser->{h},
1116 loser_mtime => $loser->{m},
1117 12 result => 'ok',
1118 });
1119 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1120  
1121 # _finish
1122 # Purpose: end the session: save the index and the client's base.
1123 # Entry: every planned action has been applied (unless dry run).
1124 # Exit: returns 1 after sending the summary.
1125 # Side effects: writes the index, the base and a session event; sets
1126 # finished. Raises server.unfinished, naming the missing paths
1127 # in order, when the client stopped early.
1128 156 ▶sub _finish :Private {
Subroutine _finish: called CC=5 SCAR=16.1
1129 156 my ($self) = @_;
1130  
1131 156 my @actions = values %{ $self->{plan} };
1132 156 ▶ unless ($self->{dry_run}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"dry_run"}) 148 8 156
1133 148 my @unfinished = sort map { $_->{p} } grep { !$self->{applied}{ $_->{p} } } @actions;
1134 148 ▶ $self->_throw('server.unfinished', { paths => join(', ', @unfinished) }) if @unfinished;
Branch: 1 branch
BranchTrueFalseTotal
if @unfinished 1 147 148
1135  
1136 147 $self->{store}->save_index($self->{index});
1137 147 $self->{store}->save_base($self->{client}, $self->{base_after});
1138 }
1139  
1140 155 my %summary = map { my $kind = $_; $kind => scalar(grep { $_->{a} =~ /\A$kind/ } @actions) }
1141 qw(pull push delete conflict);
1142 %summary = (
1143 pulled => $summary{pull},
1144 pushed => $summary{push},
1145 deleted => $summary{delete},
1146 conflicts => $summary{conflict},
1147 155 );
1148  
1149 155 $self->{logger}->info('session finished', { repo => $self->{repo}, client => $self->{client}, %summary, dry_run => $self->{dry_run} });
1150  
1151 # The client exits 3 when it had to keep conflict copies; record that here
1152 # too, so --exit means the same thing on both sides.
1153 $self->_journal({
1154 action => 'session',
1155 result => 'ok',
1156 exit => $summary{conflicts} ? $EXIT_WARNINGS : $EXIT_OK,
1157 dry_run => $self->{dry_run},
1158 %summary,
1159 155 ▶ }) unless $self->{dry_run};
Branch: 2 branches
BranchTrueFalseTotal
unless $self->{"dry_run"} 147 8 155
$summary{'conflicts'} ? : 8 139 147
1160 155 $self->{session_journalled} = 1;
1161  
1162 155 $self->{conn}->send({ ok => 1, summary => \%summary });
1163 155 $self->{finished} = 1;
1164 155 return 1;
1165 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1166  
1167 # _open_upload
1168 # Purpose: start an upload for a planned path.
1169 # Entry: $message has s, h, m, mode (s and h may be absent for a put).
1170 # Exit: returns the upload record.
1171 # Side effects: creates the parent directory and a temporary file; raises
1172 # server.busy if the path is already being received.
1173 179 ▶sub _open_upload :Private {
Subroutine _open_upload: called CC=3 SCAR=11.2
1174 179 my ($self, $path, $message) = @_;
1175  
1176 179 ▶ $self->_throw('server.busy', { path => $path }) if $self->{uploads}{$path};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"uploads"}{$path} 0 179 179
1177  
1178 179 ▶ my $size = defined $message->{s} ? $self->_uint($message, 's') : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $message->{'s'} ? : 179 0 179
1179 179 $self->{store}->ensure_parent($path);
1180 179 my ($fh, $temp) = @{ $self->{store}->temp_file($path) };
1181  
1182 return $self->{uploads}{$path} = {
1183 fh => $fh,
1184 temp => $temp,
1185 sha => Digest::SHA->new($SHA_BITS),
1186 got => 0,
1187 size => $size,
1188 hash => $message->{h},
1189 mtime => $message->{m},
1190 mode => $message->{mode},
1191 179 };
1192 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1193  
1194 # _open_delta
1195 # Purpose: find the delta upload a record belongs to.
1196 # Entry: $message->{p} names it.
1197 # Exit: returns ($path, $upload).
1198 # Side effects: raises server.no_delta when there is none, or the open
1199 # upload for that path is a whole-file put.
1200 26 ▶sub _open_delta :Private {
Subroutine _open_delta: called CC=4 SCAR=15.2
1201 26 my ($self, $message) = @_;
1202  
1203 26 ▶ my $path = $message->{p} // '';
Condition50%1/2
$message->{"p"} // ""
l!l
260
MC/DC0%0/1
$message->{"p"} // ""
$message->{"p"}
Truth table50%1/2
A
A= $message->{"p"}
Aresult
11
00
1204 26 my $upload = $self->{uploads}{$path};
1205 26 ▶ $self->_throw('server.no_delta', { path => $path }) unless $upload && $upload->{delta};
Branch: 1 branch
BranchTrueFalseTotal
unless $upload and $upload->{"delta"} 0 26 26
Condition33%1/3
$upload and $upload->{"delta"}
!ll&&!rl&&r
0026
MC/DC0%0/2
$upload and $upload->{"delta"}
$upload $upload->{"delta"}
Truth table33%1/3
A and B
A= $uploadB= $upload->{"delta"}
ABresult
0X0
100
111
1206 26 return ($path, $upload);
1207 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1208  
1209 # _append_upload
1210 # Purpose: add received bytes to an upload.
1211 # Entry: $upload is open.
1212 # Exit: returns 1.
1213 # Side effects: writes to the temporary file and the hash. Refuses more
1214 # bytes than were announced, so a client cannot fill the disk
1215 # behind a small size; on any failure the upload is discarded.
1216 206 ▶sub _append_upload :Private {
Subroutine _append_upload: called CC=4 SCAR=14.5
1217 206 my ($self, $path, $upload, $bytes) = @_;
1218  
1219 206 my $length = length $bytes;
1220 206 ▶ if (defined $upload->{size} && $upload->{got} + $length > $upload->{size}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $upload->{"size"} and $upload->{"got"} + $length > $upload->{"size"}) 1 205 206
Condition66%2/3
defined $upload->{"size"} and $upload->{"got"} + $length > $upload->{"size"}
!ll&&!rl&&r
02051
MC/DC50%1/2
defined $upload->{"size"} and $upload->{"got"} + $length > $upload->{"size"}
defined $upload->{"size"} $upload->{"got"} + $length > $upload->{"size"}
Truth table66%2/3
A and B
A= defined $upload->{"size"}B= $upload->{"got"} + $length > $upload->{"size"}
ABresult
0X0
100
111
1221 1 $self->_discard_upload($path);
1222 1 $self->_throw('server.overflow', { path => $path });
1223 }
1224  
1225 205 ▶ unless (print { $upload->{fh} } $bytes) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print {$upload->{"fh"};} $bytes) 0 205 205
1226 0 my $error = os_error();
1227 0 $self->_discard_upload($path);
1228 0 $self->_throw('io.write', { path => $upload->{temp}, error => $error });
1229 }
1230  
1231 205 $upload->{sha}->add($bytes);
1232 205 $upload->{got} += $length;
1233 205 return 1;
1234 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1235  
1236 # _commit_upload
1237 # Purpose: close, verify and install an upload, whole or delta.
1238 # Entry: $upload is no longer in uploads.
1239 # Exit: returns the new index entry.
1240 # Side effects: installs the file in the master; updates the index and
1241 # base_after; journals the push. A hash or size mismatch
1242 # discards the temporary file and raises.
1243 176 ▶sub _commit_upload :Private {
Subroutine _commit_upload: called CC=11 SCAR=27.6
1244 176 my ($self, $path, $upload, %extra) = @_;
1245  
1246 176 my $closed = eval { close $upload->{fh}; 1 };
1247 176 ▶ my $error = $closed ? undef : os_error($@);
Branch: 1 branch
BranchTrueFalseTotal
$closed ? : 176 0 176
1248 176 ▶ eval { close $upload->{old_fh} } if $upload->{old_fh};
Branch: 1 branch
BranchTrueFalseTotal
if $upload->{"old_fh"} 1 175 176
1249  
1250 176 my $hash = $upload->{sha}->hexdigest();
1251 my ($key, %args) =
1252 !$closed ? ('io.write', path => $upload->{temp}, error => $error)
1253 : (defined $upload->{hash} && $hash ne $upload->{hash}) ? ('server.hash_mismatch', path => $path, expected => $upload->{hash}, got => $hash)
1254 : (defined $upload->{size} && $upload->{got} != $upload->{size}) ? ('server.size_mismatch', path => $path, expected => $upload->{size}, got => $upload->{got})
1255 176 ▶ : ();
Branch: 3 branches
BranchTrueFalseTotal
!$closed ? : 0 176 176
defined $upload->{'hash'} && $hash ne $upload->{'hash'} ? : 0 176 176
defined $upload->{'size'} && $upload->{'got'} != $upload->{'size'} ? : 0 176 176
Condition33%2/6
defined $upload->{"hash"} and $hash ne $upload->{"hash"}
!ll&&!rl&&r
01760
defined $upload->{"size"} and $upload->{"got"} != $upload->{"size"}
!ll&&!rl&&r
01760
MC/DC0%0/2
defined $upload->{"hash"} and $hash ne $upload->{"hash"}
defined $upload->{"hash"} $hash ne $upload->{"hash"}
MC/DC0%0/2
defined $upload->{"size"} and $upload->{"got"} != $upload->{"size"}
defined $upload->{"size"} $upload->{"got"} != $upload->{"size"}
Truth table33%1/3
A and B
A= defined $upload->{"hash"}B= $hash ne $upload->{"hash"}
ABresult
0X0
100
111
Truth table33%1/3
A and B
A= defined $upload->{"size"}B= $upload->{"got"} != $upload->{"size"}
ABresult
0X0
100
111
1256 176 ▶ if ($key) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key) 0 176 176
1257 0 eval { unlink $upload->{temp} };
1258 0 $self->_throw($key, \%args);
1259 }
1260  
1261 176 $self->{store}->commit_temp($path, $upload->{temp}, $upload->{mtime}, $upload->{mode});
1262  
1263 my $entry = {
1264 t => $TYPE_FILE,
1265 s => $upload->{got},
1266 m => $upload->{mtime} // time,
1267 h => $hash,
1268 176 ▶ mode => $upload->{mode} // $DEFAULT_FILE_MODE,
Condition40%2/5
$upload->{"mtime"} // time
l!l
1760
$upload->{"mode"} // $App::FileSync::Server::DEFAULT_FILE_MODE
l!l&&r!l&&!r
17600
MC/DC0%0/1
$upload->{"mtime"} // time
$upload->{"mtime"}
MC/DC0%0/2
$upload->{"mode"} // $App::FileSync::Server::DEFAULT_FILE_MODE
$upload->{"mode"} $App::FileSync::Server::DEFAULT_FILE_MODE
Truth table50%1/2
A
A= $upload->{"mtime"}
Aresult
11
00
Truth table33%1/3
A // B
A= $upload->{"mode"}B= $App::FileSync::Server::DEFAULT_FILE_MODE
ABresult
1X1
011
000
1269 };
1270 176 $self->{index}{$path} = $entry;
1271 176 $self->{base_after}{$path} = { %{$entry} };
1272  
1273 176 $self->_journal({ action => 'push', path => $path, size => $upload->{got}, sha256 => $hash, result => 'ok', %extra });
1274 176 $self->{applied}{$path} = 1;
1275 176 return $entry;
1276 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1277  
1278 # _discard_upload / _discard_uploads
1279 # Purpose: abandon one, or every, partial upload.
1280 # Entry: none.
1281 # Exit: returns 1.
1282 # Side effects: closes handles and removes temporary files, so a failed
1283 # session leaves nothing for clean_stale_temps to find an hour
1284 # later.
1285 3 ▶sub _discard_upload :Private {
Subroutine _discard_upload: called CC=3 SCAR=11.0
1286 3 my ($self, $path) = @_;
1287  
1288 # Best effort: the session is ending or the upload was refused, so a
1289 # handle that will not close or a temp that will not go is not an error.
1290 3 ▶ if (my $upload = delete $self->{uploads}{$path}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $upload = delete $self->{"uploads"}{$path}) 3 0 3
1291 3 eval { close $_ } for grep { defined } @{$upload}{qw(fh old_fh)};
1292 3 eval { unlink $upload->{temp} };
1293 }
1294  
1295 3 return 1;
1296 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1297  
1298 24 ▶sub _discard_uploads :Private {
Subroutine _discard_uploads: called CC=2 SCAR=6.9
1299 24 my ($self) = @_;
1300  
1301 24 $self->_discard_upload($_) for keys %{ $self->{uploads} };
1302 24 return 1;
1303 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1304  
1305 # _file_stat
1306 # Purpose: size, mtime and mode of a master file the client is reading.
1307 # Entry: $abs is inside the master.
1308 # Exit: returns { s, m, mode }.
1309 # Side effects: raises server.cannot_stat or server.not_file.
1310 93 ▶sub _file_stat :Private {
Subroutine _file_stat: called CC=3 SCAR=11.3
1311 93 my ($self, $abs, $path) = @_;
1312  
1313 93 my @stat = Time::HiRes::stat($abs);
1314 93 ▶ $self->_throw('server.cannot_stat', { path => $path, error => os_error() }) unless @stat;
Branch: 1 branch
BranchTrueFalseTotal
unless @stat 0 93 93
1315 93 ▶ $self->_throw('server.not_file', { path => $path }) unless -f _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f _ 0 93 93
1316 93 return { s => $stat[$STAT_SIZE], m => $stat[$STAT_MTIME], mode => $stat[$STAT_MODE] & $MODE_MASK };
1317 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1318  
1319 # _uint
1320 # Purpose: read an unsigned integer field from a client message.
1321 # Entry: $default is used when the field is absent; without one the
1322 # field is required.
1323 # Exit: returns the number.
1324 # Side effects: raises server.bad_field for anything else (a negative or
1325 # fractional offset, a string, a missing required field).
1326 775 ▶sub _uint :Private {
Subroutine _uint: called CC=5 SCAR=16.6
1327 775 my ($self, $message, $field, $default) = @_;
1328  
1329 775 ▶ my $value = $message->{$field} // $default;
Condition66%2/3
$message->{$field} // $default
l!l&&r!l&&!r
77410
MC/DC0%0/2
$message->{$field} // $default
$message->{$field} $default
Truth table66%2/3
A // B
A= $message->{$field}B= $default
ABresult
1X1
011
000
1330 775 ▶ $self->_throw('server.bad_field', { field => $field, path => $message->{p} // '' })
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and $value =~ /$UINT/ 3 772 775
Condition60%3/5
defined $value and $value =~ /$UINT/
!ll&&!rl&&r
03772
$message->{"p"} // ""
l!l
30
MC/DC50%1/2
defined $value and $value =~ /$UINT/
defined $value $value =~ /$UINT/
MC/DC0%0/1
$message->{"p"} // ""
$message->{"p"}
Truth table66%2/3
A and B
A= defined $valueB= $value =~ /$UINT/
ABresult
0X0
100
111
Truth table50%1/2
A
A= $message->{"p"}
Aresult
11
00
1331 unless defined $value && $value =~ $UINT;
1332 772 return $value + 0;
1333 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1334  
1335 # _journal
1336 # Purpose: append an event for this client.
1337 # Entry: $event is a hashref without client.
1338 # Exit: returns 1.
1339 # Side effects: appends to the journal.
1340 546 ▶sub _journal :Private {
Subroutine _journal: called CC=1 SCAR=0.0
1341 546 my ($self, $event) = @_;
1342  
1343 546 $self->{store}->journal({ client => $self->{client}, %{$event} });
1344 546 return 1;
1345 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1346  
1347 # _reply
1348 # Purpose: send a reply and end the handler.
1349 # Entry: $reply is a hashref.
1350 # Exit: returns 1.
1351 # Side effects: writes to the connection.
1352 177 ▶sub _reply :Private {
Subroutine _reply: called CC=1 SCAR=0.0
1353 177 my ($self, $reply) = @_;
1354  
1355 177 $self->{conn}->send($reply);
1356 177 return 1;
1357 313 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1358  
1359 313 1;
1360  
1361 __END__
« blib/lib/App/FileSync/Trash.pm ↑ Summary blib/lib/App/FileSync/I18N.pm »