lib/Mail/DKIM2/MessageInstance.pm

filter: Statementstmt 97.0% 681 / 702 Branchbran 87.4% 355 / 406 Conditioncond 76.1% 239 / 314 MC/DCmcdc 65.1% 114 / 175 Subroutinesub 94.2% 65 / 69 Podpod 100% 23 / 23 totaltotal 87.4% 1477 / 1689 CC 700 SCAR 35.6
CC
700
Cov
90%
calculate
82.1
calculate
82.1
_body_diff
56.3
CRAP 35.0
« lib/Mail/Milter/Authentication/Handler/DKIM2Sign.pm ↑ Summary lib/Mail/DKIM2/BodyPlan.pm »
1 package Mail::DKIM2::MessageInstance;
2 196 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 196 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 196 our $VERSION = '0.33';
6  
7  
8 196 ▶use Mail::DKIM2::Fold ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 196 ▶use Mail::DKIM2::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 196 ▶use Mail::DKIM2::Digest;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 196 ▶use Email::MIME;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 196 ▶use MIME::Base64 qw(encode_base64 decode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 196 ▶use List::Util qw(max);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 196 ▶use B ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 196 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 196 ▶use Mail::DKIM2::TagValueList ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 196 ▶use Mail::DKIM2::Common qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
19 MI_MISSING_M_ERROR
20 parse_mime
21 extract_mi_version
22 MAX_CHAIN_LENGTH
23 chain_length_error
24 chain_number_error
25 mi_version_tag
26 duplicate_number_error
27 196 );
28 196 ▶use Mail::DKIM2::Canon qw(should_skip dkim2_canonicalize_header check_ignore_prefixes);
Subroutine BEGIN: called CC=1 SCAR=0.0
29 196 ▶use Mail::DKIM2::RecipeJSON qw(encode_tag_json decode_tag_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 # The PERMERROR for a message whose Message-Instance fields cannot form a
32 # chain, or undef.
33 1196 ▶sub _chain_error {
Subroutine _chain_error: called CC=1 SCAR=1.2
34 0 ▶ my ($msg) = @_;
Subroutine _chain_error: not called CC=1 SCAR=1.2
35 0 return _chain_error_fields([ $msg->header_raw('Message-Instance') ],
36 scalar(my @sigs = $msg->header_raw('DKIM2-Signature')));
37 }
38  
39 # The same from the Message-Instance field values and the number of
40 # DKIM2-Signature fields, for a caller that has no Email::MIME.
41 1196 ▶sub _chain_error_fields {
Subroutine _chain_error_fields: called CC=4 SCAR=17.9
42 0 ▶ my ($fields, $signatures) = @_;
Subroutine _chain_error_fields: not called CC=4 SCAR=17.9
43 0 my @mi = @$fields;
44 # The first field with no usable m= (none, or not a chain number), in
45 # field order -- interop contract C9's step b.
46 0 my ($unusable) = grep { defined }
47 0 map { my $raw = mi_version_tag($_);
48 0 ▶ defined $raw ? chain_number_error('Message-Instance', 'm', $raw)
Branch: 2 branches
BranchTrueFalseTotal
defined $raw ? : 3483 2 3485
defined $raw ? : 0 0 0
49 : MI_MISSING_M_ERROR } @mi;
50 return chain_length_error({ 'message-instance' => scalar @mi,
51 'dkim2-signature' => $signatures })
52 // $unusable
53 0 ▶ // duplicate_number_error('Message-Instance', 'm', map { extract_mi_version($_) } @mi);
Condition50%6/12
(chain_length_error({"message-instance", scalar @mi, "dkim2-signature", $signatures}) // $unusable) // duplicate_number_error("Message-Instance", "m", map({extract_mi_version($_);} @mi))
l!l&&r!l&&!r
1231181
chain_length_error({"message-instance", scalar @mi, "dkim2-signature", $signatures}) // $unusable
l!l&&r!l&&!r
391184
(chain_length_error({"message-instance", scalar @mi, "dkim2-signature", $signatures}) // $unusable) // duplicate_number_error("Message-Instance", "m", map({extract_mi_version($_);} @mi))
l!l&&r!l&&!r
000
chain_length_error({"message-instance", scalar @mi, "dkim2-signature", $signatures}) // $unusable
l!l&&r!l&&!r
000
MC/DC100%3/3
(chain_length_error({"message-instance", scalar @mi, "dkim2-signature", $signatures}) // $unusable) // duplicate_number_error("Message-Instance", "m", map({extract_mi_version($_);} @mi))
chain_length_error({"message-instance", scalar @mi, "dkim2-signature", $signatures}) $unusable duplicate_number_error("Message-Instance", "m", map({extract_mi_version($_);} @mi))
MC/DC0%0/3
(chain_length_error({"message-instance", scalar @mi, "dkim2-signature", $signatures}) // $unusable) // duplicate_number_error("Message-Instance", "m", map({extract_mi_version($_);} @mi))
chain_length_error({"message-instance", scalar @mi, "dkim2-signature", $signatures}) $unusable duplicate_number_error("Message-Instance", "m", map({extract_mi_version($_);} @mi))
Truth table100%4/4
A // B // C
A= chain_length_error({"message-instance", scalar @mi, "dkim2-signature", $signatures})B= $unusableC= duplicate_number_error("Message-Instance", "m", map({extract_mi_version($_);} @mi))
ABCresult
1XX1
01X1
0011
0000
Truth table0%0/4
A // B // C
A= chain_length_error({"message-instance", scalar @mi, "dkim2-signature", $signatures})B= $unusableC= duplicate_number_error("Message-Instance", "m", map({extract_mi_version($_);} @mi))
ABCresult
1XX1
01X1
0011
0000
54 }
55  
56 # -09 §3.1: two hashing algorithms are defined. Verifiers MUST implement
57 # both; Signers MAY implement either or both (we default to sha256). Each
58 # is a function of the data to its raw digest, by Mail::DKIM2::Digest.
59 my %HASH_ALGS = map {
60 196 my $alg = $_;
61 6414 ▶ $alg => sub { Mail::DKIM2::Digest::digest_data($alg, $_[0]) };
Subroutine __ANON__: called CC=1 SCAR=0.0
62 } qw(sha256 sha512);
63  
64 4270 ▶sub hash_algs { return { %HASH_ALGS } }
Subroutine hash_algs: called CC=1 SCAR=0.0
Pod documented
65  
66 # h= (-09 §9.3): hash-all groups joined by "|", each hash-set *(","
67 # hash-set), and each hash-set [FWS] hash-name [FWS] ":" header-hash ":"
68 # body-hash. FWS is trimmed from around the name and removed from inside the
69 # base64 hashes (§2.12: a folded value may break anywhere in them); anywhere
70 # else (inside the name, or a set missing a part) the value is malformed and
71 # this returns undef rather than skipping the set or joining the name up, as
72 # it does for an empty member (D2). Hash names are case-sensitive (§2.14):
73 # "SHA256" is a name of its own, which no verifier implements.
74 # parse_hash_groups gives [[[name, hh, bh], ...], ...]; parse_hash_sets the
75 # sets alone, in h= order.
76 4143 ▶sub parse_hash_groups {
Subroutine parse_hash_groups: called CC=7 SCAR=19.5
Pod documented
77 4143 my ($h_tag) = @_;
78 4143 ▶ my $groups = Mail::DKIM2::Common::split_any_all($h_tag) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $groups = Mail::DKIM2::Common::split_any_all($h_tag) or return 4140 3 4143
79 4140 my @out;
80 4140 for my $group (@$groups) {
81 4152 my @sets;
82 4152 for my $item (@$group) {
83 5479 ▶ my ($name, $rest) = $item =~ /\A[ \t\r\n]*([A-Za-z0-9_-]+)[ \t\r\n]*:(.*)\z/s
Branch: 1 branch
BranchTrueFalseTotal
() = $item =~ /\A[ \t\r\n]*([A-Za-z0-9_-]+)[ \t\r\n]*:(.*)\z/s or return 5478 1 5479
84 or return;
85 5478 $rest =~ s/[ \t\r\n]//g;
86 5478 my @hashes = split /:/, $rest, -1;
87 # Both are base64strings (§2.14), whatever the algorithm.
88 return unless @hashes == 2
89 5478 ▶ && !grep { !Mail::DKIM2::Util::is_base64string($_) } @hashes;
Branch: 1 branch
BranchTrueFalseTotal
unless @hashes == 2 and not grep({not Mail::DKIM2::Util::is_base64string($_);} @hashes) 5 5473 5478
Condition100%3/3
@hashes == 2 and not grep({not Mail::DKIM2::Util::is_base64string($_);} @hashes)
!ll&&!rl&&r
325473
MC/DC100%2/2
@hashes == 2 and not grep({not Mail::DKIM2::Util::is_base64string($_);} @hashes)
@hashes == 2 not grep({not Mail::DKIM2::Util::is_base64string($_);} @hashes)
Truth table100%3/3
A and not(B)
A= @hashes == 2B= not grep({not Mail::DKIM2::Util::is_base64string($_);} @hashes)
ABresult
0X0
100
111
90 5473 push @sets, [$name, @hashes];
91 }
92 4146 push @out, \@sets;
93 }
94 4134 return \@out;
95 }
96  
97 5 ▶sub parse_hash_sets {
Subroutine parse_hash_sets: called CC=2 SCAR=7.1
Pod documented
98 5 ▶ my $groups = parse_hash_groups(@_) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $groups = parse_hash_groups(@_) or return 5 0 5
99 5 return [ map { @$_ } @$groups ];
100 }
101  
102 # FILTHY PATCHING (needed for undo to work with Email::Simple)
103 196 ▶BEGIN {
Subroutine BEGIN: called CC=3 SCAR=11.0
104 # function to replace headers from the bottom up
105 196 ▶ if (!Email::Simple::Header->can('header_set_reverse')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ("Email::Simple::Header"->can("header_set_reverse")) 196 0 196
106 348 ▶ *Email::Simple::Header::header_set_reverse = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
107 348 my $self = shift;
108 348 my $h = shift;
109 348 my @vals = @_;
110 348 my $headers = $self->{headers};
111 348 my $max = @$headers / 2 - 1;
112 # Names as DKIM2 compares them: "Subject :" is a Subject.
113 348 my $want = Mail::DKIM2::Canon::field_name($h);
114 348 for my $idx (map { $_ * 2 } reverse 0..$max) {
115 14122 ▶ next unless Mail::DKIM2::Canon::field_name($headers->[$idx]) eq $want;
Branch: 1 branch
BranchTrueFalseTotal
unless Mail::DKIM2::Canon::field_name($headers->[$idx]) eq $want 13775 347 14122
116 347 ▶ if (@vals) {
Branch: 1 branch
BranchTrueFalseTotal
if (@vals) { } 165 182 347
117 165 $headers->[$idx+1] = shift @vals;
118 } else {
119 182 splice(@$headers, $idx, 2);
120 }
121 }
122 348 unshift @$headers, ($h, $_) for @vals;
123 196 };
124 }
125  
126 # function to only keep headers that match an expression
127 196 ▶ if (!Email::Simple::Header->can('header_filter')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not "Email::Simple::Header"->can("header_filter")) 196 0 196
128 333 ▶ *Email::Simple::Header::header_filter = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
129 333 my $self = shift;
130 333 my $h = shift;
131 333 my $keep = shift;
132 333 my $headers = $self->{headers};
133 333 my $max = @$headers / 2 - 1;
134 333 for my $idx (map { $_ * 2 } reverse 0..$max) {
135 6265 ▶ next unless lc($headers->[$idx]) eq lc($h);
Branch: 1 branch
BranchTrueFalseTotal
unless lc $headers->[$idx] eq lc $h 5156 1109 6265
136 1109 ▶ next if $keep->($headers->[$idx+1]);
Branch: 1 branch
BranchTrueFalseTotal
if &$keep($$headers[$idx + 1]) 776 333 1109
137 333 splice(@$headers, $idx, 2);
138 }
139 196 };
140 }
141 }
142  
143 # --- Tag accessors ---
144  
145 1231 ▶sub set_tag {
Subroutine set_tag: called CC=1 SCAR=0.0
Pod documented
146 1231 my ($self, $k, $v) = @_;
147 1231 $self->{bits}{$k} = $v;
148 }
149  
150 18270 ▶sub get_tag {
Subroutine get_tag: called CC=1 SCAR=0.0
Pod documented
151 18270 my ($self, $k) = @_;
152 18270 return $self->{bits}{$k};
153 }
154  
155 # The header hash and the body hash (base64) of this Message-Instance's h=
156 # tag, for $alg (default sha256); undef if h= has no set for it.
157 0 ▶sub header_hash { return ($_[0]->{bits}{hashes}{ $_[1] // 'sha256' } || [])->[0] }
Subroutine header_hash: not called CC=3 SCAR=24.8
Pod documented
Condition0%0/4
$_[0]{'bits'}{'hashes'}{$_[1] // 'sha256'} || []
l!l
00
$_[1] // "sha256"
l!l
00
MC/DC0%0/1
$_[0]{'bits'}{'hashes'}{$_[1] // 'sha256'} || []
$_[0]{'bits'}{'hashes'}{$_[1] // 'sha256'}
MC/DC0%0/1
$_[1] // "sha256"
$_[1]
Truth table0%0/2
A
A= $_[0]{'bits'}{'hashes'}{$_[1] // 'sha256'}
Aresult
11
00
Truth table0%0/2
A
A= $_[1]
Aresult
11
00
158 3 ▶sub body_hash { return ($_[0]->{bits}{hashes}{ $_[1] // 'sha256' } || [])->[1] }
Subroutine body_hash: called CC=3 SCAR=12.7
Pod documented
Condition50%2/4
$_[0]{'bits'}{'hashes'}{$_[1] // 'sha256'} || []
l!l
30
$_[1] // "sha256"
l!l
03
MC/DC0%0/1
$_[0]{'bits'}{'hashes'}{$_[1] // 'sha256'} || []
$_[0]{'bits'}{'hashes'}{$_[1] // 'sha256'}
MC/DC0%0/1
$_[1] // "sha256"
$_[1]
Truth table50%1/2
A
A= $_[0]{'bits'}{'hashes'}{$_[1] // 'sha256'}
Aresult
11
00
Truth table50%1/2
A
A= $_[1]
Aresult
11
00
159  
160 # The body hash (-09 section 6.1) of a raw body string with LF or CRLF
161 # line ends: no Email::MIME parse, for callers that hold the body alone.
162 # Streams the body through the digest a megabyte at a time (each piece
163 # ending at a LF, so a CRLF is never split): a large body is never copied
164 # whole.
165 196 ▶use constant BODY_CHUNK => 1 << 20;
Subroutine BEGIN: called CC=1 SCAR=0.0
166  
167 122 ▶sub body_digest_raw {
Subroutine body_digest_raw: called CC=3 SCAR=11.0
Pod documented
168 # Through a reference: "my ($body) = @_" would copy the body.
169 122 ▶ my $bref = defined $_[0] ? \$_[0] : \'';
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 122 0 122
170 122 ▶ my $alg = lc($_[1] // 'sha256');
Condition100%2/2
$_[1] // "sha256"
l!l
7115
MC/DC100%1/1
$_[1] // "sha256"
$_[1]
Truth table100%2/2
A
A= $_[1]
Aresult
11
00
171 122 my $d = Mail::DKIM2::Digest->new($alg); # croaks on an unknown $alg
172 122 _body_digest_feed([$d], $bref, 1);
173 122 return encode_base64($d->digest, '');
174 }
175  
176 # Add the body text in $$bref to each of @$digests, canonicalised as
177 # body_digest_raw does. With $final it is the rest of the body: its trailing
178 # line breaks are dropped and the closing CRLF added. Without, it stops
179 # short of any CR and LF at the end, which may yet be the body's trailing
180 # line breaks, and returns the length it took; the caller keeps the rest for
181 # the next call. Mail::DKIM2::BodyHasher streams a body through this.
182 234 ▶sub _body_digest_feed {
Subroutine _body_digest_feed: called CC=16 SCAR=27.7
183 234 my ($digests, $bref, $final) = @_;
184 234 my $len = length $$bref;
185  
186 # $end: the body without its trailing line breaks, each a LF with an
187 # optional CR before it, taken from the end.
188 234 my $end = $len;
189 234 ▶ if ($final) {
Branch: 1 branch
BranchTrueFalseTotal
if ($final) { } 215 19 234
190 215 ▶ while ($end > 0 && substr($$bref, $end - 1, 1) eq "\n") {
Branch: 1 branch
BranchTrueFalseTotal
if ($end > 0 and substr($$bref, $end - 1, 1) eq "\n") 1221287 215 1221502
Condition100%3/3
$end > 0 and substr($$bref, $end - 1, 1) eq "\n"
!ll&&!rl&&r
371781221287
MC/DC100%2/2
$end > 0 and substr($$bref, $end - 1, 1) eq "\n"
$end > 0 substr($$bref, $end - 1, 1) eq "\n"
Truth table100%3/3
A and B
A= $end > 0B= substr($$bref, $end - 1, 1) eq "\n"
ABresult
0X0
100
111
191 1221287 $end--;
192 1221287 ▶ $end-- if $end > 0 && substr($$bref, $end - 1, 1) eq "\r";
Branch: 1 branch
BranchTrueFalseTotal
if $end > 0 and substr($$bref, $end - 1, 1) eq "\r" 1216236 5051 1221287
Condition100%3/3
$end > 0 and substr($$bref, $end - 1, 1) eq "\r"
!ll&&!rl&&r
150501216236
MC/DC100%2/2
$end > 0 and substr($$bref, $end - 1, 1) eq "\r"
$end > 0 substr($$bref, $end - 1, 1) eq "\r"
Truth table100%3/3
A and B
A= $end > 0B= substr($$bref, $end - 1, 1) eq "\r"
ABresult
0X0
100
111
193 }
194 } else {
195 19 ▶ $end-- while $end > 0 && substr($$bref, $end - 1, 1) =~ /[\r\n]/;
Branch: 1 branch
BranchTrueFalseTotal
$end > 0 and substr($$bref, $end - 1, 1) =~ /[\r\n]/ and do { --$end } 3493693 19 3493712
Condition100%3/3
$end > 0 and substr($$bref, $end - 1, 1) =~ /[\r\n]/
!ll&&!rl&&r
2173493693
MC/DC100%2/2
$end > 0 and substr($$bref, $end - 1, 1) =~ /[\r\n]/
$end > 0 substr($$bref, $end - 1, 1) =~ /[\r\n]/
Truth table100%3/3
A and B
A= $end > 0B= substr($$bref, $end - 1, 1) =~ /[\r\n]/
ABresult
0X0
100
111
196 }
197  
198 234 ▶ for (my $pos = 0; $pos < $end; ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $end) 253 234 487
199 253 my $n = $end - $pos;
200 253 ▶ if ($n > BODY_CHUNK) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n > 1048576) 59 194 253
201 59 my $nl = index($$bref, "\n", $pos + BODY_CHUNK);
202 59 ▶ $n = $nl + 1 - $pos if $nl >= 0 && $nl < $end;
Branch: 1 branch
BranchTrueFalseTotal
if $nl >= 0 and $nl < $end 58 1 59
Condition66%2/3
$nl >= 0 and $nl < $end
!ll&&!rl&&r
1058
MC/DC50%1/2
$nl >= 0 and $nl < $end
$nl >= 0 $nl < $end
Truth table66%2/3
A and B
A= $nl >= 0B= $nl < $end
ABresult
0X0
100
111
203 }
204 # s/\r?\n/\r\n/g, as two literal substitutions: several times
205 # faster, the same result ("\r\r\n" stays "\r\r\n").
206 253 my $piece = substr($$bref, $pos, $n);
207 253 ▶ $piece =~ s/\r\n/\n/g if index($piece, "\r") >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($piece, "\r") != -1 169 84 253
208 253 $piece =~ s/\n/\r\n/g;
209 253 $_->add($piece) for @$digests;
210 253 $pos += $n;
211 }
212 234 ▶ if ($final) {
Branch: 1 branch
BranchTrueFalseTotal
if ($final) 215 19 234
213 215 $_->add("\r\n") for @$digests;
214 }
215 234 return $end;
216 }
217  
218 # Mark the body Recipe as null per -09 §5.2: the body changed but the
219 # previous state cannot be recreated. as_string() then emits "b": null.
220 66 ▶sub set_null_body_recipe {
Subroutine set_null_body_recipe: called CC=1 SCAR=0.0
Pod documented
221 66 my ($self) = @_;
222 66 delete $self->{bits}{rb};
223 66 $self->{bits}{rb_null} = 1; # as parse() records it
224 }
225  
226 # True if this instance declares the previous state non-recreatable (a null
227 # "b" Recipe). Such an instance cannot be undone to a prior version. Under
228 # -09 §5.1 a header Recipe can no longer be null, so only the body
229 # Recipe can render an instance unrecoverable.
230 4695 ▶sub unrecoverable {
Subroutine unrecoverable: called CC=2 SCAR=6.9
Pod documented
231 4695 my ($self) = @_;
232 4695 ▶ return $self->{bits}{rb_null} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'bits'}{'rb_null'} ? : 224 4471 4695
233 }
234  
235 # --- Wire format: m=N; h=sha256:header_hash:body_hash; r=<b64json> ---
236  
237 818 ▶sub as_string {
Subroutine as_string: called CC=9 SCAR=22.0
Pod documented
238 818 my ($self) = @_;
239 818 my %data = %{$self->{bits}};
240 818 my $m = delete $data{m};
241 818 ▶ my $hashes = delete($data{hashes}) || {};
Condition50%1/2
delete $data{'hashes'} || {}
l!l
8180
MC/DC0%0/1
delete $data{'hashes'} || {}
delete $data{'hashes'}
Truth table50%1/2
A
A= delete $data{'hashes'}
Aresult
11
00
242  
243 # -09 §9.3: h= is "|" groups of "," lists of hash-sets. A parsed
244 # instance writes the groups it was given; a calculated one, one list
245 # with a hash-set per configured algorithm, in the signer's order
246 # (default: sha256 only).
247 818 ▶ my $groups = $self->{hash_groups} || [ $self->{algs} || ['sha256'] ];
Condition100%4/4
$self->{'hash_groups'} || [$self->{'algs'} || ['sha256']]
l!l
2816
$self->{'algs'} || ['sha256']
l!l
8151
MC/DC100%1/1
$self->{'hash_groups'} || [$self->{'algs'} || ['sha256']]
$self->{'hash_groups'}
MC/DC100%1/1
$self->{'algs'} || ['sha256']
$self->{'algs'}
Truth table100%2/2
A
A= $self->{'hash_groups'}
Aresult
11
00
Truth table100%2/2
A
A= $self->{'algs'}
Aresult
11
00
248 my $result = "m=$m; h=" . join('|', map {
249 818 join ',', map { "$_:$hashes->{$_}[0]:$hashes->{$_}[1]" } grep { $hashes->{$_} } @$_
250 } @$groups);
251  
252 # Build r= tag JSON if there are Recipes
253 818 my %recipe_json;
254 818 ▶ if (delete $data{rb_null}) {
Branch: 2 branches
BranchTrueFalseTotal
if (delete $data{'rb_null'}) { } 65 753 818
elsif (exists $data{'rb'}) { } 170 583 753
255 65 $recipe_json{b} = undef; # encodes as JSON null
256 65 delete $data{rb};
257 } elsif (exists $data{rb}) {
258 170 $recipe_json{b} = _encode_recipe_list(delete $data{rb});
259 }
260 818 ▶ if (exists $data{rh}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data{"rh"}) 186 632 818
261 186 my $rh = delete $data{rh};
262 186 my %encoded;
263 # -09 §5.1: header field names in the JSON Recipes MUST be lower
264 # case (matching against the message stays case-insensitive).
265 186 for my $h (sort keys %$rh) {
266 241 $encoded{lc $h} = _encode_recipe_list($rh->{$h});
267 }
268 186 $recipe_json{h} = \%encoded;
269 }
270  
271 818 ▶ if (keys %recipe_json) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %recipe_json) 290 528 818
272 290 $result .= "; r=" . encode_tag_json(\%recipe_json);
273 }
274 818 $result .= ";";
275  
276 818 return $result;
277 }
278  
279 # The whole field, folded where its grammar allows, ready to go at the top
280 # of a message (no line break at the end); and its value alone, folded the
281 # same way, for a milter's addheader/insheader, which takes name and value
282 # apart.
283 98 ▶sub as_header {
Subroutine as_header: called CC=1 SCAR=0.0
Pod documented
284 98 my ($self) = @_;
285 98 return Mail::DKIM2::Fold::fold_header('Message-Instance: ' . $self->as_string);
286 }
287  
288 88 ▶sub as_header_value {
Subroutine as_header_value: called CC=1 SCAR=0.0
Pod documented
289 88 my ($self) = @_;
290 88 (my $value = $self->as_header) =~ s/\AMessage-Instance:[ \t]*//;
291 88 return $value;
292 }
293  
294 # What this instance says its hop changed, read off its Recipes: the body
295 # ('unchanged', no body Recipe; 'changed', one that rebuilds the previous
296 # body; 'unrecoverable', the null Recipe) and the names of the header
297 # fields with a Recipe, lower-cased and sorted.
298 613 ▶sub changes {
Subroutine changes: called CC=4 SCAR=13.9
Pod documented
299 613 my ($self) = @_;
300 613 my $bits = $self->{bits};
301 return {
302 body => $bits->{rb_null} ? 'unrecoverable' : $bits->{rb} ? 'changed' : 'unchanged',
303 613 ▶ headers => [ sort map { Mail::DKIM2::Canon::field_name($_) } keys %{ $bits->{rh} || {} } ],
Branch: 2 branches
BranchTrueFalseTotal
$bits->{'rb_null'} ? : 36 577 613
$bits->{'rb'} ? : 438 139 577
Condition100%2/2
$bits->{'rh'} || {}
l!l
479134
MC/DC100%1/1
$bits->{'rh'} || {}
$bits->{'rh'}
Truth table100%2/2
A
A= $bits->{'rh'}
Aresult
11
00
304 };
305 }
306  
307 # True if this instance has a header Recipe for the field named $name.
308 610 ▶sub changes_header {
Subroutine changes_header: called CC=2 SCAR=6.9
Pod documented
309 610 my ($self, $name) = @_;
310 610 my $want = Mail::DKIM2::Canon::field_name($name);
311 610 ▶ return (grep { $_ eq $want } @{ $self->changes->{headers} }) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
grep({$_ eq $want;} @{$self->changes->{'headers'};}) ? : 165 445 610
312 }
313  
314 # Convert internal Recipe list to wire format
315 # Internal: [from,to] arrays for copy ranges, strings for literal content
316 # Wire (draft -09 section 5): {"c": [from,to]} for a copy, {"d": [...]} for
317 # literals that are UTF-8, {"u": ["base64",...]} for literals that are not.
318 #
319 # A literal is the raw octets of a header value or body line. One that is
320 # valid UTF-8 (ASCII included) goes in a "d" step as JSON text. Anything
321 # else (ISO-2022-JP, GB18030, Big5, Latin-1 ...) goes in a "u" step,
322 # canonical base64 (RFC 4648 section 4) of the octets: JSON text is UTF-8, so
323 # the only way to carry such a literal in JSON unchanged is to encode it, and
324 # "u" SHOULD NOT be used where "d" would do (section 5).
325 # Consecutive literals of the same kind share one step.
326 412 ▶sub _encode_recipe_list {
Subroutine _encode_recipe_list: called CC=6 SCAR=17.9
327 412 my ($list) = @_;
328 412 my @encoded;
329 412 my $pending_kind = '';
330 412 my @pending;
331 848 ▶ my $flush = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
332 848 ▶ return unless @pending;
Branch: 1 branch
BranchTrueFalseTotal
unless @pending 617 231 848
333 231 push @encoded, { $pending_kind => [@pending] };
334 231 @pending = ();
335 412 };
336 412 for my $item (@$list) {
337 2056 ▶ if (ref $item eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $item eq 'ARRAY') { } 209 1847 2056
338 209 $flush->();
339 # Force numeric: an index that was used as a hash key upstream
340 # (de-duplicating copies) is stringified in place, and the JSON
341 # encoder would then emit {"c":["2","2"]} -- strings, which the
342 # section 5 schema forbids and Go rejects as invalid JSON.
343 209 push @encoded, { c => [ map { 0 + $_ } @$item ] };
344 } else {
345 1847 ▶ my $kind = Mail::DKIM2::RecipeJSON::is_utf8_octets($item) ? 'd' : 'u';
Branch: 1 branch
BranchTrueFalseTotal
Mail::DKIM2::RecipeJSON::is_utf8_octets($item) ? : 1796 51 1847
346 1847 ▶ $flush->() if $kind ne $pending_kind;
Branch: 1 branch
BranchTrueFalseTotal
if $kind ne $pending_kind 227 1620 1847
347 1847 $pending_kind = $kind;
348 1847 ▶ push @pending, $kind eq 'u' ? encode_base64($item, '') : $item;
Branch: 1 branch
BranchTrueFalseTotal
$kind eq 'u' ? : 51 1796 1847
349 }
350 }
351 412 $flush->();
352 412 return \@encoded;
353 }
354  
355 # --- Parsing ---
356  
357 4153 ▶sub parse {
Subroutine parse: called CC=36 SCAR=36.0
Pod documented
358 4153 my ($class, $header) = @_;
359 4153 ▶ my $self = bless {}, ref($class) || $class;
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
041530
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
360  
361 # Strip leading whitespace
362 4153 $header =~ s/^\s+//;
363  
364 # Parse tag-value format: m=N; h=...; r=... Tag-names MUST be lowercase
365 # (-09 §9) and are case-sensitive (§8), so one that is not lowercase is
366 # an unknown tag and ignored (the -08 contract, D10): "M=1" alone is a
367 # missing m=. There MUST be only one of each kind, and a repeat is a
368 # syntax error -- never a silent overwrite, which let a wrong h= ahead
369 # of the right one pass (review R5).
370 # The list must parse as a whole (TagValueList's grammar): a fragment
371 # that is not a tag is a syntax error, not something to skip
372 # (follow-up review F3).
373 4153 my ($pairs, $ok) = Mail::DKIM2::TagValueList::split_tag_list($header);
374 4153 my (%tags, $dup, $raw_h);
375 4153 for my $p (@$pairs) {
376 10605 my ($name, $val) = @$p;
377 10605 ▶ next if $name =~ /[A-Z]/;
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /[A-Z]/ 4 10601 10605
378 10601 ▶ $raw_h = $val if $name eq 'h';
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "h" 4153 6448 10601
379 10601 $val =~ s/\s//gs;
380 10601 ▶ $dup = 1 if exists $tags{$name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $tags{$name} 3 10598 10601
381 10601 $tags{$name} = $val;
382 }
383  
384 die "missing m= tag in Message-Instance header"
385 4153 ▶ unless exists $tags{m};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $tags{"m"} 0 4153 4153
386 4153 ▶ die "PERMERROR: Message-Instance m=$tags{m} syntax error\n" if $dup || !$ok;
Branch: 1 branch
BranchTrueFalseTotal
if $dup or not $ok 13 4140 4153
Condition100%3/3
$dup or not $ok
l!l&&r!l&&!r
3104140
MC/DC100%2/2
$dup or not $ok
$dup not $ok
Truth table100%3/3
A or not(B)
A= $dupB= not $ok
ABresult
1X1
011
000
387 # -09 section 9: h= is required.
388 4140 ▶ die "PERMERROR: Message-Instance m=$tags{m} tag=h missing\n" unless exists $tags{h};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $tags{"h"} 2 4138 4140
389 4138 $self->{bits}{m} = $tags{m};
390  
391 # -09 section 9.3: h= is a list of hash-sets
392 4138 ▶ if (exists $tags{h}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $tags{"h"}) 4138 0 4138
393 4138 ▶ my $groups = parse_hash_groups($raw_h)
Branch: 1 branch
BranchTrueFalseTotal
my $groups = parse_hash_groups($raw_h) or die qq[PERMERROR: Message-Instance m=$tags{"m"} syntax error\n] 4129 9 4138
394 or die "PERMERROR: Message-Instance m=$tags{m} syntax error\n";
395 4129 my $sets = [ map { @$_ } @$groups ];
396  
397 # §9.3: an algorithm MUST NOT be present more than once, in any
398 # group (D2). Check the LIST of sets, not a hash keyed by algorithm
399 # -- a hash would let the second occurrence silently overwrite the
400 # first, hiding the duplicate. Names are case-sensitive (§2.14).
401 # This must run before any hash is computed or compared.
402 4129 my %seen;
403 4129 for my $s (@$sets) {
404 5465 ▶ if ($seen{$s->[0]}++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen{$s->[0]}++) 7 5458 5465
405 7 die "PERMERROR: Message-Instance m=$tags{m} has a duplicate hash algorithm\n";
406 }
407 }
408  
409 4122 for my $s (@$sets) {
410 5451 $self->{bits}{hashes}{$s->[0]} = [$s->[1], $s->[2]];
411 }
412 # The order h= lists them in: the order they are checked in; and
413 # its "|" groups of "," lists (-09 §9.3).
414 4122 $self->{hash_order} = [ map { $_->[0] } @$sets ];
415 4122 $self->{hash_groups} = [ map { [ map { $_->[0] } @$_ ] } @$groups ];
416 }
417  
418 4122 ▶ if (exists $tags{r}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $tags{"r"}) 2290 1832 4122
419 # -09 §14.2: a bad base64 r= value and a post-decode JSON parse
420 # failure are different errors and must stay distinct: base64
421 # failure -> "syntax error" (§14.2 lists this explicitly for
422 # malformed field content); JSON failure -> "contains invalid JSON".
423 # decode_base64() is lenient (silently drops non-alphabet
424 # characters rather than failing), so a strict format check is
425 # needed here to actually catch malformed base64 -- otherwise it
426 # would just decode to garbage bytes that happen to also fail JSON
427 # parsing, mislabelling the error.
428 2290 ▶ if ($tags{r} !~ m{\A(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?\z}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tags{"r"} =~ m[\A(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?\z]) 1 2289 2290
429 1 die "PERMERROR: Message-Instance m=$tags{m} syntax error\n";
430 }
431 # Anything wrong with the JSON document as a whole -- its syntax,
432 # its keys, the shape of "h" and "b" -- is "contains invalid JSON";
433 # one bad step is "recipe <path> is invalid" (-09 §14.2, contract
434 # D6), with the path b[<n>] or h.<name>[<n>]: the first bad one, b
435 # before h, header names in byte order, steps in order.
436 2289 my $invalid = "PERMERROR: Message-Instance m=$tags{m} contains invalid JSON\n";
437 2289 ▶ my $bad = sub { "PERMERROR: Message-Instance m=$tags{m} recipe $_[0] is invalid\n" };
Subroutine __ANON__: called CC=1 SCAR=0.0
438 2289 my $recipe_data = eval { decode_tag_json($tags{r}) };
439 2289 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 34 2255 2289
440 34 ▶ die $@ if ref $@;
Branch: 1 branch
BranchTrueFalseTotal
if ref $@ 0 34 34
441 34 die $invalid;
442 }
443 2255 ▶ die $invalid unless ref $recipe_data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recipe_data eq "HASH" 0 2255 2255
444 # Every key is lowercase (-09 §5): decode_tag_json has already
445 # refused one that is not, and a key given twice. Other top-level
446 # keys are ignored; at least one of h and b is required.
447 2255 my %top = %$recipe_data;
448 2255 ▶ die $invalid unless exists $top{h} || exists $top{b};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $top{"h"} or exists $top{"b"} 2 2253 2255
Condition100%3/3
exists $top{"h"} or exists $top{"b"}
l!l&&r!l&&!r
105411992
MC/DC100%2/2
exists $top{"h"} or exists $top{"b"}
exists $top{"h"} exists $top{"b"}
Truth table100%3/3
A or B
A= exists $top{"h"}B= exists $top{"b"}
ABresult
1X1
011
000
449 # The document's shape before any step (D6): "h" a non-empty object
450 # (minProperties 1; never null, section 5.1), "b" an array or null.
451 2253 ▶ die $invalid if exists $top{h} && !(ref $top{h} eq 'HASH' && %{$top{h}});
Branch: 1 branch
BranchTrueFalseTotal
if exists $top{"h"} and not ref $top{"h"} eq "HASH" && %{$top{"h"};} 6 2247 2253
Condition100%6/6
exists $top{"h"} and not ref $top{"h"} eq "HASH" && %{$top{"h"};}
!ll&&!rl&&r
119910486
ref $top{'h'} eq 'HASH' && %{$top{'h'};}
!ll&&!rl&&r
511048
MC/DC100%3/3
exists $top{"h"} and not ref $top{"h"} eq "HASH" && %{$top{"h"};}
exists $top{"h"} ref $top{'h'} eq 'HASH' %{$top{'h'};}
Truth table100%4/4
A and not(B && C)
A= exists $top{"h"}B= ref $top{'h'} eq 'HASH'C= %{$top{'h'};}
ABCresult
0XX0
1110
10X1
1101
452 2247 ▶ die $invalid if exists $top{b} && defined $top{b} && ref $top{b} ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if exists $top{"b"} and defined $top{"b"} and ref $top{"b"} ne "ARRAY" 4 2243 2247
Condition100%6/6
exists $top{"b"} and defined $top{"b"} and ref $top{"b"} ne "ARRAY"
!ll&&!rl&&r
60016434
exists $top{"b"} and defined $top{"b"}
!ll&&!rl&&r
3852151647
MC/DC100%3/3
exists $top{"b"} and defined $top{"b"} and ref $top{"b"} ne "ARRAY"
exists $top{"b"} defined $top{"b"} ref $top{"b"} ne "ARRAY"
Truth table100%4/4
A and B and C
A= exists $top{"b"}B= defined $top{"b"}C= ref $top{"b"} ne "ARRAY"
ABCresult
0XX0
10X0
1100
1111
453 # A null "b" (section 5.2) means the previous body cannot be
454 # recreated -- distinct from an absent one (no change).
455 2243 ▶ if (exists $top{b}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $top{"b"}) 1858 385 2243
456 1858 ▶ if (ref $top{b} eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $top{'b'} eq 'ARRAY') { } 1643 215 1858
elsif (not defined $top{'b'}) { } 215 0 215
457 1643 $self->{bits}{rb} = _decode_recipe_list($top{b}, $bad, 'b');
458 } elsif (!defined $top{b}) {
459 215 $self->{bits}{rb_null} = 1;
460 } else {
461 0 die $invalid;
462 }
463 }
464 2074 ▶ if (exists $top{h}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $top{"h"}) 1048 1026 2074
465 # A non-empty object (minProperties 1); never null (section 5.1).
466 1048 ▶ die $invalid unless ref $top{h} eq 'HASH' && %{$top{h}};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $top{"h"} eq "HASH" and %{$top{"h"};} 0 1048 1048
Condition33%1/3
ref $top{"h"} eq "HASH" and %{$top{"h"};}
!ll&&!rl&&r
001048
MC/DC0%0/2
ref $top{"h"} eq "HASH" and %{$top{"h"};}
ref $top{"h"} eq "HASH" %{$top{"h"};}
Truth table33%1/3
A and B
A= ref $top{"h"} eq "HASH"B= %{$top{"h"};}
ABresult
0X0
100
111
467 1048 my %rh;
468 # Each key is a header field name (-09 section 5): ftext, so no
469 # WSP. "message-instance " is not a name -- and, taken for one
470 # by name matching that drops WSP before a colon, would let a
471 # Recipe rewrite the instances below it.
472 1048 ▶ die $invalid if grep { !/\A[\x21-\x39\x3B-\x7E]+\z/ } keys %{$top{h}};
Branch: 1 branch
BranchTrueFalseTotal
if grep {not /\A[\x21-\x39\x3B-\x7E]+\z/;} keys %{$top{"h"};} 14 1034 1048
473 1034 for my $h (sort keys %{$top{h}}) {
474 2831 $rh{$h} = _decode_recipe_list($top{h}{$h}, $bad, 'h.' . _path_name($h));
475 }
476 998 $self->{bits}{rh} = \%rh;
477 }
478 }
479  
480 3856 return $self;
481 }
482  
483 # Convert wire format Recipe list to internal format
484 # Wire (-09 section 5): an array of steps, each an object with exactly one
485 # key, "c", "d" or "u": {"c": [from,to]} copies, {"d": [...]} emits UTF-8
486 # literals, {"u": [...]} emits base64 ones.
487 # Internal: [from,to] arrays for copy ranges, strings for literal content
488 #
489 # A "u" item is decoded here, so the rest of the module sees one kind of
490 # literal: a plain byte string. The schema's checks are all made here, and
491 # so are §5.1/§5.2's rules on copy ranges that need no message: a range is
492 # exactly two JSON integers of at least 1, start <= end, each starting
493 # after the one before ends (no overlap, nothing out of order); a "d" or "u"
494 # array has at least one string; a "u" string is canonical base64 -- the
495 # alphabet, padding to a multiple of four, and zero pad bits, the schema's
496 # three patterns -- with no FWS; and no literal, "d" text or decoded "u"
497 # octets, may contain CR or LF, since a literal is exactly one header value
498 # or one body line. "d" text is UTF-8 already: decode_tag_json refuses JSON
499 # that is not. A list that is not an array is bad as a whole ($path); a bad
500 # step dies with $bad->("$path[<n>]"), n its 0-based index (contract D6).
501 # Whether a range lies within the lines it copies is for _check_recipe,
502 # when the Recipe is applied.
503 196 my $U_PATTERN = qr{\A(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?\z};
504 4475 ▶sub _decode_recipe_list {
Subroutine _decode_recipe_list: called CC=24 SCAR=31.8
505 4475 my ($list, $bad, $path) = @_;
506 4475 ▶ die $bad->($path) unless ref $list eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list eq "ARRAY" 1 4474 4475
507 4474 my (@decoded, $prev_end);
508 4474 for my $n (0 .. $#$list) {
509 5376 my $item = $list->[$n];
510 5376 my $invalid = $bad->("$path\[$n]");
511 5376 ▶ die $invalid unless ref $item eq 'HASH' && keys %$item == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" and keys %$item == 1 10 5366 5376
Condition100%3/3
ref $item eq "HASH" and keys %$item == 1
!ll&&!rl&&r
825366
MC/DC100%2/2
ref $item eq "HASH" and keys %$item == 1
ref $item eq "HASH" keys %$item == 1
Truth table100%3/3
A and B
A= ref $item eq "HASH"B= keys %$item == 1
ABresult
0X0
100
111
512 5366 my ($kind) = keys %$item;
513 5366 my $val = $item->{$kind};
514 5366 ▶ die $invalid unless ref $val eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $val eq "ARRAY" 17 5349 5366
515 5349 ▶ if ($kind eq 'c') {
Branch: 3 branches
BranchTrueFalseTotal
if ($kind eq 'c') { } 2688 2661 5349
elsif ($kind eq 'd') { } 2598 63 2661
elsif ($kind eq 'u') { } 58 5 63
516 die $invalid unless @$val == 2
517 2688 ▶ && !grep { !_is_json_integer($_) || $_ < 1 } @$val;
Branch: 1 branch
BranchTrueFalseTotal
unless @$val == 2 and not grep({not _is_json_integer($_) or $_ < 1;} @$val) 52 2636 2688
Condition100%6/6
@$val == 2 and not grep({not _is_json_integer($_) or $_ < 1;} @$val)
!ll&&!rl&&r
17352636
!_is_json_integer($_) || $_ < 1
l!l&&r!l&&!r
25145303
MC/DC100%2/2
@$val == 2 and not grep({not _is_json_integer($_) or $_ < 1;} @$val)
@$val == 2 not grep({not _is_json_integer($_) or $_ < 1;} @$val)
MC/DC100%2/2
!_is_json_integer($_) || $_ < 1
!_is_json_integer($_) $_ < 1
Truth table100%3/3
A and not(B)
A= @$val == 2B= not grep({not _is_json_integer($_) or $_ < 1;} @$val)
ABresult
0X0
100
111
Truth table100%3/3
not(A) || B
A= !_is_json_integer($_)B= $_ < 1
ABresult
1X1
011
000
518 2636 ▶ die $invalid if $val->[0] > $val->[1]
Branch: 1 branch
BranchTrueFalseTotal
if $val->[0] > $val->[1] or defined $prev_end and $val->[0] <= $prev_end 49 2587 2636
Condition100%6/6
$val->[0] > $val->[1] or defined $prev_end and $val->[0] <= $prev_end
l!l&&r!l&&!r
11382587
defined $prev_end and $val->[0] <= $prev_end
!ll&&!rl&&r
1541104638
MC/DC100%3/3
$val->[0] > $val->[1] or defined $prev_end and $val->[0] <= $prev_end
$val->[0] > $val->[1] defined $prev_end $val->[0] <= $prev_end
Truth table100%4/4
A or B and C
A= $val->[0] > $val->[1]B= defined $prev_endC= $val->[0] <= $prev_end
ABCresult
1XX1
0111
00X0
0100
519 || (defined $prev_end && $val->[0] <= $prev_end);
520 2587 $prev_end = $val->[1];
521 2587 push @decoded, $val;
522 } elsif ($kind eq 'd') {
523 2598 ▶ die $invalid unless @$val;
Branch: 1 branch
BranchTrueFalseTotal
unless @$val 8 2590 2598
524 2590 for my $text (@$val) {
525 6622 ▶ die $invalid unless _is_json_string($text) && $text !~ /[\r\n]/;
Branch: 1 branch
BranchTrueFalseTotal
unless _is_json_string($text) and not $text =~ /[\r\n]/ 20 6602 6622
Condition100%3/3
_is_json_string($text) and not $text =~ /[\r\n]/
!ll&&!rl&&r
4166602
MC/DC100%2/2
_is_json_string($text) and not $text =~ /[\r\n]/
_is_json_string($text) not $text =~ /[\r\n]/
Truth table100%3/3
A and not(B)
A= _is_json_string($text)B= not $text =~ /[\r\n]/
ABresult
0X0
100
111
526 }
527 2570 push @decoded, @$val;
528 } elsif ($kind eq 'u') {
529 58 ▶ die $invalid unless @$val;
Branch: 1 branch
BranchTrueFalseTotal
unless @$val 4 54 58
530 54 for my $b64 (@$val) {
531 59 ▶ die $invalid unless _is_json_string($b64) && $b64 =~ $U_PATTERN;
Branch: 1 branch
BranchTrueFalseTotal
unless _is_json_string($b64) and $b64 =~ /$U_PATTERN/ 26 33 59
Condition100%3/3
_is_json_string($b64) and $b64 =~ /$U_PATTERN/
!ll&&!rl&&r
42233
MC/DC100%2/2
_is_json_string($b64) and $b64 =~ /$U_PATTERN/
_is_json_string($b64) $b64 =~ /$U_PATTERN/
Truth table100%3/3
A and B
A= _is_json_string($b64)B= $b64 =~ /$U_PATTERN/
ABresult
0X0
100
111
532 33 my $octets = decode_base64($b64);
533 33 ▶ die $invalid if $octets =~ /[\r\n]/;
Branch: 1 branch
BranchTrueFalseTotal
if $octets =~ /[\r\n]/ 13 20 33
534 20 push @decoded, $octets;
535 }
536 } else {
537 5 die $invalid;
538 }
539 }
540 4270 return \@decoded;
541 }
542  
543 # A header name as a Recipe path writes it: printable ASCII as it is,
544 # any other octet as \xHH (contract D6).
545 2831 ▶sub _path_name {
Subroutine _path_name: called CC=1 SCAR=0.2
546 2831 my ($name) = @_;
547 0 $name =~ s/([^\x21-\x7e])/sprintf '\\x%02X', ord $1/ge;
548 2831 return $name;
549 }
550  
551 # --- Digests ---
552  
553 1438 ▶sub h_digest {
Subroutine h_digest: called CC=6 SCAR=17.9
Pod documented
554 1438 my ($msg, $alg, $prefixes) = @_;
555 1438 ▶ $alg = lc($alg // 'sha256');
Condition100%2/2
$alg // "sha256"
l!l
14362
MC/DC100%1/1
$alg // "sha256"
$alg
Truth table100%2/2
A
A= $alg
Aresult
11
00
556  
557 # Fields grouped by name as DKIM2 compares names (field_name: "From :"
558 # is a From), names in order, each name's fields bottom-up.
559 1438 my @pairs = $msg->header_obj->header_raw_pairs;
560 1438 my %by;
561 15132 push @{ $by{ Mail::DKIM2::Canon::field_name($pairs[2 * $_]) } }, $pairs[2 * $_ + 1]
562 1438 for 0 .. $#pairs / 2;
563 1438 my $data = '';
564 1438 for my $header (sort keys %by) {
565 10866 ▶ next if should_skip($header, $prefixes);
Branch: 1 branch
BranchTrueFalseTotal
if should_skip($header, $prefixes) 3722 7144 10866
566 7144 for my $item (reverse @{ $by{$header} }) {
567 7235 my $chead = dkim2_canonicalize_header("$header: $item\r\n");
568 7235 $data .= $chead;
569 }
570 }
571  
572 1438 return _hash_data_b64($alg, $data);
573 }
574  
575 1366 ▶sub b_digest {
Subroutine b_digest: called CC=2 SCAR=6.9
Pod documented
576 1366 my ($msg, $alg) = @_;
577 1366 ▶ $alg = lc($alg // 'sha256');
Condition100%2/2
$alg // "sha256"
l!l
134917
MC/DC100%1/1
$alg // "sha256"
$alg
Truth table100%2/2
A
A= $alg
Aresult
11
00
578  
579 # DKIM simple body canonicalization: strip trailing empty lines,
580 # ensure exactly one trailing CRLF
581 1366 my $body = $msg->body_raw;
582 1366 $body =~ s/(\r\n)+\z//;
583 1366 $body .= "\r\n";
584  
585 1366 return _hash_data_b64($alg, $body);
586 }
587  
588 # -09 §3.1/§3.5: hash $data with the named (implemented) algorithm and
589 # base64-encode the result.
590 6385 ▶sub _hash_data_b64 {
Subroutine _hash_data_b64: called CC=2 SCAR=7.1
591 6385 my ($alg, $data) = @_;
592 6385 ▶ my $fn = $HASH_ALGS{$alg} or croak "unsupported hash algorithm: $alg";
Branch: 1 branch
BranchTrueFalseTotal
my $fn = $HASH_ALGS{$alg} or croak("unsupported hash algorithm: $alg") 6385 0 6385
593 6385 return encode_base64($fn->($data), '');
594 }
595  
596 # --- Body Recipe computation ---
597  
598 # The capped Myers line diff, the same algorithm in every implementation in
599 # this repository so they emit identical Recipes (docs/superpowers/specs/
600 # 2026-10-09-capped-myers-body-diff-design.md).
601 #
602 # _body_diff(\@cur, \@prev, $max_literals) returns undef when the bodies are
603 # identical, 'too_big' when rebuilding @prev would take more than
604 # $max_literals literal lines or the search ran out of work budget, else the
605 # Recipe: [from,to] copy ranges (1-based, into @cur) and literal lines, in
606 # @prev order.
607 #
608 # The cap is on the Recipe's output, but it bounds the search exactly:
609 # literals = M - LCS and edits D = N + M - 2*LCS, so at most L literals
610 # means D <= N - M + 2L. MAX_DIFF_WORK bounds the rest -- CPU and trace
611 # memory when N is much larger than M and that edit bound is loose.
612 196 ▶use constant MAX_RECIPE_LITERALS => 1000;
Subroutine BEGIN: called CC=1 SCAR=0.0
613 196 ▶use constant MAX_DIFF_WORK => 4_000_000;
Subroutine BEGIN: called CC=1 SCAR=0.0
614  
615 285 ▶sub _body_diff {
Subroutine _body_diff: called CC=56 SCAR=40.3
616 285 my ($cur, $prev, $max) = @_;
617 285 ▶ $max //= MAX_RECIPE_LITERALS;
Condition100%2/2
$max //= 1000
l!l
30255
MC/DC100%1/1
$max //= 1000
$max
Truth table100%2/2
A
A= $max
Aresult
11
00
618 285 my ($C, $P) = (scalar @$cur, scalar @$prev);
619  
620 # 1. Trim the common prefix and suffix.
621 285 my $pre = 0;
622 285 ▶ $pre++ while $pre < $C && $pre < $P && $cur->[$pre] eq $prev->[$pre];
Branch: 1 branch
BranchTrueFalseTotal
$pre < $C and $pre < $P and $cur->[$pre] eq $prev->[$pre] and do { ++$pre } 1092 285 1377
Condition100%6/6
$pre < $C and $pre < $P and $cur->[$pre] eq $prev->[$pre]
!ll&&!rl&&r
221641092
$pre < $C and $pre < $P
!ll&&!rl&&r
551661156
MC/DC100%3/3
$pre < $C and $pre < $P and $cur->[$pre] eq $prev->[$pre]
$pre < $C $pre < $P $cur->[$pre] eq $prev->[$pre]
Truth table100%4/4
A and B and C
A= $pre < $CB= $pre < $PC= $cur->[$pre] eq $prev->[$pre]
ABCresult
0XX0
10X0
1100
1111
623 285 ▶ return undef if $pre == $C && $pre == $P;
Branch: 1 branch
BranchTrueFalseTotal
if $pre == $C and $pre == $P 53 232 285
Condition100%3/3
$pre == $C and $pre == $P
!ll&&!rl&&r
230253
MC/DC100%2/2
$pre == $C and $pre == $P
$pre == $C $pre == $P
Truth table100%3/3
A and B
A= $pre == $CB= $pre == $P
ABresult
0X0
100
111
624 232 my $suf = 0;
625 232 ▶ $suf++ while $suf < $C - $pre && $suf < $P - $pre
Branch: 1 branch
BranchTrueFalseTotal
$suf < $C - $pre and $suf < $P - $pre and $$cur[$C - 1 - $suf] eq $$prev[$P - 1 - $suf] and do { ++$suf } 2502 232 2734
Condition100%6/6
$suf < $C - $pre and $suf < $P - $pre and $$cur[$C - 1 - $suf] eq $$prev[$P - 1 - $suf]
!ll&&!rl&&r
199332502
$suf < $C - $pre and $suf < $P - $pre
!ll&&!rl&&r
301692535
MC/DC100%3/3
$suf < $C - $pre and $suf < $P - $pre and $$cur[$C - 1 - $suf] eq $$prev[$P - 1 - $suf]
$suf < $C - $pre $suf < $P - $pre $$cur[$C - 1 - $suf] eq $$prev[$P - 1 - $suf]
Truth table100%4/4
A and B and C
A= $suf < $C - $preB= $suf < $P - $preC= $$cur[$C - 1 - $suf] eq $$prev[$P - 1 - $suf]
ABCresult
0XX0
10X0
1100
1111
626 && $cur->[$C - 1 - $suf] eq $prev->[$P - 1 - $suf];
627  
628 # 2. Intern the middle lines and discard those that cannot be in the
629 # LCS: a current line that never occurs in the previous middle is a pure
630 # deletion, a previous line that never occurs in the current middle is
631 # certainly a literal.
632 232 my (%id, %cnt_a, %cnt_b);
633 232 my @a_lines = @{$cur}[$pre .. $C - $suf - 1];
634 232 my @b_lines = @{$prev}[$pre .. $P - $suf - 1];
635 232 $cnt_b{$_}++ for @b_lines;
636 232 $cnt_a{$_}++ for @a_lines;
637 232 my (@A, @ai, @B, @bj);
638 232 for my $i (0 .. $#a_lines) {
639 279179 my $l = $a_lines[$i];
640 279179 ▶ next unless $cnt_b{$l};
Branch: 1 branch
BranchTrueFalseTotal
unless $cnt_b{$l} 50538 228641 279179
641 228641 ▶ push @A, $id{$l} //= scalar keys %id;
Condition100%2/2
$id{$l} //= scalar keys %id
l!l
124206104435
MC/DC100%1/1
$id{$l} //= scalar keys %id
$id{$l}
Truth table100%2/2
A
A= $id{$l}
Aresult
11
00
642 228641 push @ai, $i;
643 }
644 232 for my $j (0 .. $#b_lines) {
645 233652 my $l = $b_lines[$j];
646 233652 ▶ next unless $cnt_a{$l};
Branch: 1 branch
BranchTrueFalseTotal
unless $cnt_a{$l} 5017 228635 233652
647 228635 ▶ push @B, $id{$l} //= scalar keys %id;
Condition50%1/2
$id{$l} //= scalar keys %id
l!l
2286350
MC/DC0%0/1
$id{$l} //= scalar keys %id
$id{$l}
Truth table50%1/2
A
A= $id{$l}
Aresult
11
00
648 228635 push @bj, $j;
649 }
650 232 my ($N, $M) = (scalar @A, scalar @B);
651 232 my $unique = @b_lines - $M;
652  
653 # A previous line occurring more often than in the current body needs
654 # a literal for each extra copy: a lower bound on the literal count
655 # that costs nothing to check before searching.
656 232 my $floor = $unique;
657 232 for my $l (keys %cnt_b) {
658 109451 ▶ my $extra = $cnt_b{$l} - ($cnt_a{$l} // 0);
Condition100%2/2
$cnt_a{$l} // 0
l!l
1044355016
MC/DC100%1/1
$cnt_a{$l} // 0
$cnt_a{$l}
Truth table100%2/2
A
A= $cnt_a{$l}
Aresult
11
00
659 109451 ▶ $floor += $extra if $extra > 0 && $cnt_a{$l};
Branch: 1 branch
BranchTrueFalseTotal
if $extra > 0 and $cnt_a{$l} 1 109450 109451
Condition100%3/3
$extra > 0 and $cnt_a{$l}
!ll&&!rl&&r
10443450161
MC/DC100%2/2
$extra > 0 and $cnt_a{$l}
$extra > 0 $cnt_a{$l}
Truth table100%3/3
A and B
A= $extra > 0B= $cnt_a{$l}
ABresult
0X0
100
111
660 }
661 232 ▶ return 'too_big' if $floor > $max;
Branch: 1 branch
BranchTrueFalseTotal
if $floor > $max 8 224 232
662  
663 # 3. Myers' greedy O(ND) search over the reduced sequences, keeping each
664 # round's V (packed, 32 bits a diagonal) for the backtrack. x indexes
665 # @A (current), y indexes @B (previous); "down" takes a previous line as
666 # a literal, "right" skips a current line, a diagonal step is a match.
667 224 my @match; # $match[$y] = $x for each matched @B line
668 224 ▶ if ($N && $M) {
Branch: 1 branch
BranchTrueFalseTotal
if ($N and $M) 16 208 224
Condition66%2/3
$N and $M
!ll&&!rl&&r
208016
MC/DC50%1/2
$N and $M
$N $M
Truth table66%2/3
A and B
A= $NB= $M
ABresult
0X0
100
111
669 16 my $dmax = $N - $M + 2 * ($max - $unique);
670 16 ▶ $dmax = $N + $M if $dmax > $N + $M;
Branch: 1 branch
BranchTrueFalseTotal
if $dmax > $N + $M 11 5 16
671 16 ▶ return 'too_big' if $dmax < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $dmax < 0 0 16 16
672 16 my $off = $dmax + 1;
673 16 my @v = (0) x (2 * $off + 1);
674 16 my @trace;
675 16 my $work = 0;
676 16 my ($found, $x, $y);
677 16 ROUND: for my $d (0 .. $dmax) {
678 2026 push @trace, pack('N*', @v[$off - $d - 1 .. $off + $d + 1]);
679 2026 ▶ for (my $k = -$d; $k <= $d; $k += 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k <= $d) 2003051 2011 2005062
680 2003051 ▶ $x = ($k == -$d
Branch: 1 branch
BranchTrueFalseTotal
$k == -$d || $k != $d && $v[$off + $k - 1] < $v[$off + $k + 1] ? : 2001043 2008 2003051
Condition83%5/6
$k == -$d or $k != $d and $v[$off + $k - 1] < $v[$off + $k + 1]
l!l&&r!l&&!r
202619990172008
$k != $d and $v[$off + $k - 1] < $v[$off + $k + 1]
!ll&&!rl&&r
200801999017
MC/DC66%2/3
$k == -$d or $k != $d and $v[$off + $k - 1] < $v[$off + $k + 1]
$k == -$d $k != $d $v[$off + $k - 1] < $v[$off + $k + 1]
Truth table75%3/4
A or B and C
A= $k == -$dB= $k != $dC= $v[$off + $k - 1] < $v[$off + $k + 1]
ABCresult
1XX1
0111
00X0
0100
681 || ($k != $d && $v[$off + $k - 1] < $v[$off + $k + 1]))
682 ? $v[$off + $k + 1]
683 : $v[$off + $k - 1] + 1;
684 2003051 $y = $x - $k;
685 2003051 ▶ while ($x < $N && $y < $M && $A[$x] == $B[$y]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $N and $y < $M and $A[$x] == $B[$y]) 112625 2003051 2115676
Condition100%6/6
$x < $N and $y < $M and $A[$x] == $B[$y]
!ll&&!rl&&r
352003016112625
$x < $N and $y < $M
!ll&&!rl&&r
17182115641
MC/DC100%3/3
$x < $N and $y < $M and $A[$x] == $B[$y]
$x < $N $y < $M $A[$x] == $B[$y]
Truth table100%4/4
A and B and C
A= $x < $NB= $y < $MC= $A[$x] == $B[$y]
ABCresult
0XX0
10X0
1100
1111
686 112625 $x++; $y++; $work++;
687 }
688 2003051 $v[$off + $k] = $x;
689 2003051 ▶ return 'too_big' if ++$work > MAX_DIFF_WORK;
Branch: 1 branch
BranchTrueFalseTotal
if ++$work > 4000000 0 2003051 2003051
690 2003051 ▶ if ($x == $N && $y == $M) { $found = $d; last ROUND }
Branch: 1 branch
BranchTrueFalseTotal
if ($x == $N and $y == $M) 15 2003036 2003051
Condition100%3/3
$x == $N and $y == $M
!ll&&!rl&&r
2003034215
MC/DC100%2/2
$x == $N and $y == $M
$x == $N $y == $M
Truth table100%3/3
A and B
A= $x == $NB= $y == $M
ABresult
0X0
100
111
691 }
692 }
693 16 ▶ return 'too_big' unless defined $found;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $found 1 15 16
694  
695 # Backtrack: trace[d] holds V as it stood before round d, for
696 # diagonals -d-1 .. d+1 (index k + d + 1).
697 15 ▶ for (my $d = $found; $d > 0; $d--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($d > 0) 10 15 25
698 10 my $t = $trace[$d];
699 10 my $k = $x - $y;
700 10 ▶ my $down = $k == -$d
Condition66%4/6
$k == -$d || $k != $d && vec($t, $k - 1 + $d + 1, 32) < vec($t, $k + 1 + $d + 1, 32)
l!l&&r!l&&!r
028
$k != $d and vec($t, $k - 1 + $d + 1, 32) < vec($t, $k + 1 + $d + 1, 32)
!ll&&!rl&&r
802
MC/DC33%1/3
$k == -$d || $k != $d && vec($t, $k - 1 + $d + 1, 32) < vec($t, $k + 1 + $d + 1, 32)
$k == -$d $k != $d vec($t, $k - 1 + $d + 1, 32) < vec($t, $k + 1 + $d + 1, 32)
Truth table50%2/4
A || B and C
A= $k == -$dB= $k != $dC= vec($t, $k - 1 + $d + 1, 32) < vec($t, $k + 1 + $d + 1, 32)
ABCresult
1XX1
0111
00X0
0100
701 || ($k != $d && vec($t, $k - 1 + $d + 1, 32) < vec($t, $k + 1 + $d + 1, 32));
702 10 ▶ my $pk = $down ? $k + 1 : $k - 1;
Branch: 1 branch
BranchTrueFalseTotal
$down ? : 2 8 10
703 10 my $px = vec($t, $pk + $d + 1, 32);
704 10 my $py = $px - $pk;
705 10 ▶ my ($sx, $sy) = $down ? ($px, $py + 1) : ($px + 1, $py);
Branch: 1 branch
BranchTrueFalseTotal
$down ? : 2 8 10
706 10 ▶ while ($x > $sx) { $x--; $y--; $match[$y] = $x }
Branch: 1 branch
BranchTrueFalseTotal
if ($x > $sx) 4021 10 4031
707 10 ($x, $y) = ($px, $py);
708 }
709 15 ▶ while ($x > 0) { $x--; $y--; $match[$y] = $x }
Branch: 1 branch
BranchTrueFalseTotal
if ($x > 0) 104602 15 104617
710 }
711  
712 # 4. Map back to whole-body indices and build the Recipe in @prev order,
713 # merging copies that are adjacent in both bodies.
714 223 my %src;
715 223 for my $y (0 .. $#match) {
716 108623 ▶ next unless defined $match[$y];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $match[$y] 0 108623 108623
717 108623 $src{$pre + $bj[$y]} = $pre + $ai[$match[$y]];
718 }
719 223 my @recipe;
720 223 my $literals = 0;
721 223 for my $j (0 .. $P - 1) {
722 my $i = $j < $pre ? $j
723 : $j >= $P - $suf ? $j - $P + $C
724 113524 ▶ : $src{$j};
Branch: 2 branches
BranchTrueFalseTotal
$j < $pre ? : 835 112689 113524
$j >= $P - $suf ? : 1458 111231 112689
725 113524 ▶ if (!defined $i) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $i) { } 2608 110916 113524
elsif (@recipe and ref $recipe[-1] and $recipe[-1][1] == $i) { } 110563 353 110916
726 2608 push @recipe, $prev->[$j];
727 2608 $literals++;
728 ▶ } elsif (@recipe && ref $recipe[-1] && $recipe[-1][1] == $i) {
Condition100%6/6
@recipe and ref $recipe[-1] and $recipe[-1][1] == $i
!ll&&!rl&&r
3485110563
@recipe and ref $recipe[-1]
!ll&&!rl&&r
209139110568
MC/DC100%3/3
@recipe and ref $recipe[-1] and $recipe[-1][1] == $i
@recipe ref $recipe[-1] $recipe[-1][1] == $i
Truth table100%4/4
A and B and C
A= @recipeB= ref $recipe[-1]C= $recipe[-1][1] == $i
ABCresult
0XX0
10X0
1100
1111
729 110563 $recipe[-1][1] = $i + 1;
730 } else {
731 353 push @recipe, [$i + 1, $i + 1];
732 }
733 }
734 223 ▶ return 'too_big' if $literals > $max;
Branch: 1 branch
BranchTrueFalseTotal
if $literals > $max 0 223 223
735 223 return \@recipe;
736 }
737  
738 # --- Calculate helpers ---
739  
740 # The body Recipe rebuilding $prev_raw from $cur_raw (raw body strings):
741 # undef when they are the same body, "too_big" over $max literal lines.
742 # Lines split as the verifier rebuilds them, trailing line breaks dropped.
743 267 ▶sub _body_recipe {
Subroutine _body_recipe: called CC=1 SCAR=0.0
744 267 my ($cur_raw, $prev_raw, $max) = @_;
745 267 (my $s1 = $cur_raw) =~ s/[\r\n]+$//;
746 267 (my $s2 = $prev_raw) =~ s/[\r\n]+$//;
747 267 return _body_diff([split /\r?\n/, $s1], [split /\r?\n/, $s2], $max);
748 }
749  
750 # BodyRecipe 'none' with a caller-supplied BodyHash: croak unless the hash
751 # equals the body hash in the previous message's top Message-Instance, for
752 # every algorithm both carry (and at least one).
753 2 ▶sub _check_body_unchanged {
Subroutine _check_body_unchanged: called CC=5 SCAR=16.2
754 2 my ($previous, $body_hash, $algs) = @_;
755 2 ▶ my %map = map { (extract_mi_version($_) // 0) => $_ }
Condition50%1/2
extract_mi_version($_) // 0
l!l
20
MC/DC0%0/1
extract_mi_version($_) // 0
extract_mi_version($_)
Truth table50%1/2
A
A= extract_mi_version($_)
Aresult
11
00
756 $previous->header_raw('Message-Instance');
757 2 my $top = __PACKAGE__->parse($map{ max(keys %map) });
758 2 my @common = grep { $top->{bits}{hashes}{$_} } @$algs;
759 2 ▶ croak "BodyRecipe 'none' with BodyHash: the previous instance has no "
Branch: 1 branch
BranchTrueFalseTotal
unless @common 0 2 2
760 . join('/', @$algs) . " body hash to compare" unless @common;
761 2 for my $alg (@common) {
762 croak "BodyRecipe 'none' with BodyHash: the body hash is not the "
763 . "previous instance's, so the body changed"
764 2 ▶ unless $body_hash->{$alg} eq $top->{bits}{hashes}{$alg}[1];
Branch: 1 branch
BranchTrueFalseTotal
unless $body_hash->{$alg} eq $top->{"bits"}{"hashes"}{$alg}[1] 1 1 2
765 }
766 }
767  
768 # --- Calculate ---
769  
770 834 ▶sub calculate {
Subroutine calculate: called CC=78 SCAR=44.1
Pod documented
771 834 my ($class, $current, $previous, %opts) = @_;
772 834 Mail::DKIM2::Util::check_options("$class->calculate", \%opts,
773 qw(Algs BodyHash BodyRecipe IgnorePrefixes MaxRecipeLiterals));
774 831 ▶ croak "need a message" unless $current;
Branch: 1 branch
BranchTrueFalseTotal
unless $current 0 831 831
775  
776 831 my $self = bless {}, $class;
777 831 my $prefixes = check_ignore_prefixes($opts{IgnorePrefixes});
778  
779 # -09 §3.1: the signer chooses one or more hash algorithms; default
780 # is sha256 only (the signer default MUST NOT change).
781 830 ▶ $self->{algs} = ($opts{Algs} && @{$opts{Algs}}) ? [ @{$opts{Algs}} ] : ['sha256'];
Branch: 1 branch
BranchTrueFalseTotal
$opts{'Algs'} && @{$opts{'Algs'};} ? : 23 807 830
Condition66%2/3
$opts{"Algs"} and @{$opts{"Algs"};}
!ll&&!rl&&r
807023
MC/DC50%1/2
$opts{"Algs"} and @{$opts{"Algs"};}
$opts{"Algs"} @{$opts{"Algs"};}
Truth table66%2/3
A and B
A= $opts{"Algs"}B= @{$opts{"Algs"};}
ABresult
0X0
100
111
782  
783 # BodyHash: the caller hashed the body (body_digest_raw), so $current
784 # may be the header block alone. Only where nothing here reads or
785 # changes the body: m=1, or a caller-supplied BodyRecipe.
786 croak "BodyRecipe needs a previous message"
787 830 ▶ if exists $opts{BodyRecipe} && !$previous;
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"BodyRecipe"} and not $previous 1 829 830
Condition100%3/3
exists $opts{"BodyRecipe"} and not $previous
!ll&&!rl&&r
790391
MC/DC100%2/2
exists $opts{"BodyRecipe"} and not $previous
exists $opts{"BodyRecipe"} not $previous
Truth table100%3/3
A and not(B)
A= exists $opts{"BodyRecipe"}B= not $previous
ABresult
0X0
100
111
788  
789 # The literal-line cap on a diff body Recipe: over it, a null body Recipe.
790 croak "MaxRecipeLiterals must be a non-negative integer"
791 if exists $opts{MaxRecipeLiterals}
792 829 ▶ && !(defined $opts{MaxRecipeLiterals} && $opts{MaxRecipeLiterals} =~ /\A[0-9]+\z/);
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"MaxRecipeLiterals"} and not defined $opts{"MaxRecipeLiterals"} && $opts{"MaxRecipeLiterals"} =~ /\A[0-9]+\z/ 3 826 829
Condition100%6/6
exists $opts{"MaxRecipeLiterals"} and not defined $opts{"MaxRecipeLiterals"} && $opts{"MaxRecipeLiterals"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
812143
defined $opts{'MaxRecipeLiterals'} && $opts{'MaxRecipeLiterals'} =~ /\A[0-9]+\z/
!ll&&!rl&&r
1214
MC/DC100%3/3
exists $opts{"MaxRecipeLiterals"} and not defined $opts{"MaxRecipeLiterals"} && $opts{"MaxRecipeLiterals"} =~ /\A[0-9]+\z/
exists $opts{"MaxRecipeLiterals"} defined $opts{'MaxRecipeLiterals'} $opts{'MaxRecipeLiterals'} =~ /\A[0-9]+\z/
Truth table100%4/4
A and not(B && C)
A= exists $opts{"MaxRecipeLiterals"}B= defined $opts{'MaxRecipeLiterals'}C= $opts{'MaxRecipeLiterals'} =~ /\A[0-9]+\z/
ABCresult
0XX0
1110
10X1
1101
793  
794 826 my $body_hash;
795 826 ▶ if (exists $opts{BodyHash}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"BodyHash"}) 21 805 826
796 21 my $bh = $opts{BodyHash};
797 21 ▶ $bh = { sha256 => $bh } if defined $bh && !ref $bh;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bh and not ref $bh 14 7 21
Condition66%2/3
defined $bh and not ref $bh
!ll&&!rl&&r
0714
MC/DC50%1/2
defined $bh and not ref $bh
defined $bh not ref $bh
Truth table66%2/3
A and not(B)
A= defined $bhB= not ref $bh
ABresult
0X0
100
111
798 21 ▶ croak "BodyHash must be a base64 string or a hashref of algorithm => base64"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $bh eq "HASH" 1 20 21
799 unless ref $bh eq 'HASH';
800 20 for my $alg (@{$self->{algs}}) {
801 24 ▶ croak "BodyHash has no $alg hash" unless defined $bh->{$alg};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bh->{$alg} 2 22 24
802 }
803 # Each value goes into the h= tag verbatim: it must be the base64
804 # of a digest of that algorithm's length, nothing else.
805 18 for my $alg (sort keys %$bh) {
806 21 ▶ my $fn = $HASH_ALGS{$alg}
Branch: 1 branch
BranchTrueFalseTotal
my $fn = $HASH_ALGS{$alg} or croak("BodyHash: unsupported hash algorithm $alg") 20 1 21
807 or croak "BodyHash: unsupported hash algorithm $alg";
808 20 my $v = $bh->{$alg};
809 20 ▶ croak "BodyHash $alg is not a $alg digest in base64"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and not ref $v and $v =~ m[\A[A-Za-z0-9+/]+={0,2}\z] and length &decode_base64($v) == length &$fn("") 4 16 20
Condition66%6/9
defined $v and not ref $v and $v =~ m[\A[A-Za-z0-9+/]+={0,2}\z] and length &decode_base64($v) == length &$fn("")
!ll&&!rl&&r
1316
defined $v and not ref $v and $v =~ m[\A[A-Za-z0-9+/]+={0,2}\z]
!ll&&!rl&&r
0119
defined $v and not ref $v
!ll&&!rl&&r
0020
MC/DC50%2/4
defined $v and not ref $v and $v =~ m[\A[A-Za-z0-9+/]+={0,2}\z] and length &decode_base64($v) == length &$fn("")
defined $v not ref $v $v =~ m[\A[A-Za-z0-9+/]+={0,2}\z] length &decode_base64($v) == length &$fn("")
Truth table60%3/5
A and not(B) and C and D
A= defined $vB= not ref $vC= $v =~ m[\A[A-Za-z0-9+/]+={0,2}\z]D= length &decode_base64($v) == length &$fn("")
ABCDresult
0XXX0
10XX0
110X0
11100
11111
810 unless defined $v && !ref $v
811 && $v =~ m{\A[A-Za-z0-9+/]+={0,2}\z}
812 && length(decode_base64($v)) == length($fn->(''));
813 }
814 croak "BodyHash needs BodyRecipe when there is a previous message"
815 13 ▶ if $previous && !exists $opts{BodyRecipe};
Branch: 1 branch
BranchTrueFalseTotal
if $previous and not exists $opts{"BodyRecipe"} 1 12 13
Condition100%3/3
$previous and not exists $opts{"BodyRecipe"}
!ll&&!rl&&r
481
MC/DC100%2/2
$previous and not exists $opts{"BodyRecipe"}
$previous not exists $opts{"BodyRecipe"}
Truth table100%3/3
A and not(B)
A= $previousB= not exists $opts{"BodyRecipe"}
ABresult
0X0
100
111
816 12 $body_hash = $bh;
817 # The header block must be complete: a string whose last field has
818 # no line break gets one (nothing reads the body here).
819 12 ▶ $current .= "\r\n"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $current or $current =~ /\n\z/ 1 11 12
Condition66%2/3
ref $current or $current =~ /\n\z/
l!l&&r!l&&!r
0111
MC/DC50%1/2
ref $current or $current =~ /\n\z/
ref $current $current =~ /\n\z/
Truth table66%2/3
A or B
A= ref $currentB= $current =~ /\n\z/
ABresult
1X1
011
000
820 if !ref $current && $current !~ /\n\z/;
821 }
822  
823 817 ▶ unless (ref($current) && $current->isa('Email::MIME')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $current and $current->isa("Email::MIME")) 101 716 817
Condition66%2/3
ref $current and $current->isa("Email::MIME")
!ll&&!rl&&r
1010716
MC/DC50%1/2
ref $current and $current->isa("Email::MIME")
ref $current $current->isa("Email::MIME")
Truth table66%2/3
A and B
A= ref $currentB= $current->isa("Email::MIME")
ABresult
0X0
100
111
824 101 $current = parse_mime($current);
825 }
826  
827 817 my $rb_recipe;
828  
829 817 ▶ if ($previous) {
Branch: 1 branch
BranchTrueFalseTotal
if ($previous) { } 299 518 817
830 299 ▶ unless (ref($previous) && $previous->isa('Email::MIME')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $previous and $previous->isa("Email::MIME")) 66 233 299
Condition66%2/3
ref $previous and $previous->isa("Email::MIME")
!ll&&!rl&&r
660233
MC/DC50%1/2
ref $previous and $previous->isa("Email::MIME")
ref $previous $previous->isa("Email::MIME")
Truth table66%2/3
A and B
A= ref $previousB= $previous->isa("Email::MIME")
ABresult
0X0
100
111
831 66 $previous = parse_mime($previous);
832 }
833  
834 299 my @mi_cur = $current->header_raw('Message-Instance');
835 299 my @mi_prev = $previous->header_raw('Message-Instance');
836 299 ▶ die "Message already has " . MAX_CHAIN_LENGTH . " instances\n"
Branch: 1 branch
BranchTrueFalseTotal
if @mi_cur >= 32 1 298 299
837 if @mi_cur >= MAX_CHAIN_LENGTH;
838 298 ▶ if (my $error = _chain_error($current)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = _chain_error($current)) 0 298 298
839 0 die "$error\n";
840 }
841 # No instances on either side is a first instance with Recipes
842 # (-09 section 12.1: changes made as the message enters DKIM2).
843 # Verify same message by checking MI headers match
844 # header_raw returns values only, so prepend the name for canonicalization
845 298 my $canon_cur = join(',', map { dkim2_canonicalize_header("Message-Instance: $_") } @mi_cur);
846 298 my $canon_prev = join(',', map { dkim2_canonicalize_header("Message-Instance: $_") } @mi_prev);
847 298 ▶ die "This isn't the same message" unless ($canon_cur eq $canon_prev);
Branch: 1 branch
BranchTrueFalseTotal
unless $canon_cur eq $canon_prev 0 298 298
848  
849 298 my %map = map { extract_mi_version($_) => $_ } @mi_cur;
850 298 ▶ $self->set_tag('m', (max(keys %map) // 0) + 1);
Condition100%2/2
&max(keys %map) // 0
l!l
28612
MC/DC100%1/1
&max(keys %map) // 0
&max(keys %map)
Truth table100%2/2
A
A= &max(keys %map)
Aresult
11
00
851  
852 298 ▶ if (exists $opts{BodyRecipe}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{'BodyRecipe'}) { } 31 267 298
853 # Caller supplies the body Recipe: no body diff runs.
854 31 my $br = $opts{BodyRecipe};
855 31 ▶ if (defined $br && !ref $br && $br eq 'none') {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $br and not ref $br and $br eq 'none') { } 4 27 31
elsif (defined $br and not ref $br and $br eq 'null') { } 9 18 27
elsif (ref $br eq 'ARRAY') { } 15 3 18
Condition100%6/6
defined $br and not ref $br and $br eq "none"
!ll&&!rl&&r
17104
defined $br and not ref $br
!ll&&!rl&&r
11614
MC/DC100%3/3
defined $br and not ref $br and $br eq "none"
defined $br not ref $br $br eq "none"
Truth table100%4/4
A and not(B) and C
A= defined $brB= not ref $brC= $br eq "none"
ABCresult
0XX0
10X0
1100
1111
856 4 $rb_recipe = undef;
857 # No b key declares the body unchanged: a caller-supplied
858 # BodyHash must then be the previous instance's body hash.
859 _check_body_unchanged($previous, $body_hash, $self->{algs})
860 4 ▶ if $body_hash;
Branch: 1 branch
BranchTrueFalseTotal
if $body_hash 2 2 4
861 ▶ } elsif (defined $br && !ref $br && $br eq 'null') {
Condition100%6/6
defined $br and not ref $br and $br eq "null"
!ll&&!rl&&r
1719
defined $br and not ref $br
!ll&&!rl&&r
11610
MC/DC100%3/3
defined $br and not ref $br and $br eq "null"
defined $br not ref $br $br eq "null"
Truth table100%4/4
A and not(B) and C
A= defined $brB= not ref $brC= $br eq "null"
ABCresult
0XX0
10X0
1100
1111
862 9 $self->set_null_body_recipe;
863 } elsif (ref $br eq 'ARRAY') {
864 15 my $last = 0;
865 15 for my $step (@$br) {
866 16 ▶ croak "BodyRecipe step is undefined" unless defined $step;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $step 1 15 16
867 15 ▶ unless (ref $step) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $step) 3 12 15
868 3 ▶ croak "BodyRecipe literal contains a line break"
Branch: 1 branch
BranchTrueFalseTotal
if $step =~ /[\r\n]/ 3 0 3
869 if $step =~ /[\r\n]/;
870 0 next;
871 }
872 12 ▶ croak "BodyRecipe step must be [from,to] or a string"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $step eq "ARRAY" and @$step == 2 0 12 12
Condition33%1/3
ref $step eq "ARRAY" and @$step == 2
!ll&&!rl&&r
0012
MC/DC0%0/2
ref $step eq "ARRAY" and @$step == 2
ref $step eq "ARRAY" @$step == 2
Truth table33%1/3
A and B
A= ref $step eq "ARRAY"B= @$step == 2
ABresult
0X0
100
111
873 unless ref $step eq 'ARRAY' && @$step == 2;
874 12 my ($f, $t) = @$step;
875 12 ▶ croak "BodyRecipe range [$f,$t] invalid"
Branch: 1 branch
BranchTrueFalseTotal
unless $f =~ /^\d+\z/ and $t =~ /^\d+\z/ and $f >= 1 and $t >= $f and $f > $last 3 9 12
Condition75%9/12
$f =~ /^\d+\z/ and $t =~ /^\d+\z/ and $f >= 1 and $t >= $f and $f > $last
!ll&&!rl&&r
219
$f =~ /^\d+\z/ and $t =~ /^\d+\z/ and $f >= 1 and $t >= $f
!ll&&!rl&&r
1110
$f =~ /^\d+\z/ and $t =~ /^\d+\z/ and $f >= 1
!ll&&!rl&&r
0111
$f =~ /^\d+\z/ and $t =~ /^\d+\z/
!ll&&!rl&&r
0012
MC/DC60%3/5
$f =~ /^\d+\z/ and $t =~ /^\d+\z/ and $f >= 1 and $t >= $f and $f > $last
$f =~ /^\d+\z/ $t =~ /^\d+\z/ $f >= 1 $t >= $f $f > $last
Truth table66%4/6
A and B and C and D and E
A= $f =~ /^\d+\z/B= $t =~ /^\d+\z/C= $f >= 1D= $t >= $fE= $f > $last
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
876 unless $f =~ /^\d+\z/ && $t =~ /^\d+\z/
877 && $f >= 1 && $t >= $f && $f > $last;
878 9 $last = $t;
879 }
880 8 ▶ $rb_recipe = [ map { ref $_ ? [ @$_ ] : $_ } @$br ];
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 7 0 7
881 } else {
882 3 croak "BodyRecipe must be 'none', 'null' or an ARRAY ref";
883 }
884 }
885 else {
886 # A diff Recipe. A body the diff cannot rebuild within
887 # MaxRecipeLiterals lines (default MAX_RECIPE_LITERALS) is
888 # declared unrecoverable.
889 $rb_recipe = _body_recipe($current->body_raw, $previous->body_raw,
890 267 $opts{MaxRecipeLiterals});
891 267 ▶ if (defined $rb_recipe && !ref $rb_recipe) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rb_recipe and not ref $rb_recipe) 5 262 267
Condition100%3/3
defined $rb_recipe and not ref $rb_recipe
!ll&&!rl&&r
522105
MC/DC100%2/2
defined $rb_recipe and not ref $rb_recipe
defined $rb_recipe not ref $rb_recipe
Truth table100%3/3
A and not(B)
A= defined $rb_recipeB= not ref $rb_recipe
ABresult
0X0
100
111
892 5 $rb_recipe = undef;
893 5 $self->set_null_body_recipe;
894 }
895 }
896 }
897 else {
898 518 ▶ die "Already has Message-Instance headers" if $current->header_raw('Message-Instance');
Branch: 1 branch
BranchTrueFalseTotal
if $current->header_raw("Message-Instance") 0 518 518
899 518 $self->set_tag('m', 1);
900 }
901  
902 # Hashes are always of the current (newest) version of the message,
903 # for every configured algorithm (-09 §9.3).
904 805 for my $alg (@{$self->{algs}}) {
905 $self->{bits}{hashes}{$alg} = [ h_digest($current, $alg, $prefixes),
906 812 ▶ $body_hash ? $body_hash->{$alg} : b_digest($current, $alg) ];
Branch: 1 branch
BranchTrueFalseTotal
$body_hash ? : 13 799 812
907 }
908  
909 # nothing more to calculate without a previous version
910 805 ▶ return $self unless $previous;
Branch: 1 branch
BranchTrueFalseTotal
unless $previous 518 287 805
911  
912 # The header difference.
913 # Names as hashing and undo group them (field_name: "Subject :" is
914 # "subject"), so each Recipe key names the fields it is undone on.
915 287 my %all = map { Mail::DKIM2::Canon::field_name($_) => 1 }
916 ($current->header_names, $previous->header_names);
917 287 my %hdiff;
918 287 for my $h (sort keys %all) {
919 1949 ▶ next if should_skip($h, $prefixes);
Branch: 1 branch
BranchTrueFalseTotal
if should_skip($h, $prefixes) 586 1363 1949
920 1363 my @cur = reverse Mail::DKIM2::Canon::header_values($current, $h);
921 1363 my @prev = reverse Mail::DKIM2::Canon::header_values($previous, $h);
922 # Same number of instances AND the same values: zero instances and
923 # one empty instance both join to "", and removing an empty field
924 # (a bare "Bcc:") is still a change the Recipe must record.
925 next if @cur == @prev
926 1307 && join("\n", map { dkim2_canonicalize_header($_) } @cur)
927 1363 ▶ eq join("\n", map { dkim2_canonicalize_header($_) } @prev);
Branch: 1 branch
BranchTrueFalseTotal
if @cur == @prev and join("\n", map({dkim2_canonicalize_header($_);} @cur)) eq join("\n", map({dkim2_canonicalize_header($_);} @prev)) 1110 253 1363
Condition100%3/3
@cur == @prev and join("\n", map({dkim2_canonicalize_header($_);} @cur)) eq join("\n", map({dkim2_canonicalize_header($_);} @prev))
!ll&&!rl&&r
831701110
MC/DC100%2/2
@cur == @prev and join("\n", map({dkim2_canonicalize_header($_);} @cur)) eq join("\n", map({dkim2_canonicalize_header($_);} @prev))
@cur == @prev join("\n", map({dkim2_canonicalize_header($_);} @cur)) eq join("\n", map({dkim2_canonicalize_header($_);} @prev))
Truth table100%3/3
A and B
A= @cur == @prevB= join("\n", map({dkim2_canonicalize_header($_);} @cur)) eq join("\n", map({dkim2_canonicalize_header($_);} @prev))
ABresult
0X0
100
111
928 # A Recipe key is a header field name (-09 section 5): ftext. A
929 # field Email::Simple read under a name that is not one ("Y Bad:",
930 # a control character) cannot have its change recorded -- a verifier
931 # refuses the key -- so refuse to describe it rather than sign
932 # mail that no verifier accepts.
933 253 ▶ die "cannot record a change to the field \"$h\": not a header field name\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $h =~ /\A[\x21-\x39\x3B-\x7E]+\z/ 3 250 253
934 unless $h =~ /\A[\x21-\x39\x3B-\x7E]+\z/;
935 # headers are indexed from 1 from the bottom up
936 250 my %known;
937 250 push @{ $known{dkim2_canonicalize_header($cur[$_])} }, $_ + 1 for 0..$#cur;
938 # Recipe: reconstruct @prev from @cur. Copy ranges must ascend (each
939 # starts after the last one ends, -09 §5.1), so each field of
940 # @cur is copied at most once and never out of turn: a repeat, or a
941 # field the hop moved above one it left alone, goes in literally.
942 # $last_end only grows, so each value's ascending index list is
943 # consumed through a cursor that never moves back: linear overall.
944 # (A grep over the whole list per field made N repeated fields cost
945 # N^2 -- follow-up review F1.)
946 250 my $last_end = 0;
947 250 my %cursor;
948 my @res = map {
949 250 my $canon = dkim2_canonicalize_header($_);
950 211 ▶ my $list = $known{$canon} || [];
Condition100%2/2
$known{$canon} || []
l!l
12199
MC/DC100%1/1
$known{$canon} || []
$known{$canon}
Truth table100%2/2
A
A= $known{$canon}
Aresult
11
00
951 211 ▶ my $c = \($cursor{$canon} //= 0);
Condition100%2/2
$cursor{$canon} //= 0
l!l
3208
MC/DC100%1/1
$cursor{$canon} //= 0
$cursor{$canon}
Truth table100%2/2
A
A= $cursor{$canon}
Aresult
11
00
952 211 ▶ $$c++ while $$c < @$list && $list->[$$c] <= $last_end;
Branch: 1 branch
BranchTrueFalseTotal
$$c < @$list and $$list[$$c] <= $last_end and do { ++$$c } 5 211 216
Condition100%3/3
$$c < @$list and $$list[$$c] <= $last_end
!ll&&!rl&&r
20385
MC/DC100%2/2
$$c < @$list and $$list[$$c] <= $last_end
$$c < @$list $$list[$$c] <= $last_end
Truth table100%3/3
A and B
A= $$c < @$listB= $$list[$$c] <= $last_end
ABresult
0X0
100
111
953 211 my $idx = $list->[$$c];
954 211 ▶ $idx ? [$idx, $last_end = $idx] : $_
Branch: 1 branch
BranchTrueFalseTotal
$idx ? : 8 203 211
955 } @prev;
956 # combine adjacent ranges
957 250 for (1..$#res) {
958 7 ▶ next unless (ref $res[$_] && ref $res[$_-1]);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $res[$_] and ref $res[$_ - 1] 5 2 7
Condition66%2/3
ref $res[$_] and ref $res[$_ - 1]
!ll&&!rl&&r
502
MC/DC50%1/2
ref $res[$_] and ref $res[$_ - 1]
ref $res[$_] ref $res[$_ - 1]
Truth table66%2/3
A and B
A= ref $res[$_]B= ref $res[$_ - 1]
ABresult
0X0
100
111
959 2 ▶ next unless ($res[$_][0] == $res[$_-1][1] + 1);
Branch: 1 branch
BranchTrueFalseTotal
unless $res[$_][0] == $res[$_ - 1][1] + 1 0 2 2
960 2 $res[$_][0] = $res[$_-1][0];
961 2 $res[$_-1] = undef;
962 }
963 250 my @vals = grep { defined } @res;
964 250 $hdiff{$h} = \@vals;
965 }
966  
967 284 ▶ if ($rb_recipe) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rb_recipe) 218 66 284
968 218 $self->set_tag('rb', $rb_recipe);
969 }
970 284 ▶ if (keys %hdiff) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %hdiff) 183 101 284
971 183 $self->set_tag('rh', \%hdiff);
972 }
973  
974 284 return $self;
975 }
976  
977 # --- First instance over earlier unsigned ones ---
978  
979 14 ▶sub calculate_first {
Subroutine calculate_first: called CC=13 SCAR=26.5
Pod documented
980 14 my ($class, $current, $previous, %opts) = @_;
981 14 Mail::DKIM2::Util::check_options("$class->calculate_first", \%opts,
982 qw(Algs IgnorePrefixes MaxRecipeLiterals));
983 12 ▶ croak "need a message" unless $current;
Branch: 1 branch
BranchTrueFalseTotal
unless $current 0 12 12
984 12 ▶ croak "need a previous message" unless $previous;
Branch: 1 branch
BranchTrueFalseTotal
unless $previous 0 12 12
985  
986 12 ▶ $current = parse_mime($current) unless ref($current) && $current->isa('Email::MIME');
Branch: 1 branch
BranchTrueFalseTotal
unless ref $current and $current->isa("Email::MIME") 12 0 12
Condition33%1/3
ref $current and $current->isa("Email::MIME")
!ll&&!rl&&r
1200
MC/DC0%0/2
ref $current and $current->isa("Email::MIME")
ref $current $current->isa("Email::MIME")
Truth table33%1/3
A and B
A= ref $currentB= $current->isa("Email::MIME")
ABresult
0X0
100
111
987 # undo() (and so chain_verifies) rewrites the message it is given: work
988 # on copies of $previous.
989 12 ▶ my $prev_raw = ref($previous) ? $previous->as_string : $previous;
Branch: 1 branch
BranchTrueFalseTotal
ref $previous ? : 0 12 12
990 12 $previous = parse_mime($prev_raw);
991  
992 # Only a chain that undoes cleanly says what the message was before it.
993 my ($ok, $why) = $class->chain_verifies($prev_raw,
994 12 ▶ (exists $opts{IgnorePrefixes} ? (IgnorePrefixes => $opts{IgnorePrefixes}) : ()));
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'IgnorePrefixes'} ? : 5 7 12
995 12 ▶ die(($why // 'Message-Instance chain does not verify') . "\n") unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 1 11 12
Condition50%1/2
$why // "Message-Instance chain does not verify"
l!l
10
MC/DC0%0/1
$why // "Message-Instance chain does not verify"
$why
Truth table50%1/2
A
A= $why
Aresult
11
00
996  
997 # Undo every instance, m=1 included (its own Recipes, if any). Past a
998 # null body Recipe the earlier body is gone: header Recipes only, and
999 # the new instance declares the body unrecoverable.
1000 11 my $lost = 0;
1001 11 ▶ while (my @mi = $previous->header_raw('Message-Instance')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@mi) = $previous->header_raw("Message-Instance")) 18 11 29
1002 18 ▶ my %by_v = map { (extract_mi_version($_) // 0) => $_ } @mi;
Condition50%1/2
extract_mi_version($_) // 0
l!l
250
MC/DC0%0/1
extract_mi_version($_) // 0
extract_mi_version($_)
Truth table50%1/2
A
A= extract_mi_version($_)
Aresult
11
00
1003 18 ▶ $lost = 1 if $class->parse($by_v{ max(keys %by_v) })->unrecoverable;
Branch: 1 branch
BranchTrueFalseTotal
if $class->parse($by_v{&max(keys %by_v)})->unrecoverable 2 16 18
1004 18 $previous = $class->undo($previous, HeadersOnly => $lost);
1005 }
1006 11 $current->header_set('Message-Instance');
1007  
1008 11 ▶ return $class->calculate($current, $previous, %opts,
Branch: 1 branch
BranchTrueFalseTotal
$lost ? : 2 9 11
1009 ($lost ? (BodyRecipe => 'null') : ()));
1010 }
1011  
1012 # --- Verify ---
1013  
1014 436 ▶sub verify {
Subroutine verify: called CC=15 SCAR=27.5
Pod documented
1015 436 my ($class, $msg, %opts) = @_;
1016 436 Mail::DKIM2::Util::check_options("$class->verify", \%opts,
1017 qw(HeadersOnly IgnorePrefixes BodyHashes));
1018 435 ▶ croak "need a message" unless $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless $msg 0 435 435
1019 435 check_ignore_prefixes($opts{IgnorePrefixes});
1020  
1021 434 ▶ unless (ref($msg) && $msg->isa('Email::MIME')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $msg and $msg->isa("Email::MIME")) 11 423 434
Condition66%2/3
ref $msg and $msg->isa("Email::MIME")
!ll&&!rl&&r
110423
MC/DC50%1/2
ref $msg and $msg->isa("Email::MIME")
ref $msg $msg->isa("Email::MIME")
Truth table66%2/3
A and B
A= ref $msgB= $msg->isa("Email::MIME")
ABresult
0X0
100
111
1022 11 $msg = parse_mime($msg);
1023 }
1024  
1025 434 ▶ if (my $error = _chain_error($msg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = _chain_error($msg)) 8 426 434
1026 8 ▶ return wantarray ? (0, $error) : 0;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 6 8
1027 }
1028  
1029 426 my %map = map { extract_mi_version($_) => $_ } $msg->header_raw('Message-Instance');
1030 426 ▶ my $num = keys %map ? max(keys %map) : 0;
Branch: 1 branch
BranchTrueFalseTotal
keys %map ? : 425 1 426
1031 426 ▶ return 0 unless $num;
Branch: 1 branch
BranchTrueFalseTotal
unless $num 1 425 426
1032  
1033 # A crafted instance (duplicate algorithm, bad hash set, unparseable
1034 # Recipe) is a verdict, not an exception: this is the status-returning
1035 # half of the contract, and a host must not have to eval it.
1036 425 my $self = eval { $class->parse($map{$num}) };
1037 425 ▶ unless ($self) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self) 64 361 425
1038 64 ▶ die $@ if ref $@;
Branch: 1 branch
BranchTrueFalseTotal
if ref $@ 0 64 64
1039 64 my $err = _parse_error($@);
1040 64 ▶ return wantarray ? (0, $err) : 0;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 64 0 64
1041 }
1042  
1043 my ($ok, $err) = $self->_check_hashes($num,
1044 360 ▶ sub { h_digest($msg, $_[0], $opts{IgnorePrefixes}) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1045 # HeadersOnly: below a null body Recipe the body this instance
1046 # hashed is gone; its header hashes are still checkable.
1047 # BodyHashes: computed already (Mail::DKIM2::BodyPlan), from a body
1048 # $msg does not carry.
1049 $opts{HeadersOnly} ? undef
1050 0 ▶ : $opts{BodyHashes} ? sub { $opts{BodyHashes}{$_[0]} // '' }
Subroutine __ANON__: not called CC=2 SCAR=17.9
Condition0%0/2
$opts{"BodyHashes"}{$_[0]} // ""
l!l
00
MC/DC0%0/1
$opts{"BodyHashes"}{$_[0]} // ""
$opts{"BodyHashes"}{$_[0]}
Truth table0%0/2
A
A= $opts{"BodyHashes"}{$_[0]}
Aresult
11
00
1051 361 ▶ : sub { b_digest($msg, $_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 2 branches
BranchTrueFalseTotal
$opts{'HeadersOnly'} ? : 14 347 361
$opts{'BodyHashes'} ? : 0 347 347
1052 361 ▶ return wantarray ? (0, $err) : 0 unless $ok;
Branch: 2 branches
BranchTrueFalseTotal
unless $ok 86 275 361
wantarray ? : 47 39 86
1053 275 return $num;
1054 }
1055  
1056 # A parse() failure in the words verify() reports it.
1057 208 ▶sub _parse_error {
Subroutine _parse_error: called CC=1 SCAR=0.0
1058 208 my ($err) = @_;
1059 208 $err =~ s/\s+at\s+\S+\s+line\s+\d+\.?\s*\z//;
1060 208 $err =~ s/\s+\z//;
1061 208 return $err;
1062 }
1063  
1064 # Instance $num's hash-sets against the header and body hashes the two
1065 # callbacks give for an algorithm ($body undef: headers only, when the body
1066 # is gone -- below a null body Recipe, or a DSN without it, -09 §16.4 -- and
1067 # a set passes on its header hash). Returns 1, or (0, $reason).
1068 #
1069 # -09 §14.7: each set passes if its hashes match, fails if one does not, and
1070 # is a PERMERROR if this verifier does not implement its algorithm; the
1071 # "," lists and "|" groups combine as Common::combine_sets says (D4). A set
1072 # reports its header hash before its body hash; sets go in h= order.
1073 1436 ▶sub _check_hashes {
Subroutine _check_hashes: called CC=13 SCAR=27.0
1074 1436 my ($self, $num, $header, $body) = @_;
1075  
1076 1436 ▶ my $hashes = $self->get_tag('hashes') || {};
Condition50%1/2
$self->get_tag('hashes') || {}
l!l
14360
MC/DC0%0/1
$self->get_tag('hashes') || {}
$self->get_tag('hashes')
Truth table50%1/2
A
A= $self->get_tag('hashes')
Aresult
11
00
1077 1436 my $impl = hash_algs();
1078 # h= groups: as parsed, or the one list calculate() writes (its algs).
1079 my $groups = $self->{hash_groups}
1080 1436 ▶ || [ $self->{hash_order} || $self->{algs} || [ sort keys %$hashes ] ];
Condition14%1/7
$self->{'hash_groups'} || [$self->{'hash_order'} || $self->{'algs'} || [sort(keys %$hashes)]]
l!l
14360
$self->{'hash_order'} || $self->{'algs'} || [sort(keys %$hashes)]
l!l
00
$self->{"hash_order"} or $self->{"algs"}
l!l&&r!l&&!r
000
MC/DC0%0/1
$self->{'hash_groups'} || [$self->{'hash_order'} || $self->{'algs'} || [sort(keys %$hashes)]]
$self->{'hash_groups'}
MC/DC0%0/2
$self->{'hash_order'} || $self->{'algs'} || [sort(keys %$hashes)]
$self->{"hash_order"} $self->{"algs"}
Truth table50%1/2
A
A= $self->{'hash_groups'}
Aresult
11
00
Truth table0%0/3
A or B
A= $self->{"hash_order"}B= $self->{"algs"}
ABresult
1X1
011
000
1081 1436 my @results;
1082 1436 for my $group (@$groups) {
1083 1443 my @members;
1084 1443 for my $alg (@$group) {
1085 1451 my $pair = $hashes->{$alg};
1086 push @members,
1087 1451 ▶ !$impl->{$alg} || !$pair
Branch: 3 branches
BranchTrueFalseTotal
!($impl->{$alg} && $pair) ? : 9 1442 1451
$pair->[0] ne &$header($alg) ? : 134 1308 1442
$body && $pair->[1] ne &$body($alg) ? : 92 1216 1308
Condition83%5/6
$impl->{$alg} && $pair
!ll&&!rl&&r
901442
$body and $pair->[1] ne &$body($alg)
!ll&&!rl&&r
42117492
MC/DC50%1/2
$impl->{$alg} && $pair
$impl->{$alg} $pair
MC/DC100%2/2
$body and $pair->[1] ne &$body($alg)
$body $pair->[1] ne &$body($alg)
Truth table66%2/3
A && B
A= $impl->{$alg}B= $pair
ABresult
0X0
100
111
Truth table100%3/3
A and B
A= $bodyB= $pair->[1] ne &$body($alg)
ABresult
0X0
100
111
1088 ? ['permerror', "PERMERROR: Message-Instance m=$num algorithm $alg unknown"]
1089 : $pair->[0] ne $header->($alg)
1090 ? ['fail', "FAIL: Message-Instance m=$num header hash $alg mismatch"]
1091 : $body && $pair->[1] ne $body->($alg)
1092 ? ['fail', "FAIL: Message-Instance m=$num body hash $alg mismatch"]
1093 : ['pass'];
1094 }
1095 1443 push @results, \@members;
1096 }
1097 1436 my ($state, $why) = Mail::DKIM2::Common::combine_sets(\@results,
1098 "FAIL: Message-Instance m=$num no group of hashes passed");
1099 1436 ▶ return $state eq 'pass' ? 1 : (0, $why);
Branch: 1 branch
BranchTrueFalseTotal
$state eq 'pass' ? : 1211 225 1436
1100 }
1101  
1102 # --- Undo ---
1103  
1104 # Rebuild the previous lines from @$old by a Recipe of [from, to] copy ranges
1105 # (1-based, inclusive) and literal lines. Each range must lie within @$old,
1106 # and the ranges must ascend: each must start after the one before it ends
1107 # (-09 §5.1, and the same rule for the body). The previous version is
1108 # rebuilt from this one, and a hop's change never needs a line of it twice
1109 # or in a different order -- a reordering is recorded literally. Without the
1110 # check a few bytes of header could name a copy of billions of lines.
1111 # Everything is checked before anything is copied.
1112 #
1113 # A bound must be a JSON integer (-09 §5 schema): {"c":["1","2"]} is
1114 # malformed, and every verifier in the interop set rejects it. The JSON
1115 # decoder gives a number an IV and a string a PV, so the distinction is
1116 # read off the scalar's flags -- before anything stringifies it, which
1117 # would set POK on a genuine number too.
1118 13058 ▶sub _is_json_integer {
Subroutine _is_json_integer: called CC=5 SCAR=16.1
1119 13058 my ($v) = @_;
1120 13058 ▶ return 0 unless defined $v && !ref $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and not ref $v 8 13050 13058
Condition100%3/3
defined $v and not ref $v
!ll&&!rl&&r
4413050
MC/DC100%2/2
defined $v and not ref $v
defined $v not ref $v
Truth table100%3/3
A and not(B)
A= defined $vB= not ref $v
ABresult
0X0
100
111
1121 13050 my $flags = B::svref_2object(\$v)->FLAGS;
1122 13050 ▶ return ($flags & B::SVf_IOK) && !($flags & (B::SVf_POK | B::SVf_NOK)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$flags & 256 && !($flags & 1536) ? : 13033 17 13050
Condition66%2/3
$flags & 256 and not $flags & 1536
!ll&&!rl&&r
17013033
MC/DC50%1/2
$flags & 256 and not $flags & 1536
$flags & 256 not $flags & 1536
Truth table66%2/3
A and not(B)
A= $flags & 256B= not $flags & 1536
ABresult
0X0
100
111
1123 }
1124  
1125 # A JSON string, read off the flags the same way: a JSON number is not one.
1126 6681 ▶sub _is_json_string {
Subroutine _is_json_string: called CC=4 SCAR=14.9
1127 6681 my ($v) = @_;
1128 6681 ▶ return 0 unless defined $v && !ref $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and not ref $v 0 6681 6681
Condition33%1/3
defined $v and not ref $v
!ll&&!rl&&r
006681
MC/DC0%0/2
defined $v and not ref $v
defined $v not ref $v
Truth table33%1/3
A and not(B)
A= defined $vB= not ref $v
ABresult
0X0
100
111
1129 6681 ▶ return (B::svref_2object(\$v)->FLAGS & B::SVf_POK) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
B::svref_2object(\$v)->FLAGS & 1024 ? : 6673 8 6681
1130 }
1131  
1132 # Recipe structure: integer bounds, from <= to, ascending, non-overlapping.
1133 # $lines, when given, also bounds "to" by the old body/header; it is omitted
1134 # when the thing the Recipe applies to is gone (a body below a null body
1135 # Recipe), where the structure must still be valid.
1136 4087 ▶sub _check_recipe {
Subroutine _check_recipe: called CC=17 SCAR=38.6
1137 4087 my ($what, $recipe, $lines) = @_;
1138 4087 my $prev;
1139 4087 for my $cmd (grep { ref($_) eq 'ARRAY' } @$recipe) {
1140 3858 my ($from, $to) = @$cmd;
1141 3858 ▶ die "$what Recipe has a malformed copy range\n"
Branch: 1 branch
BranchTrueFalseTotal
unless @$cmd == 2 and _is_json_integer($from) and $from >= 0 and _is_json_integer($to) and $to >= 0 0 3858 3858
Condition33%4/12
@$cmd == 2 and _is_json_integer($from) and $from >= 0 and _is_json_integer($to) and $to >= 0
!ll&&!rl&&r
003858
@$cmd == 2 and _is_json_integer($from) and $from >= 0 and _is_json_integer($to)
!ll&&!rl&&r
003858
@$cmd == 2 and _is_json_integer($from) and $from >= 0
!ll&&!rl&&r
003858
@$cmd == 2 and _is_json_integer($from)
!ll&&!rl&&r
003858
MC/DC0%0/5
@$cmd == 2 and _is_json_integer($from) and $from >= 0 and _is_json_integer($to) and $to >= 0
@$cmd == 2 _is_json_integer($from) $from >= 0 _is_json_integer($to) $to >= 0
Truth table16%1/6
A and B and C and D and E
A= @$cmd == 2B= _is_json_integer($from)C= $from >= 0D= _is_json_integer($to)E= $to >= 0
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
1142 unless @$cmd == 2
1143 && _is_json_integer($from) && $from >= 0
1144 && _is_json_integer($to) && $to >= 0;
1145 3858 ▶ unless (1 <= $from && $from <= $to && (!defined $lines || $to <= $lines)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (1 <= $from and $from <= $to and !defined($lines) || $to <= $lines) 27 3831 3858
Condition66%6/9
1 <= $from and $from <= $to and !defined($lines) || $to <= $lines
!ll&&!rl&&r
0273831
1 <= $from and $from <= $to
!ll&&!rl&&r
003858
not defined $lines or $to <= $lines
l!l&&r!l&&!r
1822200927
MC/DC50%2/4
1 <= $from and $from <= $to and !defined($lines) || $to <= $lines
1 <= $from $from <= $to not defined $lines $to <= $lines
Truth table60%3/5
A and B and not(C) or D
A= 1 <= $fromB= $from <= $toC= not defined $linesD= $to <= $lines
ABCDresult
0XXX0
10XX0
11000
111X1
11011
1146 # No line count (structure-only check below a null body Recipe).
1147 27 ▶ die "$what Recipe has an invalid copy range $from-$to\n" unless defined $lines;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lines 0 27 27
1148 27 die "$what Recipe copies lines $from-$to of $lines\n";
1149 }
1150 3831 ▶ if ($prev && $from <= $prev->[1]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prev and $from <= $prev->[1]) 0 3831 3831
Condition66%2/3
$prev and $from <= $prev->[1]
!ll&&!rl&&r
209617350
MC/DC0%0/2
$prev and $from <= $prev->[1]
$prev $from <= $prev->[1]
Truth table66%2/3
A and B
A= $prevB= $from <= $prev->[1]
ABresult
0X0
100
111
1151 0 ▶ if ($to >= $prev->[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($to >= $prev->[0]) 0 0 0
1152 0 ▶ my $lo = $from > $prev->[0] ? $from : $prev->[0];
Branch: 1 branch
BranchTrueFalseTotal
$from > $prev->[0] ? : 0 0 0
1153 0 ▶ my $hi = $to < $prev->[1] ? $to : $prev->[1];
Branch: 1 branch
BranchTrueFalseTotal
$to < $prev->[1] ? : 0 0 0
1154 0 die "$what Recipe copies lines $lo-$hi twice\n";
1155 }
1156 0 die "$what Recipe copies lines $from-$to out of order\n";
1157 }
1158 3831 $prev = [$from, $to];
1159 }
1160 4060 return;
1161 }
1162  
1163 507 ▶sub _apply_recipe {
Subroutine _apply_recipe: called CC=2 SCAR=6.9
1164 507 my ($what, $recipe, $old) = @_;
1165 507 _check_recipe($what, $recipe, scalar @$old);
1166  
1167 return map {
1168 492 ▶ ref($_) eq 'ARRAY' ? @$old[$_->[0] - 1 .. $_->[1] - 1] : $_
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 322 1781 2103
1169 } @$recipe;
1170 }
1171  
1172 # Set a message's body to exactly these octets. Email::MIME->body_set encodes
1173 # what it is given according to the Content-Transfer-Encoding header, so on a
1174 # base64 or quoted-printable part the rebuilt previous body -- already in its
1175 # wire encoding, since Recipes work on wire lines -- came back encoded twice,
1176 # and every base64/QP message a list re-encoded failed its m=1 hash on undo
1177 # (2026-10-04: 17 of 88 corpus samples through Mailman; the milter refused to
1178 # sign them). This is Email::MIME::body_set without the encoding step.
1179 134 ▶sub _body_raw_set {
Subroutine _body_raw_set: called CC=1 SCAR=0.0
1180 134 my ($msg, $raw) = @_;
1181 134 $msg->{body_raw} = $raw;
1182 134 $msg->Email::Simple::body_set($raw);
1183 134 return;
1184 }
1185  
1186 336 ▶sub undo {
Subroutine undo: called CC=16 SCAR=27.8
Pod documented
1187 336 my ($class, $msg, %opts) = @_;
1188 336 Mail::DKIM2::Util::check_options("$class->undo", \%opts, qw(HeadersOnly));
1189 335 ▶ croak "need a message" unless $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless $msg 0 335 335
1190  
1191 335 ▶ unless (ref($msg) && $msg->isa('Email::MIME')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $msg and $msg->isa("Email::MIME")) 43 292 335
Condition66%2/3
ref $msg and $msg->isa("Email::MIME")
!ll&&!rl&&r
430292
MC/DC50%1/2
ref $msg and $msg->isa("Email::MIME")
ref $msg $msg->isa("Email::MIME")
Truth table66%2/3
A and B
A= ref $msgB= $msg->isa("Email::MIME")
ABresult
0X0
100
111
1192 43 $msg = parse_mime($msg);
1193 }
1194  
1195 335 ▶ if (my $error = _chain_error($msg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = _chain_error($msg)) 2 333 335
1196 2 die "$error\n";
1197 }
1198  
1199 333 my %map = map { extract_mi_version($_) => $_ } $msg->header_raw('Message-Instance');
1200 333 ▶ my $num = keys %map ? max(keys %map) : 0;
Branch: 1 branch
BranchTrueFalseTotal
keys %map ? : 333 0 333
1201 333 ▶ return unless $num;
Branch: 1 branch
BranchTrueFalseTotal
unless $num 0 333 333
1202  
1203 333 ▶ $msg->header_obj->header_filter('Message-Instance', sub { extract_mi_version(shift) < $num });
Subroutine __ANON__: called CC=1 SCAR=0.0
1204  
1205 333 my $self = $class->parse($map{$num});
1206  
1207 302 my $rb = $self->get_tag('rb');
1208 302 my $rh = $self->get_tag('rh');
1209  
1210 302 ▶ if ($rb && !$opts{HeadersOnly}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($rb and not $opts{'HeadersOnly'}) { } 142 160 302
elsif ($rb) { } 2 158 160
Condition100%3/3
$rb and not $opts{"HeadersOnly"}
!ll&&!rl&&r
1582142
MC/DC100%2/2
$rb and not $opts{"HeadersOnly"}
$rb not $opts{"HeadersOnly"}
Truth table100%3/3
A and not(B)
A= $rbB= not $opts{"HeadersOnly"}
ABresult
0X0
100
111
1211 # Every line, trailing blank ones too: they are not hashed (§6.1),
1212 # but a Recipe may number and copy them, as the other
1213 # implementations in the interop set allow. Only the empty piece
1214 # after the last line break is not a line.
1215 142 my @old = split /\r?\n/, $msg->body_raw, -1;
1216 142 ▶ pop @old if @old && $old[-1] eq '';
Branch: 1 branch
BranchTrueFalseTotal
if @old and $old[-1] eq "" 139 3 142
Condition100%3/3
@old and $old[-1] eq ""
!ll&&!rl&&r
21139
MC/DC100%2/2
@old and $old[-1] eq ""
@old $old[-1] eq ""
Truth table100%3/3
A and B
A= @oldB= $old[-1] eq ""
ABresult
0X0
100
111
1217 142 my @new = _apply_recipe('body', $rb, \@old);
1218 134 _body_raw_set($msg, join("\r\n", @new, ''));
1219 } elsif ($rb) {
1220 # The body is not rebuilt, but the Recipe must still be well formed.
1221 2 _check_recipe('body', $rb);
1222 }
1223  
1224 294 ▶ if ($rh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rh) 149 145 294
1225 149 for my $h (sort keys %$rh) {
1226 358 my $v = $rh->{$h};
1227 358 ▶ next unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 358 358
1228 # Message-Instance and DKIM2-Signature fields are not content (-09
1229 # section 6.2): a Recipe naming one acts on content fields of that
1230 # name, of which there are none, and what it rebuilds is not hashed.
1231 # Applying it to the received fields would let a hop rewrite the
1232 # instances below its own -- a forged history the walk then checks.
1233 358 ▶ if (Mail::DKIM2::Canon::field_name($h) =~ /\A(?:message-instance|dkim2-signature)\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (Mail::DKIM2::Canon::field_name($h) =~ /\A(?:message-instance|dkim2-signature)\z/) 5 353 358
1234 5 _apply_recipe("$h header", $v, []);
1235 3 next;
1236 }
1237 353 my @old = reverse Mail::DKIM2::Canon::header_values($msg, $h);
1238 353 my @new = _apply_recipe("$h header", $v, \@old);
1239 348 $msg->header_obj->header_set_reverse($h, @new);
1240 }
1241 }
1242  
1243 287 return $msg;
1244 }
1245  
1246 # Verify the WHOLE Message-Instance chain reverses cleanly: check the top
1247 # instance against the current content, then undo it and check the next one
1248 # down, until m=1; past an instance with a null body Recipe, header-only
1249 # (the body is gone but the header history is still checked). This is the
1250 # undo check a recipient performs — running it before signing catches an
1251 # upstream that emitted a non-reversible Recipe.
1252 # Returns (1, undef) on success or (0, reason) on the first failure.
1253 130 ▶sub chain_verifies {
Subroutine chain_verifies: called CC=16 SCAR=28.3
Pod documented
1254 130 my ($class, $msg, %opts) = @_;
1255 130 Mail::DKIM2::Util::check_options("$class->chain_verifies", \%opts,
1256 qw(IgnorePrefixes));
1257 129 check_ignore_prefixes($opts{IgnorePrefixes});
1258 129 ▶ unless (ref($msg) && $msg->isa('Email::MIME')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $msg and $msg->isa("Email::MIME")) 129 0 129
Condition33%1/3
ref $msg and $msg->isa("Email::MIME")
!ll&&!rl&&r
12900
MC/DC0%0/2
ref $msg and $msg->isa("Email::MIME")
ref $msg $msg->isa("Email::MIME")
Truth table33%1/3
A and B
A= ref $msgB= $msg->isa("Email::MIME")
ABresult
0X0
100
111
1259 129 $msg = parse_mime("$msg");
1260 }
1261 129 ▶ if (my $error = _chain_error($msg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = _chain_error($msg)) 5 124 129
1262 5 return (0, $error);
1263 }
1264 124 my $headers_only = 0;
1265 124 while (1) {
1266 207 my @mi = $msg->header_raw('Message-Instance');
1267 207 ▶ my %by_v = map { (extract_mi_version($_) // 0) => $_ } @mi;
Condition50%1/2
extract_mi_version($_) // 0
l!l
8250
MC/DC0%0/1
extract_mi_version($_) // 0
extract_mi_version($_)
Truth table50%1/2
A
A= extract_mi_version($_)
Aresult
11
00
1268 207 ▶ my $num = %by_v ? (sort { $b <=> $a } keys %by_v)[0] : 0;
Branch: 1 branch
BranchTrueFalseTotal
%by_v ? : 206 1 207
1269 207 ▶ last unless $num;
Branch: 1 branch
BranchTrueFalseTotal
unless $num 1 206 207
1270  
1271 206 my ($ok, $err) = $class->verify($msg, %opts, HeadersOnly => $headers_only);
1272 206 ▶ return (0, $err // "FAIL: Message-Instance m=$num header hash mismatch") unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 69 137 206
Condition50%1/2
$err // "FAIL: Message-Instance m=$num header hash mismatch"
l!l
690
MC/DC0%0/1
$err // "FAIL: Message-Instance m=$num header hash mismatch"
$err
Truth table50%1/2
A
A= $err
Aresult
11
00
1273  
1274 137 ▶ last if $num <= 1;
Branch: 1 branch
BranchTrueFalseTotal
if $num <= 1 51 86 137
1275 # A null body Recipe loses the previous body, not the header
1276 # history: from here down, undo header Recipes only and check each
1277 # instance's header hashes, down to m=1.
1278 86 ▶ $headers_only = 1 if $class->parse($by_v{$num})->unrecoverable;
Branch: 1 branch
BranchTrueFalseTotal
if $class->parse($by_v{$num})->unrecoverable 14 72 86
1279  
1280 86 my $prev = eval { $class->undo($msg, HeadersOnly => $headers_only) };
1281 86 ▶ die $@ if ref $@;
Branch: 1 branch
BranchTrueFalseTotal
if ref $@ 0 86 86
1282 # A bad step is already a verdict (parse: "Recipe <path> is
1283 # invalid", D6). A range past the lines it copies is found here, as
1284 # "contains invalid JSON"; a third value says which range, for a log.
1285 86 ▶ if ($@ || !$prev) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $prev) 3 83 86
Condition66%2/3
$@ or not $prev
l!l&&r!l&&!r
3083
MC/DC50%1/2
$@ or not $prev
$@ not $prev
Truth table66%2/3
A or not(B)
A= $@B= not $prev
ABresult
1X1
011
000
1286 3 ▶ (my $why = $@ // '') =~ s/\s+\z//;
Condition50%1/2
$@ // ""
l!l
30
MC/DC0%0/1
$@ // ""
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
1287 3 ▶ return (0, $why) if $why =~ /\A(?:PERMERROR|FAIL|TEMPERROR): /;
Branch: 1 branch
BranchTrueFalseTotal
if $why =~ /\A(?:PERMERROR|FAIL|TEMPERROR): / 0 3 3
1288 3 return (0, "PERMERROR: Message-Instance m=$num contains invalid JSON", $why);
1289 }
1290 83 $msg = $prev;
1291 }
1292 52 return (1, undef);
1293 }
1294  
1295  
1296 196 1;
1297  
1298 __END__
« lib/Mail/Milter/Authentication/Handler/DKIM2Sign.pm ↑ Summary lib/Mail/DKIM2/BodyPlan.pm »