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 212 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 212 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 212 our $VERSION = '0.35';
6  
7  
8 212 ▶use Mail::DKIM2::Fold ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 212 ▶use Mail::DKIM2::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 212 ▶use Mail::DKIM2::Digest;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 212 ▶use Email::MIME;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 212 ▶use MIME::Base64 qw(encode_base64 decode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 212 ▶use List::Util qw(max);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 212 ▶use B ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 212 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 212 ▶use Mail::DKIM2::TagValueList ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 212 ▶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 212 );
28 212 ▶use Mail::DKIM2::Canon qw(should_skip dkim2_canonicalize_header check_ignore_prefixes);
Subroutine BEGIN: called CC=1 SCAR=0.0
29 212 ▶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 1210 ▶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 1210 ▶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 ? : 3504 2 3506
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
931198
chain_length_error({"message-instance", scalar @mi, "dkim2-signature", $signatures}) // $unusable
l!l&&r!l&&!r
361201
(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 212 my $alg = $_;
61 6470 ▶ $alg => sub { Mail::DKIM2::Digest::digest_data($alg, $_[0]) };
Subroutine __ANON__: called CC=1 SCAR=0.0
62 } qw(sha256 sha512);
63  
64 4318 ▶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 4183 ▶sub parse_hash_groups {
Subroutine parse_hash_groups: called CC=7 SCAR=19.5
Pod documented
77 4183 my ($h_tag) = @_;
78 4183 ▶ 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 4180 3 4183
79 4180 my @out;
80 4180 for my $group (@$groups) {
81 4192 my @sets;
82 4192 for my $item (@$group) {
83 5519 ▶ 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 5518 1 5519
84 or return;
85 5518 $rest =~ s/[ \t\r\n]//g;
86 5518 my @hashes = split /:/, $rest, -1;
87 # Both are base64strings (§2.14), whatever the algorithm.
88 return unless @hashes == 2
89 5518 ▶ && !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 5513 5518
Condition100%3/3
@hashes == 2 and not grep({not Mail::DKIM2::Util::is_base64string($_);} @hashes)
!ll&&!rl&&r
325513
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 5513 push @sets, [$name, @hashes];
91 }
92 4186 push @out, \@sets;
93 }
94 4174 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 212 ▶BEGIN {
Subroutine BEGIN: called CC=3 SCAR=11.0
104 # function to replace headers from the bottom up
105 212 ▶ if (!Email::Simple::Header->can('header_set_reverse')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ("Email::Simple::Header"->can("header_set_reverse")) 212 0 212
106 351 ▶ *Email::Simple::Header::header_set_reverse = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
107 351 my $self = shift;
108 351 my $h = shift;
109 351 my @vals = @_;
110 351 my $headers = $self->{headers};
111 351 my $max = @$headers / 2 - 1;
112 # Names as DKIM2 compares them: "Subject :" is a Subject.
113 351 my $want = Mail::DKIM2::Canon::field_name($h);
114 351 for my $idx (map { $_ * 2 } reverse 0..$max) {
115 14167 ▶ 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 13817 350 14167
116 350 ▶ if (@vals) {
Branch: 1 branch
BranchTrueFalseTotal
if (@vals) { } 168 182 350
117 168 $headers->[$idx+1] = shift @vals;
118 } else {
119 182 splice(@$headers, $idx, 2);
120 }
121 }
122 351 unshift @$headers, ($h, $_) for @vals;
123 212 };
124 }
125  
126 # function to only keep headers that match an expression
127 212 ▶ if (!Email::Simple::Header->can('header_filter')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not "Email::Simple::Header"->can("header_filter")) 212 0 212
128 337 ▶ *Email::Simple::Header::header_filter = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
129 337 my $self = shift;
130 337 my $h = shift;
131 337 my $keep = shift;
132 337 my $headers = $self->{headers};
133 337 my $max = @$headers / 2 - 1;
134 337 for my $idx (map { $_ * 2 } reverse 0..$max) {
135 6328 ▶ next unless lc($headers->[$idx]) eq lc($h);
Branch: 1 branch
BranchTrueFalseTotal
unless lc $headers->[$idx] eq lc $h 5212 1116 6328
136 1116 ▶ next if $keep->($headers->[$idx+1]);
Branch: 1 branch
BranchTrueFalseTotal
if &$keep($$headers[$idx + 1]) 779 337 1116
137 337 splice(@$headers, $idx, 2);
138 }
139 212 };
140 }
141 }
142  
143 # --- Tag accessors ---
144  
145 1252 ▶sub set_tag {
Subroutine set_tag: called CC=1 SCAR=0.0
Pod documented
146 1252 my ($self, $k, $v) = @_;
147 1252 $self->{bits}{$k} = $v;
148 }
149  
150 18404 ▶sub get_tag {
Subroutine get_tag: called CC=1 SCAR=0.0
Pod documented
151 18404 my ($self, $k) = @_;
152 18404 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 212 ▶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 4744 ▶sub unrecoverable {
Subroutine unrecoverable: called CC=2 SCAR=6.9
Pod documented
231 4744 my ($self) = @_;
232 4744 ▶ return $self->{bits}{rb_null} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'bits'}{'rb_null'} ? : 224 4520 4744
233 }
234  
235 # --- Wire format: m=N; h=sha256:header_hash:body_hash; r=<b64json> ---
236  
237 831 ▶sub as_string {
Subroutine as_string: called CC=9 SCAR=22.0
Pod documented
238 831 my ($self) = @_;
239 831 my %data = %{$self->{bits}};
240 831 my $m = delete $data{m};
241 831 ▶ my $hashes = delete($data{hashes}) || {};
Condition50%1/2
delete $data{'hashes'} || {}
l!l
8310
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 831 ▶ my $groups = $self->{hash_groups} || [ $self->{algs} || ['sha256'] ];
Condition100%4/4
$self->{'hash_groups'} || [$self->{'algs'} || ['sha256']]
l!l
2829
$self->{'algs'} || ['sha256']
l!l
8281
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 831 join ',', map { "$_:$hashes->{$_}[0]:$hashes->{$_}[1]" } grep { $hashes->{$_} } @$_
250 } @$groups);
251  
252 # Build r= tag JSON if there are Recipes
253 831 my %recipe_json;
254 831 ▶ if (delete $data{rb_null}) {
Branch: 2 branches
BranchTrueFalseTotal
if (delete $data{'rb_null'}) { } 65 766 831
elsif (exists $data{'rb'}) { } 174 592 766
255 65 $recipe_json{b} = undef; # encodes as JSON null
256 65 delete $data{rb};
257 } elsif (exists $data{rb}) {
258 174 $recipe_json{b} = _encode_recipe_list(delete $data{rb});
259 }
260 831 ▶ if (exists $data{rh}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data{"rh"}) 190 641 831
261 190 my $rh = delete $data{rh};
262 190 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 190 for my $h (sort keys %$rh) {
266 247 $encoded{lc $h} = _encode_recipe_list($rh->{$h});
267 }
268 190 $recipe_json{h} = \%encoded;
269 }
270  
271 831 ▶ if (keys %recipe_json) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %recipe_json) 294 537 831
272 294 $result .= "; r=" . encode_tag_json(\%recipe_json);
273 }
274 831 $result .= ";";
275  
276 831 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 102 ▶sub as_header {
Subroutine as_header: called CC=1 SCAR=0.0
Pod documented
284 102 my ($self) = @_;
285 102 return Mail::DKIM2::Fold::fold_header('Message-Instance: ' . $self->as_string);
286 }
287  
288 92 ▶sub as_header_value {
Subroutine as_header_value: called CC=1 SCAR=0.0
Pod documented
289 92 my ($self) = @_;
290 92 (my $value = $self->as_header) =~ s/\AMessage-Instance:[ \t]*//;
291 92 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 619 ▶sub changes {
Subroutine changes: called CC=4 SCAR=13.9
Pod documented
299 619 my ($self) = @_;
300 619 my $bits = $self->{bits};
301 return {
302 body => $bits->{rb_null} ? 'unrecoverable' : $bits->{rb} ? 'changed' : 'unchanged',
303 619 ▶ headers => [ sort map { Mail::DKIM2::Canon::field_name($_) } keys %{ $bits->{rh} || {} } ],
Branch: 2 branches
BranchTrueFalseTotal
$bits->{'rb_null'} ? : 36 583 619
$bits->{'rb'} ? : 444 139 583
Condition100%2/2
$bits->{'rh'} || {}
l!l
485134
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 616 ▶sub changes_header {
Subroutine changes_header: called CC=2 SCAR=6.9
Pod documented
309 616 my ($self, $name) = @_;
310 616 my $want = Mail::DKIM2::Canon::field_name($name);
311 616 ▶ return (grep { $_ eq $want } @{ $self->changes->{headers} }) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
grep({$_ eq $want;} @{$self->changes->{'headers'};}) ? : 165 451 616
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 422 ▶sub _encode_recipe_list {
Subroutine _encode_recipe_list: called CC=6 SCAR=17.9
327 422 my ($list) = @_;
328 422 my @encoded;
329 422 my $pending_kind = '';
330 422 my @pending;
331 866 ▶ my $flush = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
332 866 ▶ return unless @pending;
Branch: 1 branch
BranchTrueFalseTotal
unless @pending 631 235 866
333 235 push @encoded, { $pending_kind => [@pending] };
334 235 @pending = ();
335 422 };
336 422 for my $item (@$list) {
337 2064 ▶ if (ref $item eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $item eq 'ARRAY') { } 213 1851 2064
338 213 $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 213 push @encoded, { c => [ map { 0 + $_ } @$item ] };
344 } else {
345 1851 ▶ my $kind = Mail::DKIM2::RecipeJSON::is_utf8_octets($item) ? 'd' : 'u';
Branch: 1 branch
BranchTrueFalseTotal
Mail::DKIM2::RecipeJSON::is_utf8_octets($item) ? : 1800 51 1851
346 1851 ▶ $flush->() if $kind ne $pending_kind;
Branch: 1 branch
BranchTrueFalseTotal
if $kind ne $pending_kind 231 1620 1851
347 1851 $pending_kind = $kind;
348 1851 ▶ push @pending, $kind eq 'u' ? encode_base64($item, '') : $item;
Branch: 1 branch
BranchTrueFalseTotal
$kind eq 'u' ? : 51 1800 1851
349 }
350 }
351 422 $flush->();
352 422 return \@encoded;
353 }
354  
355 # --- Parsing ---
356  
357 4193 ▶sub parse {
Subroutine parse: called CC=36 SCAR=36.0
Pod documented
358 4193 my ($class, $header) = @_;
359 4193 ▶ my $self = bless {}, ref($class) || $class;
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
041930
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 4193 $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 4193 my ($pairs, $ok) = Mail::DKIM2::TagValueList::split_tag_list($header);
374 4193 my (%tags, $dup, $raw_h);
375 4193 for my $p (@$pairs) {
376 10710 my ($name, $val) = @$p;
377 10710 ▶ next if $name =~ /[A-Z]/;
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /[A-Z]/ 4 10706 10710
378 10706 ▶ $raw_h = $val if $name eq 'h';
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "h" 4193 6513 10706
379 10706 $val =~ s/\s//gs;
380 10706 ▶ $dup = 1 if exists $tags{$name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $tags{$name} 3 10703 10706
381 10706 $tags{$name} = $val;
382 }
383  
384 die "missing m= tag in Message-Instance header"
385 4193 ▶ unless exists $tags{m};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $tags{"m"} 0 4193 4193
386 4193 ▶ die "PERMERROR: Message-Instance m=$tags{m} syntax error\n" if $dup || !$ok;
Branch: 1 branch
BranchTrueFalseTotal
if $dup or not $ok 13 4180 4193
Condition100%3/3
$dup or not $ok
l!l&&r!l&&!r
3104180
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 4180 ▶ die "PERMERROR: Message-Instance m=$tags{m} tag=h missing\n" unless exists $tags{h};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $tags{"h"} 2 4178 4180
389 4178 $self->{bits}{m} = $tags{m};
390  
391 # -09 section 9.3: h= is a list of hash-sets
392 4178 ▶ if (exists $tags{h}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $tags{"h"}) 4178 0 4178
393 4178 ▶ 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] 4169 9 4178
394 or die "PERMERROR: Message-Instance m=$tags{m} syntax error\n";
395 4169 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 4169 my %seen;
403 4169 for my $s (@$sets) {
404 5505 ▶ if ($seen{$s->[0]}++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen{$s->[0]}++) 7 5498 5505
405 7 die "PERMERROR: Message-Instance m=$tags{m} has a duplicate hash algorithm\n";
406 }
407 }
408  
409 4162 for my $s (@$sets) {
410 5491 $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 4162 $self->{hash_order} = [ map { $_->[0] } @$sets ];
415 4162 $self->{hash_groups} = [ map { [ map { $_->[0] } @$_ ] } @$groups ];
416 }
417  
418 4162 ▶ if (exists $tags{r}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $tags{"r"}) 2315 1847 4162
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 2315 ▶ 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 2314 2315
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 2314 my $invalid = "PERMERROR: Message-Instance m=$tags{m} contains invalid JSON\n";
437 2314 ▶ my $bad = sub { "PERMERROR: Message-Instance m=$tags{m} recipe $_[0] is invalid\n" };
Subroutine __ANON__: called CC=1 SCAR=0.0
438 2314 my $recipe_data = eval { decode_tag_json($tags{r}) };
439 2314 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 34 2280 2314
440 34 ▶ die $@ if ref $@;
Branch: 1 branch
BranchTrueFalseTotal
if ref $@ 0 34 34
441 34 die $invalid;
442 }
443 2280 ▶ die $invalid unless ref $recipe_data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recipe_data eq "HASH" 0 2280 2280
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 2280 my %top = %$recipe_data;
448 2280 ▶ die $invalid unless exists $top{h} || exists $top{b};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $top{"h"} or exists $top{"b"} 2 2278 2280
Condition100%3/3
exists $top{"h"} or exists $top{"b"}
l!l&&r!l&&!r
107911992
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 2278 ▶ 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 2272 2278
Condition100%6/6
exists $top{"h"} and not ref $top{"h"} eq "HASH" && %{$top{"h"};}
!ll&&!rl&&r
119910736
ref $top{'h'} eq 'HASH' && %{$top{'h'};}
!ll&&!rl&&r
511073
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 2272 ▶ 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 2268 2272
Condition100%6/6
exists $top{"b"} and defined $top{"b"} and ref $top{"b"} ne "ARRAY"
!ll&&!rl&&r
60016684
exists $top{"b"} and defined $top{"b"}
!ll&&!rl&&r
3852151672
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 2268 ▶ if (exists $top{b}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $top{"b"}) 1883 385 2268
456 1883 ▶ if (ref $top{b} eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $top{'b'} eq 'ARRAY') { } 1668 215 1883
elsif (not defined $top{'b'}) { } 215 0 215
457 1668 $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 2099 ▶ if (exists $top{h}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $top{"h"}) 1073 1026 2099
465 # A non-empty object (minProperties 1); never null (section 5.1).
466 1073 ▶ die $invalid unless ref $top{h} eq 'HASH' && %{$top{h}};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $top{"h"} eq "HASH" and %{$top{"h"};} 0 1073 1073
Condition33%1/3
ref $top{"h"} eq "HASH" and %{$top{"h"};}
!ll&&!rl&&r
001073
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 1073 my %rh;
468 # Each key is a header field name (-09 section 5): ftext, so no
469 # WSP. "subject " is not a name, and name matching that drops
470 # WSP before a colon would take it for Subject where a stricter
471 # verifier does not: it is malformed, so that every verifier
472 # says the same.
473 1073 ▶ 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 1059 1073
474 1059 for my $h (sort keys %{$top{h}}) {
475 2869 $rh{$h} = _decode_recipe_list($top{h}{$h}, $bad, 'h.' . _path_name($h));
476 }
477 1023 $self->{bits}{rh} = \%rh;
478 }
479 }
480  
481 3896 return $self;
482 }
483  
484 # Convert wire format Recipe list to internal format
485 # Wire (-09 section 5): an array of steps, each an object with exactly one
486 # key, "c", "d" or "u": {"c": [from,to]} copies, {"d": [...]} emits UTF-8
487 # literals, {"u": [...]} emits base64 ones.
488 # Internal: [from,to] arrays for copy ranges, strings for literal content
489 #
490 # A "u" item is decoded here, so the rest of the module sees one kind of
491 # literal: a plain byte string. The schema's checks are all made here, and
492 # so are §5.1/§5.2's rules on copy ranges that need no message: a range is
493 # exactly two JSON integers of at least 1, start <= end, each starting
494 # after the one before ends (no overlap, nothing out of order); a "d" or "u"
495 # array has at least one string; a "u" string is canonical base64 -- the
496 # alphabet, padding to a multiple of four, and zero pad bits, the schema's
497 # three patterns -- with no FWS; and no literal, "d" text or decoded "u"
498 # octets, may contain CR or LF, since a literal is exactly one header value
499 # or one body line. "d" text is UTF-8 already: decode_tag_json refuses JSON
500 # that is not. A list that is not an array is bad as a whole ($path); a bad
501 # step dies with $bad->("$path[<n>]"), n its 0-based index (contract D6).
502 # Whether a range lies within the lines it copies is for _check_recipe,
503 # when the Recipe is applied.
504 212 my $U_PATTERN = qr{\A(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?\z};
505 4538 ▶sub _decode_recipe_list {
Subroutine _decode_recipe_list: called CC=24 SCAR=31.8
506 4538 my ($list, $bad, $path) = @_;
507 4538 ▶ die $bad->($path) unless ref $list eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list eq "ARRAY" 1 4537 4538
508 4537 my (@decoded, $prev_end);
509 4537 for my $n (0 .. $#$list) {
510 5426 my $item = $list->[$n];
511 5426 my $invalid = $bad->("$path\[$n]");
512 5426 ▶ die $invalid unless ref $item eq 'HASH' && keys %$item == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" and keys %$item == 1 10 5416 5426
Condition100%3/3
ref $item eq "HASH" and keys %$item == 1
!ll&&!rl&&r
825416
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
513 5416 my ($kind) = keys %$item;
514 5416 my $val = $item->{$kind};
515 5416 ▶ die $invalid unless ref $val eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $val eq "ARRAY" 17 5399 5416
516 5399 ▶ if ($kind eq 'c') {
Branch: 3 branches
BranchTrueFalseTotal
if ($kind eq 'c') { } 2713 2686 5399
elsif ($kind eq 'd') { } 2623 63 2686
elsif ($kind eq 'u') { } 58 5 63
517 die $invalid unless @$val == 2
518 2713 ▶ && !grep { !_is_json_integer($_) || $_ < 1 } @$val;
Branch: 1 branch
BranchTrueFalseTotal
unless @$val == 2 and not grep({not _is_json_integer($_) or $_ < 1;} @$val) 52 2661 2713
Condition100%6/6
@$val == 2 and not grep({not _is_json_integer($_) or $_ < 1;} @$val)
!ll&&!rl&&r
17352661
!_is_json_integer($_) || $_ < 1
l!l&&r!l&&!r
25145353
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
519 2661 ▶ 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 2612 2661
Condition100%6/6
$val->[0] > $val->[1] or defined $prev_end and $val->[0] <= $prev_end
l!l&&r!l&&!r
11382612
defined $prev_end and $val->[0] <= $prev_end
!ll&&!rl&&r
1566104638
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
520 || (defined $prev_end && $val->[0] <= $prev_end);
521 2612 $prev_end = $val->[1];
522 2612 push @decoded, $val;
523 } elsif ($kind eq 'd') {
524 2623 ▶ die $invalid unless @$val;
Branch: 1 branch
BranchTrueFalseTotal
unless @$val 8 2615 2623
525 2615 for my $text (@$val) {
526 6647 ▶ 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 6627 6647
Condition100%3/3
_is_json_string($text) and not $text =~ /[\r\n]/
!ll&&!rl&&r
4166627
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
527 }
528 2595 push @decoded, @$val;
529 } elsif ($kind eq 'u') {
530 58 ▶ die $invalid unless @$val;
Branch: 1 branch
BranchTrueFalseTotal
unless @$val 4 54 58
531 54 for my $b64 (@$val) {
532 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
533 33 my $octets = decode_base64($b64);
534 33 ▶ die $invalid if $octets =~ /[\r\n]/;
Branch: 1 branch
BranchTrueFalseTotal
if $octets =~ /[\r\n]/ 13 20 33
535 20 push @decoded, $octets;
536 }
537 } else {
538 5 die $invalid;
539 }
540 }
541 4333 return \@decoded;
542 }
543  
544 # A header name as a Recipe path writes it: printable ASCII as it is,
545 # any other octet as \xHH (contract D6).
546 2869 ▶sub _path_name {
Subroutine _path_name: called CC=1 SCAR=0.2
547 2869 my ($name) = @_;
548 0 $name =~ s/([^\x21-\x7e])/sprintf '\\x%02X', ord $1/ge;
549 2869 return $name;
550 }
551  
552 # --- Digests ---
553  
554 1458 ▶sub h_digest {
Subroutine h_digest: called CC=6 SCAR=17.9
Pod documented
555 1458 my ($msg, $alg, $prefixes) = @_;
556 1458 ▶ $alg = lc($alg // 'sha256');
Condition100%2/2
$alg // "sha256"
l!l
14562
MC/DC100%1/1
$alg // "sha256"
$alg
Truth table100%2/2
A
A= $alg
Aresult
11
00
557  
558 # Fields grouped by name as DKIM2 compares names (field_name: "From :"
559 # is a From), names in order, each name's fields bottom-up.
560 1458 my @pairs = $msg->header_obj->header_raw_pairs;
561 1458 my %by;
562 15349 push @{ $by{ Mail::DKIM2::Canon::field_name($pairs[2 * $_]) } }, $pairs[2 * $_ + 1]
563 1458 for 0 .. $#pairs / 2;
564 1458 my $data = '';
565 1458 for my $header (sort keys %by) {
566 11038 ▶ next if should_skip($header, $prefixes);
Branch: 1 branch
BranchTrueFalseTotal
if should_skip($header, $prefixes) 3763 7275 11038
567 7275 for my $item (reverse @{ $by{$header} }) {
568 7366 my $chead = dkim2_canonicalize_header("$header: $item\r\n");
569 7366 $data .= $chead;
570 }
571 }
572  
573 1458 return _hash_data_b64($alg, $data);
574 }
575  
576 1385 ▶sub b_digest {
Subroutine b_digest: called CC=2 SCAR=6.9
Pod documented
577 1385 my ($msg, $alg) = @_;
578 1385 ▶ $alg = lc($alg // 'sha256');
Condition100%2/2
$alg // "sha256"
l!l
136817
MC/DC100%1/1
$alg // "sha256"
$alg
Truth table100%2/2
A
A= $alg
Aresult
11
00
579  
580 # DKIM simple body canonicalization: strip trailing empty lines,
581 # ensure exactly one trailing CRLF
582 1385 my $body = $msg->body_raw;
583 1385 $body =~ s/(\r\n)+\z//;
584 1385 $body .= "\r\n";
585  
586 1385 return _hash_data_b64($alg, $body);
587 }
588  
589 # -09 §3.1/§3.5: hash $data with the named (implemented) algorithm and
590 # base64-encode the result.
591 6441 ▶sub _hash_data_b64 {
Subroutine _hash_data_b64: called CC=2 SCAR=7.1
592 6441 my ($alg, $data) = @_;
593 6441 ▶ 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") 6441 0 6441
594 6441 return encode_base64($fn->($data), '');
595 }
596  
597 # --- Body Recipe computation ---
598  
599 # The capped Myers line diff, the same algorithm in every implementation in
600 # this repository so they emit identical Recipes (docs/superpowers/specs/
601 # 2026-10-09-capped-myers-body-diff-design.md).
602 #
603 # _body_diff(\@cur, \@prev, $max_literals) returns undef when the bodies are
604 # identical, 'too_big' when rebuilding @prev would take more than
605 # $max_literals literal lines or the search ran out of work budget, else the
606 # Recipe: [from,to] copy ranges (1-based, into @cur) and literal lines, in
607 # @prev order.
608 #
609 # The cap is on the Recipe's output, but it bounds the search exactly:
610 # literals = M - LCS and edits D = N + M - 2*LCS, so at most L literals
611 # means D <= N - M + 2L. MAX_DIFF_WORK bounds the rest -- CPU and trace
612 # memory when N is much larger than M and that edit bound is loose.
613 212 ▶use constant MAX_RECIPE_LITERALS => 1000;
Subroutine BEGIN: called CC=1 SCAR=0.0
614 212 ▶use constant MAX_DIFF_WORK => 4_000_000;
Subroutine BEGIN: called CC=1 SCAR=0.0
615  
616 289 ▶sub _body_diff {
Subroutine _body_diff: called CC=56 SCAR=40.3
617 289 my ($cur, $prev, $max) = @_;
618 289 ▶ $max //= MAX_RECIPE_LITERALS;
Condition100%2/2
$max //= 1000
l!l
30259
MC/DC100%1/1
$max //= 1000
$max
Truth table100%2/2
A
A= $max
Aresult
11
00
619 289 my ($C, $P) = (scalar @$cur, scalar @$prev);
620  
621 # 1. Trim the common prefix and suffix.
622 289 my $pre = 0;
623 289 ▶ $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 } 1094 289 1383
Condition100%6/6
$pre < $C and $pre < $P and $cur->[$pre] eq $prev->[$pre]
!ll&&!rl&&r
223661094
$pre < $C and $pre < $P
!ll&&!rl&&r
551681160
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
624 289 ▶ return undef if $pre == $C && $pre == $P;
Branch: 1 branch
BranchTrueFalseTotal
if $pre == $C and $pre == $P 53 236 289
Condition100%3/3
$pre == $C and $pre == $P
!ll&&!rl&&r
234253
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
625 236 my $suf = 0;
626 236 ▶ $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 236 2738
Condition100%6/6
$suf < $C - $pre and $suf < $P - $pre and $$cur[$C - 1 - $suf] eq $$prev[$P - 1 - $suf]
!ll&&!rl&&r
201352502
$suf < $C - $pre and $suf < $P - $pre
!ll&&!rl&&r
301712537
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
627 && $cur->[$C - 1 - $suf] eq $prev->[$P - 1 - $suf];
628  
629 # 2. Intern the middle lines and discard those that cannot be in the
630 # LCS: a current line that never occurs in the previous middle is a pure
631 # deletion, a previous line that never occurs in the current middle is
632 # certainly a literal.
633 236 my (%id, %cnt_a, %cnt_b);
634 236 my @a_lines = @{$cur}[$pre .. $C - $suf - 1];
635 236 my @b_lines = @{$prev}[$pre .. $P - $suf - 1];
636 236 $cnt_b{$_}++ for @b_lines;
637 236 $cnt_a{$_}++ for @a_lines;
638 236 my (@A, @ai, @B, @bj);
639 236 for my $i (0 .. $#a_lines) {
640 279195 my $l = $a_lines[$i];
641 279195 ▶ next unless $cnt_b{$l};
Branch: 1 branch
BranchTrueFalseTotal
unless $cnt_b{$l} 50552 228643 279195
642 228643 ▶ push @A, $id{$l} //= scalar keys %id;
Condition100%2/2
$id{$l} //= scalar keys %id
l!l
124206104437
MC/DC100%1/1
$id{$l} //= scalar keys %id
$id{$l}
Truth table100%2/2
A
A= $id{$l}
Aresult
11
00
643 228643 push @ai, $i;
644 }
645 236 for my $j (0 .. $#b_lines) {
646 233654 my $l = $b_lines[$j];
647 233654 ▶ next unless $cnt_a{$l};
Branch: 1 branch
BranchTrueFalseTotal
unless $cnt_a{$l} 5017 228637 233654
648 228637 ▶ push @B, $id{$l} //= scalar keys %id;
Condition50%1/2
$id{$l} //= scalar keys %id
l!l
2286370
MC/DC0%0/1
$id{$l} //= scalar keys %id
$id{$l}
Truth table50%1/2
A
A= $id{$l}
Aresult
11
00
649 228637 push @bj, $j;
650 }
651 236 my ($N, $M) = (scalar @A, scalar @B);
652 236 my $unique = @b_lines - $M;
653  
654 # A previous line occurring more often than in the current body needs
655 # a literal for each extra copy: a lower bound on the literal count
656 # that costs nothing to check before searching.
657 236 my $floor = $unique;
658 236 for my $l (keys %cnt_b) {
659 109453 ▶ my $extra = $cnt_b{$l} - ($cnt_a{$l} // 0);
Condition100%2/2
$cnt_a{$l} // 0
l!l
1044375016
MC/DC100%1/1
$cnt_a{$l} // 0
$cnt_a{$l}
Truth table100%2/2
A
A= $cnt_a{$l}
Aresult
11
00
660 109453 ▶ $floor += $extra if $extra > 0 && $cnt_a{$l};
Branch: 1 branch
BranchTrueFalseTotal
if $extra > 0 and $cnt_a{$l} 1 109452 109453
Condition100%3/3
$extra > 0 and $cnt_a{$l}
!ll&&!rl&&r
10443650161
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
661 }
662 236 ▶ return 'too_big' if $floor > $max;
Branch: 1 branch
BranchTrueFalseTotal
if $floor > $max 8 228 236
663  
664 # 3. Myers' greedy O(ND) search over the reduced sequences, keeping each
665 # round's V (packed, 32 bits a diagonal) for the backtrack. x indexes
666 # @A (current), y indexes @B (previous); "down" takes a previous line as
667 # a literal, "right" skips a current line, a diagonal step is a match.
668 228 my @match; # $match[$y] = $x for each matched @B line
669 228 ▶ if ($N && $M) {
Branch: 1 branch
BranchTrueFalseTotal
if ($N and $M) 18 210 228
Condition66%2/3
$N and $M
!ll&&!rl&&r
210018
MC/DC50%1/2
$N and $M
$N $M
Truth table66%2/3
A and B
A= $NB= $M
ABresult
0X0
100
111
670 18 my $dmax = $N - $M + 2 * ($max - $unique);
671 18 ▶ $dmax = $N + $M if $dmax > $N + $M;
Branch: 1 branch
BranchTrueFalseTotal
if $dmax > $N + $M 13 5 18
672 18 ▶ return 'too_big' if $dmax < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $dmax < 0 0 18 18
673 18 my $off = $dmax + 1;
674 18 my @v = (0) x (2 * $off + 1);
675 18 my @trace;
676 18 my $work = 0;
677 18 my ($found, $x, $y);
678 18 ROUND: for my $d (0 .. $dmax) {
679 2028 push @trace, pack('N*', @v[$off - $d - 1 .. $off + $d + 1]);
680 2028 ▶ for (my $k = -$d; $k <= $d; $k += 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k <= $d) 2003053 2011 2005064
681 2003053 ▶ $x = ($k == -$d
Branch: 1 branch
BranchTrueFalseTotal
$k == -$d || $k != $d && $v[$off + $k - 1] < $v[$off + $k + 1] ? : 2001045 2008 2003053
Condition83%5/6
$k == -$d or $k != $d and $v[$off + $k - 1] < $v[$off + $k + 1]
l!l&&r!l&&!r
202819990172008
$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
682 || ($k != $d && $v[$off + $k - 1] < $v[$off + $k + 1]))
683 ? $v[$off + $k + 1]
684 : $v[$off + $k - 1] + 1;
685 2003053 $y = $x - $k;
686 2003053 ▶ while ($x < $N && $y < $M && $A[$x] == $B[$y]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $N and $y < $M and $A[$x] == $B[$y]) 112627 2003053 2115680
Condition100%6/6
$x < $N and $y < $M and $A[$x] == $B[$y]
!ll&&!rl&&r
372003016112627
$x < $N and $y < $M
!ll&&!rl&&r
19182115643
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
687 112627 $x++; $y++; $work++;
688 }
689 2003053 $v[$off + $k] = $x;
690 2003053 ▶ return 'too_big' if ++$work > MAX_DIFF_WORK;
Branch: 1 branch
BranchTrueFalseTotal
if ++$work > 4000000 0 2003053 2003053
691 2003053 ▶ if ($x == $N && $y == $M) { $found = $d; last ROUND }
Branch: 1 branch
BranchTrueFalseTotal
if ($x == $N and $y == $M) 17 2003036 2003053
Condition100%3/3
$x == $N and $y == $M
!ll&&!rl&&r
2003034217
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
692 }
693 }
694 18 ▶ return 'too_big' unless defined $found;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $found 1 17 18
695  
696 # Backtrack: trace[d] holds V as it stood before round d, for
697 # diagonals -d-1 .. d+1 (index k + d + 1).
698 17 ▶ for (my $d = $found; $d > 0; $d--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($d > 0) 10 17 27
699 10 my $t = $trace[$d];
700 10 my $k = $x - $y;
701 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
702 || ($k != $d && vec($t, $k - 1 + $d + 1, 32) < vec($t, $k + 1 + $d + 1, 32));
703 10 ▶ my $pk = $down ? $k + 1 : $k - 1;
Branch: 1 branch
BranchTrueFalseTotal
$down ? : 2 8 10
704 10 my $px = vec($t, $pk + $d + 1, 32);
705 10 my $py = $px - $pk;
706 10 ▶ my ($sx, $sy) = $down ? ($px, $py + 1) : ($px + 1, $py);
Branch: 1 branch
BranchTrueFalseTotal
$down ? : 2 8 10
707 10 ▶ while ($x > $sx) { $x--; $y--; $match[$y] = $x }
Branch: 1 branch
BranchTrueFalseTotal
if ($x > $sx) 4021 10 4031
708 10 ($x, $y) = ($px, $py);
709 }
710 17 ▶ while ($x > 0) { $x--; $y--; $match[$y] = $x }
Branch: 1 branch
BranchTrueFalseTotal
if ($x > 0) 104604 17 104621
711 }
712  
713 # 4. Map back to whole-body indices and build the Recipe in @prev order,
714 # merging copies that are adjacent in both bodies.
715 227 my %src;
716 227 for my $y (0 .. $#match) {
717 108625 ▶ next unless defined $match[$y];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $match[$y] 0 108625 108625
718 108625 $src{$pre + $bj[$y]} = $pre + $ai[$match[$y]];
719 }
720 227 my @recipe;
721 227 my $literals = 0;
722 227 for my $j (0 .. $P - 1) {
723 my $i = $j < $pre ? $j
724 : $j >= $P - $suf ? $j - $P + $C
725 113528 ▶ : $src{$j};
Branch: 2 branches
BranchTrueFalseTotal
$j < $pre ? : 837 112691 113528
$j >= $P - $suf ? : 1458 111233 112691
726 113528 ▶ if (!defined $i) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $i) { } 2608 110920 113528
elsif (@recipe and ref $recipe[-1] and $recipe[-1][1] == $i) { } 110563 357 110920
727 2608 push @recipe, $prev->[$j];
728 2608 $literals++;
729 ▶ } 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
3525110563
@recipe and ref $recipe[-1]
!ll&&!rl&&r
213139110568
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
730 110563 $recipe[-1][1] = $i + 1;
731 } else {
732 357 push @recipe, [$i + 1, $i + 1];
733 }
734 }
735 227 ▶ return 'too_big' if $literals > $max;
Branch: 1 branch
BranchTrueFalseTotal
if $literals > $max 0 227 227
736 227 return \@recipe;
737 }
738  
739 # --- Calculate helpers ---
740  
741 # The body Recipe rebuilding $prev_raw from $cur_raw (raw body strings):
742 # undef when they are the same body, "too_big" over $max literal lines.
743 # Lines split as the verifier rebuilds them, trailing line breaks dropped.
744 271 ▶sub _body_recipe {
Subroutine _body_recipe: called CC=1 SCAR=0.0
745 271 my ($cur_raw, $prev_raw, $max) = @_;
746 271 (my $s1 = $cur_raw) =~ s/[\r\n]+$//;
747 271 (my $s2 = $prev_raw) =~ s/[\r\n]+$//;
748 271 return _body_diff([split /\r?\n/, $s1], [split /\r?\n/, $s2], $max);
749 }
750  
751 # BodyRecipe 'none' with a caller-supplied BodyHash: croak unless the hash
752 # equals the body hash in the previous message's top Message-Instance, for
753 # every algorithm both carry (and at least one).
754 2 ▶sub _check_body_unchanged {
Subroutine _check_body_unchanged: called CC=5 SCAR=16.2
755 2 my ($previous, $body_hash, $algs) = @_;
756 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
757 $previous->header_raw('Message-Instance');
758 2 my $top = __PACKAGE__->parse($map{ max(keys %map) });
759 2 my @common = grep { $top->{bits}{hashes}{$_} } @$algs;
760 2 ▶ croak "BodyRecipe 'none' with BodyHash: the previous instance has no "
Branch: 1 branch
BranchTrueFalseTotal
unless @common 0 2 2
761 . join('/', @$algs) . " body hash to compare" unless @common;
762 2 for my $alg (@common) {
763 croak "BodyRecipe 'none' with BodyHash: the body hash is not the "
764 . "previous instance's, so the body changed"
765 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
766 }
767 }
768  
769 # --- Calculate ---
770  
771 847 ▶sub calculate {
Subroutine calculate: called CC=78 SCAR=44.1
Pod documented
772 847 my ($class, $current, $previous, %opts) = @_;
773 847 Mail::DKIM2::Util::check_options("$class->calculate", \%opts,
774 qw(Algs BodyHash BodyRecipe IgnorePrefixes MaxRecipeLiterals));
775 844 ▶ croak "need a message" unless $current;
Branch: 1 branch
BranchTrueFalseTotal
unless $current 0 844 844
776  
777 844 my $self = bless {}, $class;
778 844 my $prefixes = check_ignore_prefixes($opts{IgnorePrefixes});
779  
780 # -09 §3.1: the signer chooses one or more hash algorithms; default
781 # is sha256 only (the signer default MUST NOT change).
782 843 ▶ $self->{algs} = ($opts{Algs} && @{$opts{Algs}}) ? [ @{$opts{Algs}} ] : ['sha256'];
Branch: 1 branch
BranchTrueFalseTotal
$opts{'Algs'} && @{$opts{'Algs'};} ? : 23 820 843
Condition66%2/3
$opts{"Algs"} and @{$opts{"Algs"};}
!ll&&!rl&&r
820023
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
783  
784 # BodyHash: the caller hashed the body (body_digest_raw), so $current
785 # may be the header block alone. Only where nothing here reads or
786 # changes the body: m=1, or a caller-supplied BodyRecipe.
787 croak "BodyRecipe needs a previous message"
788 843 ▶ if exists $opts{BodyRecipe} && !$previous;
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"BodyRecipe"} and not $previous 1 842 843
Condition100%3/3
exists $opts{"BodyRecipe"} and not $previous
!ll&&!rl&&r
803391
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
789  
790 # The literal-line cap on a diff body Recipe: over it, a null body Recipe.
791 croak "MaxRecipeLiterals must be a non-negative integer"
792 if exists $opts{MaxRecipeLiterals}
793 842 ▶ && !(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 839 842
Condition100%6/6
exists $opts{"MaxRecipeLiterals"} and not defined $opts{"MaxRecipeLiterals"} && $opts{"MaxRecipeLiterals"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
825143
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
794  
795 839 my $body_hash;
796 839 ▶ if (exists $opts{BodyHash}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"BodyHash"}) 21 818 839
797 21 my $bh = $opts{BodyHash};
798 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
799 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
800 unless ref $bh eq 'HASH';
801 20 for my $alg (@{$self->{algs}}) {
802 24 ▶ croak "BodyHash has no $alg hash" unless defined $bh->{$alg};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bh->{$alg} 2 22 24
803 }
804 # Each value goes into the h= tag verbatim: it must be the base64
805 # of a digest of that algorithm's length, nothing else.
806 18 for my $alg (sort keys %$bh) {
807 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
808 or croak "BodyHash: unsupported hash algorithm $alg";
809 20 my $v = $bh->{$alg};
810 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
811 unless defined $v && !ref $v
812 && $v =~ m{\A[A-Za-z0-9+/]+={0,2}\z}
813 && length(decode_base64($v)) == length($fn->(''));
814 }
815 croak "BodyHash needs BodyRecipe when there is a previous message"
816 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
817 12 $body_hash = $bh;
818 # The header block must be complete: a string whose last field has
819 # no line break gets one (nothing reads the body here).
820 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
821 if !ref $current && $current !~ /\n\z/;
822 }
823  
824 830 ▶ unless (ref($current) && $current->isa('Email::MIME')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $current and $current->isa("Email::MIME")) 105 725 830
Condition66%2/3
ref $current and $current->isa("Email::MIME")
!ll&&!rl&&r
1050725
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
825 105 $current = parse_mime($current);
826 }
827  
828 830 my $rb_recipe;
829  
830 830 ▶ if ($previous) {
Branch: 1 branch
BranchTrueFalseTotal
if ($previous) { } 303 527 830
831 303 ▶ unless (ref($previous) && $previous->isa('Email::MIME')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $previous and $previous->isa("Email::MIME")) 66 237 303
Condition66%2/3
ref $previous and $previous->isa("Email::MIME")
!ll&&!rl&&r
660237
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
832 66 $previous = parse_mime($previous);
833 }
834  
835 303 my @mi_cur = $current->header_raw('Message-Instance');
836 303 my @mi_prev = $previous->header_raw('Message-Instance');
837 303 ▶ die "Message already has " . MAX_CHAIN_LENGTH . " instances\n"
Branch: 1 branch
BranchTrueFalseTotal
if @mi_cur >= 32 1 302 303
838 if @mi_cur >= MAX_CHAIN_LENGTH;
839 302 ▶ if (my $error = _chain_error($current)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = _chain_error($current)) 0 302 302
840 0 die "$error\n";
841 }
842 # No instances on either side is a first instance with Recipes
843 # (-09 section 12.1: changes made as the message enters DKIM2).
844 # Verify same message by checking MI headers match
845 # header_raw returns values only, so prepend the name for canonicalization
846 302 my $canon_cur = join(',', map { dkim2_canonicalize_header("Message-Instance: $_") } @mi_cur);
847 302 my $canon_prev = join(',', map { dkim2_canonicalize_header("Message-Instance: $_") } @mi_prev);
848 302 ▶ die "This isn't the same message" unless ($canon_cur eq $canon_prev);
Branch: 1 branch
BranchTrueFalseTotal
unless $canon_cur eq $canon_prev 0 302 302
849  
850 302 my %map = map { extract_mi_version($_) => $_ } @mi_cur;
851 302 ▶ $self->set_tag('m', (max(keys %map) // 0) + 1);
Condition100%2/2
&max(keys %map) // 0
l!l
28913
MC/DC100%1/1
&max(keys %map) // 0
&max(keys %map)
Truth table100%2/2
A
A= &max(keys %map)
Aresult
11
00
852  
853 302 ▶ if (exists $opts{BodyRecipe}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{'BodyRecipe'}) { } 31 271 302
854 # Caller supplies the body Recipe: no body diff runs.
855 31 my $br = $opts{BodyRecipe};
856 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
857 4 $rb_recipe = undef;
858 # No b key declares the body unchanged: a caller-supplied
859 # BodyHash must then be the previous instance's body hash.
860 _check_body_unchanged($previous, $body_hash, $self->{algs})
861 4 ▶ if $body_hash;
Branch: 1 branch
BranchTrueFalseTotal
if $body_hash 2 2 4
862 ▶ } 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
863 9 $self->set_null_body_recipe;
864 } elsif (ref $br eq 'ARRAY') {
865 15 my $last = 0;
866 15 for my $step (@$br) {
867 16 ▶ croak "BodyRecipe step is undefined" unless defined $step;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $step 1 15 16
868 15 ▶ unless (ref $step) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $step) 3 12 15
869 3 ▶ croak "BodyRecipe literal contains a line break"
Branch: 1 branch
BranchTrueFalseTotal
if $step =~ /[\r\n]/ 3 0 3
870 if $step =~ /[\r\n]/;
871 0 next;
872 }
873 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
874 unless ref $step eq 'ARRAY' && @$step == 2;
875 12 my ($f, $t) = @$step;
876 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
877 unless $f =~ /^\d+\z/ && $t =~ /^\d+\z/
878 && $f >= 1 && $t >= $f && $f > $last;
879 9 $last = $t;
880 }
881 8 ▶ $rb_recipe = [ map { ref $_ ? [ @$_ ] : $_ } @$br ];
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 7 0 7
882 } else {
883 3 croak "BodyRecipe must be 'none', 'null' or an ARRAY ref";
884 }
885 }
886 else {
887 # A diff Recipe. A body the diff cannot rebuild within
888 # MaxRecipeLiterals lines (default MAX_RECIPE_LITERALS) is
889 # declared unrecoverable.
890 $rb_recipe = _body_recipe($current->body_raw, $previous->body_raw,
891 271 $opts{MaxRecipeLiterals});
892 271 ▶ if (defined $rb_recipe && !ref $rb_recipe) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rb_recipe and not ref $rb_recipe) 5 266 271
Condition100%3/3
defined $rb_recipe and not ref $rb_recipe
!ll&&!rl&&r
522145
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
893 5 $rb_recipe = undef;
894 5 $self->set_null_body_recipe;
895 }
896 }
897 }
898 else {
899 527 ▶ die "Already has Message-Instance headers" if $current->header_raw('Message-Instance');
Branch: 1 branch
BranchTrueFalseTotal
if $current->header_raw("Message-Instance") 0 527 527
900 527 $self->set_tag('m', 1);
901 }
902  
903 # Hashes are always of the current (newest) version of the message,
904 # for every configured algorithm (-09 §9.3).
905 818 for my $alg (@{$self->{algs}}) {
906 $self->{bits}{hashes}{$alg} = [ h_digest($current, $alg, $prefixes),
907 825 ▶ $body_hash ? $body_hash->{$alg} : b_digest($current, $alg) ];
Branch: 1 branch
BranchTrueFalseTotal
$body_hash ? : 13 812 825
908 }
909  
910 # nothing more to calculate without a previous version
911 818 ▶ return $self unless $previous;
Branch: 1 branch
BranchTrueFalseTotal
unless $previous 527 291 818
912  
913 # The header difference.
914 # Names as hashing and undo group them (field_name: "Subject :" is
915 # "subject"), so each Recipe key names the fields it is undone on.
916 291 my %all = map { Mail::DKIM2::Canon::field_name($_) => 1 }
917 ($current->header_names, $previous->header_names);
918 291 my %hdiff;
919 291 for my $h (sort keys %all) {
920 1996 ▶ next if should_skip($h, $prefixes);
Branch: 1 branch
BranchTrueFalseTotal
if should_skip($h, $prefixes) 603 1393 1996
921 1393 my @cur = reverse Mail::DKIM2::Canon::header_values($current, $h);
922 1393 my @prev = reverse Mail::DKIM2::Canon::header_values($previous, $h);
923 # Same number of instances AND the same values: zero instances and
924 # one empty instance both join to "", and removing an empty field
925 # (a bare "Bcc:") is still a change the Recipe must record.
926 next if @cur == @prev
927 1335 && join("\n", map { dkim2_canonicalize_header($_) } @cur)
928 1393 ▶ 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)) 1134 259 1393
Condition100%3/3
@cur == @prev and join("\n", map({dkim2_canonicalize_header($_);} @cur)) eq join("\n", map({dkim2_canonicalize_header($_);} @prev))
!ll&&!rl&&r
851741134
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
929 # A Recipe key is a header field name (-09 section 5): ftext. A
930 # field Email::Simple read under a name that is not one ("Y Bad:",
931 # a control character) cannot have its change recorded -- a verifier
932 # refuses the key -- so refuse to describe it rather than sign
933 # mail that no verifier accepts.
934 259 ▶ 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 256 259
935 unless $h =~ /\A[\x21-\x39\x3B-\x7E]+\z/;
936 # headers are indexed from 1 from the bottom up
937 256 my %known;
938 256 push @{ $known{dkim2_canonicalize_header($cur[$_])} }, $_ + 1 for 0..$#cur;
939 # Recipe: reconstruct @prev from @cur. Copy ranges must ascend (each
940 # starts after the last one ends, -09 §5.1), so each field of
941 # @cur is copied at most once and never out of turn: a repeat, or a
942 # field the hop moved above one it left alone, goes in literally.
943 # $last_end only grows, so each value's ascending index list is
944 # consumed through a cursor that never moves back: linear overall.
945 # (A grep over the whole list per field made N repeated fields cost
946 # N^2 -- follow-up review F1.)
947 256 my $last_end = 0;
948 256 my %cursor;
949 my @res = map {
950 256 my $canon = dkim2_canonicalize_header($_);
951 215 ▶ my $list = $known{$canon} || [];
Condition100%2/2
$known{$canon} || []
l!l
12203
MC/DC100%1/1
$known{$canon} || []
$known{$canon}
Truth table100%2/2
A
A= $known{$canon}
Aresult
11
00
952 215 ▶ my $c = \($cursor{$canon} //= 0);
Condition100%2/2
$cursor{$canon} //= 0
l!l
3212
MC/DC100%1/1
$cursor{$canon} //= 0
$cursor{$canon}
Truth table100%2/2
A
A= $cursor{$canon}
Aresult
11
00
953 215 ▶ $$c++ while $$c < @$list && $list->[$$c] <= $last_end;
Branch: 1 branch
BranchTrueFalseTotal
$$c < @$list and $$list[$$c] <= $last_end and do { ++$$c } 5 215 220
Condition100%3/3
$$c < @$list and $$list[$$c] <= $last_end
!ll&&!rl&&r
20785
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
954 215 my $idx = $list->[$$c];
955 215 ▶ $idx ? [$idx, $last_end = $idx] : $_
Branch: 1 branch
BranchTrueFalseTotal
$idx ? : 8 207 215
956 } @prev;
957 # combine adjacent ranges
958 256 for (1..$#res) {
959 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
960 2 ▶ next unless ($res[$_][0] == $res[$_-1][1] + 1);
Branch: 1 branch
BranchTrueFalseTotal
unless $res[$_][0] == $res[$_ - 1][1] + 1 0 2 2
961 2 $res[$_][0] = $res[$_-1][0];
962 2 $res[$_-1] = undef;
963 }
964 256 my @vals = grep { defined } @res;
965 256 $hdiff{$h} = \@vals;
966 }
967  
968 288 ▶ if ($rb_recipe) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rb_recipe) 222 66 288
969 222 $self->set_tag('rb', $rb_recipe);
970 }
971 288 ▶ if (keys %hdiff) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %hdiff) 187 101 288
972 187 $self->set_tag('rh', \%hdiff);
973 }
974  
975 288 return $self;
976 }
977  
978 # --- First instance over earlier unsigned ones ---
979  
980 15 ▶sub calculate_first {
Subroutine calculate_first: called CC=13 SCAR=26.5
Pod documented
981 15 my ($class, $current, $previous, %opts) = @_;
982 15 Mail::DKIM2::Util::check_options("$class->calculate_first", \%opts,
983 qw(Algs IgnorePrefixes MaxRecipeLiterals));
984 13 ▶ croak "need a message" unless $current;
Branch: 1 branch
BranchTrueFalseTotal
unless $current 0 13 13
985 13 ▶ croak "need a previous message" unless $previous;
Branch: 1 branch
BranchTrueFalseTotal
unless $previous 0 13 13
986  
987 13 ▶ $current = parse_mime($current) unless ref($current) && $current->isa('Email::MIME');
Branch: 1 branch
BranchTrueFalseTotal
unless ref $current and $current->isa("Email::MIME") 13 0 13
Condition33%1/3
ref $current and $current->isa("Email::MIME")
!ll&&!rl&&r
1300
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
988 # undo() (and so chain_verifies) rewrites the message it is given: work
989 # on copies of $previous.
990 13 ▶ my $prev_raw = ref($previous) ? $previous->as_string : $previous;
Branch: 1 branch
BranchTrueFalseTotal
ref $previous ? : 0 13 13
991 13 $previous = parse_mime($prev_raw);
992  
993 # Only a chain that undoes cleanly says what the message was before it.
994 my ($ok, $why) = $class->chain_verifies($prev_raw,
995 13 ▶ (exists $opts{IgnorePrefixes} ? (IgnorePrefixes => $opts{IgnorePrefixes}) : ()));
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'IgnorePrefixes'} ? : 5 8 13
996 13 ▶ die(($why // 'Message-Instance chain does not verify') . "\n") unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 1 12 13
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
997  
998 # Undo every instance, m=1 included (its own Recipes, if any). Past a
999 # null body Recipe the earlier body is gone: header Recipes only, and
1000 # the new instance declares the body unrecoverable.
1001 12 my $lost = 0;
1002 12 ▶ while (my @mi = $previous->header_raw('Message-Instance')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@mi) = $previous->header_raw("Message-Instance")) 20 12 32
1003 20 ▶ my %by_v = map { (extract_mi_version($_) // 0) => $_ } @mi;
Condition50%1/2
extract_mi_version($_) // 0
l!l
280
MC/DC0%0/1
extract_mi_version($_) // 0
extract_mi_version($_)
Truth table50%1/2
A
A= extract_mi_version($_)
Aresult
11
00
1004 20 ▶ $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 18 20
1005 20 $previous = $class->undo($previous, HeadersOnly => $lost);
1006 }
1007 12 $current->header_set('Message-Instance');
1008  
1009 12 ▶ return $class->calculate($current, $previous, %opts,
Branch: 1 branch
BranchTrueFalseTotal
$lost ? : 2 10 12
1010 ($lost ? (BodyRecipe => 'null') : ()));
1011 }
1012  
1013 # --- Verify ---
1014  
1015 440 ▶sub verify {
Subroutine verify: called CC=15 SCAR=27.5
Pod documented
1016 440 my ($class, $msg, %opts) = @_;
1017 440 Mail::DKIM2::Util::check_options("$class->verify", \%opts,
1018 qw(HeadersOnly IgnorePrefixes BodyHashes));
1019 439 ▶ croak "need a message" unless $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless $msg 0 439 439
1020 439 check_ignore_prefixes($opts{IgnorePrefixes});
1021  
1022 438 ▶ unless (ref($msg) && $msg->isa('Email::MIME')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $msg and $msg->isa("Email::MIME")) 11 427 438
Condition66%2/3
ref $msg and $msg->isa("Email::MIME")
!ll&&!rl&&r
110427
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
1023 11 $msg = parse_mime($msg);
1024 }
1025  
1026 438 ▶ if (my $error = _chain_error($msg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = _chain_error($msg)) 5 433 438
1027 5 ▶ return wantarray ? (0, $error) : 0;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 3 5
1028 }
1029  
1030 433 my %map = map { extract_mi_version($_) => $_ } $msg->header_raw('Message-Instance');
1031 433 ▶ my $num = keys %map ? max(keys %map) : 0;
Branch: 1 branch
BranchTrueFalseTotal
keys %map ? : 432 1 433
1032 433 ▶ return 0 unless $num;
Branch: 1 branch
BranchTrueFalseTotal
unless $num 1 432 433
1033  
1034 # A crafted instance (duplicate algorithm, bad hash set, unparseable
1035 # Recipe) is a verdict, not an exception: this is the status-returning
1036 # half of the contract, and a host must not have to eval it.
1037 432 my $self = eval { $class->parse($map{$num}) };
1038 432 ▶ unless ($self) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self) 64 368 432
1039 64 ▶ die $@ if ref $@;
Branch: 1 branch
BranchTrueFalseTotal
if ref $@ 0 64 64
1040 64 my $err = _parse_error($@);
1041 64 ▶ return wantarray ? (0, $err) : 0;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 64 0 64
1042 }
1043  
1044 my ($ok, $err) = $self->_check_hashes($num,
1045 367 ▶ sub { h_digest($msg, $_[0], $opts{IgnorePrefixes}) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1046 # HeadersOnly: below a null body Recipe the body this instance
1047 # hashed is gone; its header hashes are still checkable.
1048 # BodyHashes: computed already (Mail::DKIM2::BodyPlan), from a body
1049 # $msg does not carry.
1050 $opts{HeadersOnly} ? undef
1051 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
1052 368 ▶ : sub { b_digest($msg, $_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 2 branches
BranchTrueFalseTotal
$opts{'HeadersOnly'} ? : 14 354 368
$opts{'BodyHashes'} ? : 0 354 354
1053 368 ▶ return wantarray ? (0, $err) : 0 unless $ok;
Branch: 2 branches
BranchTrueFalseTotal
unless $ok 84 284 368
wantarray ? : 47 37 84
1054 284 return $num;
1055 }
1056  
1057 # A parse() failure in the words verify() reports it.
1058 208 ▶sub _parse_error {
Subroutine _parse_error: called CC=1 SCAR=0.0
1059 208 my ($err) = @_;
1060 208 $err =~ s/\s+at\s+\S+\s+line\s+\d+\.?\s*\z//;
1061 208 $err =~ s/\s+\z//;
1062 208 return $err;
1063 }
1064  
1065 # Instance $num's hash-sets against the header and body hashes the two
1066 # callbacks give for an algorithm ($body undef: headers only, when the body
1067 # is gone -- below a null body Recipe, or a DSN without it, -09 §16.4 -- and
1068 # a set passes on its header hash). Returns 1, or (0, $reason).
1069 #
1070 # -09 §14.7: each set passes if its hashes match, fails if one does not, and
1071 # is a PERMERROR if this verifier does not implement its algorithm; the
1072 # "," lists and "|" groups combine as Common::combine_sets says (D4). A set
1073 # reports its header hash before its body hash; sets go in h= order.
1074 1460 ▶sub _check_hashes {
Subroutine _check_hashes: called CC=13 SCAR=27.0
1075 1460 my ($self, $num, $header, $body) = @_;
1076  
1077 1460 ▶ my $hashes = $self->get_tag('hashes') || {};
Condition50%1/2
$self->get_tag('hashes') || {}
l!l
14600
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
1078 1460 my $impl = hash_algs();
1079 # h= groups: as parsed, or the one list calculate() writes (its algs).
1080 my $groups = $self->{hash_groups}
1081 1460 ▶ || [ $self->{hash_order} || $self->{algs} || [ sort keys %$hashes ] ];
Condition14%1/7
$self->{'hash_groups'} || [$self->{'hash_order'} || $self->{'algs'} || [sort(keys %$hashes)]]
l!l
14600
$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
1082 1460 my @results;
1083 1460 for my $group (@$groups) {
1084 1467 my @members;
1085 1467 for my $alg (@$group) {
1086 1475 my $pair = $hashes->{$alg};
1087 push @members,
1088 1475 ▶ !$impl->{$alg} || !$pair
Branch: 3 branches
BranchTrueFalseTotal
!($impl->{$alg} && $pair) ? : 9 1466 1475
$pair->[0] ne &$header($alg) ? : 135 1331 1466
$body && $pair->[1] ne &$body($alg) ? : 88 1243 1331
Condition83%5/6
$impl->{$alg} && $pair
!ll&&!rl&&r
901466
$body and $pair->[1] ne &$body($alg)
!ll&&!rl&&r
42120188
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
1089 ? ['permerror', "PERMERROR: Message-Instance m=$num algorithm $alg unknown"]
1090 : $pair->[0] ne $header->($alg)
1091 ? ['fail', "FAIL: Message-Instance m=$num header hash $alg mismatch"]
1092 : $body && $pair->[1] ne $body->($alg)
1093 ? ['fail', "FAIL: Message-Instance m=$num body hash $alg mismatch"]
1094 : ['pass'];
1095 }
1096 1467 push @results, \@members;
1097 }
1098 1460 my ($state, $why) = Mail::DKIM2::Common::combine_sets(\@results,
1099 "FAIL: Message-Instance m=$num no group of hashes passed");
1100 1460 ▶ return $state eq 'pass' ? 1 : (0, $why);
Branch: 1 branch
BranchTrueFalseTotal
$state eq 'pass' ? : 1238 222 1460
1101 }
1102  
1103 # --- Undo ---
1104  
1105 # Rebuild the previous lines from @$old by a Recipe of [from, to] copy ranges
1106 # (1-based, inclusive) and literal lines. Each range must lie within @$old,
1107 # and the ranges must ascend: each must start after the one before it ends
1108 # (-09 §5.1, and the same rule for the body). The previous version is
1109 # rebuilt from this one, and a hop's change never needs a line of it twice
1110 # or in a different order -- a reordering is recorded literally. Without the
1111 # check a few bytes of header could name a copy of billions of lines.
1112 # Everything is checked before anything is copied.
1113 #
1114 # A bound must be a JSON integer (-09 §5 schema): {"c":["1","2"]} is
1115 # malformed, and every verifier in the interop set rejects it. The JSON
1116 # decoder gives a number an IV and a string a PV, so the distinction is
1117 # read off the scalar's flags -- before anything stringifies it, which
1118 # would set POK on a genuine number too.
1119 13142 ▶sub _is_json_integer {
Subroutine _is_json_integer: called CC=5 SCAR=16.1
1120 13142 my ($v) = @_;
1121 13142 ▶ return 0 unless defined $v && !ref $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and not ref $v 8 13134 13142
Condition100%3/3
defined $v and not ref $v
!ll&&!rl&&r
4413134
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
1122 13134 my $flags = B::svref_2object(\$v)->FLAGS;
1123 13134 ▶ return ($flags & B::SVf_IOK) && !($flags & (B::SVf_POK | B::SVf_NOK)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$flags & 256 && !($flags & 1536) ? : 13117 17 13134
Condition66%2/3
$flags & 256 and not $flags & 1536
!ll&&!rl&&r
17013117
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
1124 }
1125  
1126 # A JSON string, read off the flags the same way: a JSON number is not one.
1127 6706 ▶sub _is_json_string {
Subroutine _is_json_string: called CC=4 SCAR=14.9
1128 6706 my ($v) = @_;
1129 6706 ▶ return 0 unless defined $v && !ref $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and not ref $v 0 6706 6706
Condition33%1/3
defined $v and not ref $v
!ll&&!rl&&r
006706
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
1130 6706 ▶ return (B::svref_2object(\$v)->FLAGS & B::SVf_POK) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
B::svref_2object(\$v)->FLAGS & 1024 ? : 6698 8 6706
1131 }
1132  
1133 # Recipe structure: integer bounds, from <= to, ascending, non-overlapping.
1134 # $lines, when given, also bounds "to" by the old body/header; it is omitted
1135 # when the thing the Recipe applies to is gone (a body below a null body
1136 # Recipe), where the structure must still be valid.
1137 4119 ▶sub _check_recipe {
Subroutine _check_recipe: called CC=17 SCAR=38.6
1138 4119 my ($what, $recipe, $lines) = @_;
1139 4119 my $prev;
1140 4119 for my $cmd (grep { ref($_) eq 'ARRAY' } @$recipe) {
1141 3875 my ($from, $to) = @$cmd;
1142 3875 ▶ 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 3875 3875
Condition33%4/12
@$cmd == 2 and _is_json_integer($from) and $from >= 0 and _is_json_integer($to) and $to >= 0
!ll&&!rl&&r
003875
@$cmd == 2 and _is_json_integer($from) and $from >= 0 and _is_json_integer($to)
!ll&&!rl&&r
003875
@$cmd == 2 and _is_json_integer($from) and $from >= 0
!ll&&!rl&&r
003875
@$cmd == 2 and _is_json_integer($from)
!ll&&!rl&&r
003875
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
1143 unless @$cmd == 2
1144 && _is_json_integer($from) && $from >= 0
1145 && _is_json_integer($to) && $to >= 0;
1146 3875 ▶ 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 3848 3875
Condition66%6/9
1 <= $from and $from <= $to and !defined($lines) || $to <= $lines
!ll&&!rl&&r
0273848
1 <= $from and $from <= $to
!ll&&!rl&&r
003875
not defined $lines or $to <= $lines
l!l&&r!l&&!r
1829201927
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
1147 # No line count (structure-only check below a null body Recipe).
1148 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
1149 27 die "$what Recipe copies lines $from-$to of $lines\n";
1150 }
1151 3848 ▶ if ($prev && $from <= $prev->[1]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prev and $from <= $prev->[1]) 0 3848 3848
Condition66%2/3
$prev and $from <= $prev->[1]
!ll&&!rl&&r
211317350
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
1152 0 ▶ if ($to >= $prev->[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($to >= $prev->[0]) 0 0 0
1153 0 ▶ my $lo = $from > $prev->[0] ? $from : $prev->[0];
Branch: 1 branch
BranchTrueFalseTotal
$from > $prev->[0] ? : 0 0 0
1154 0 ▶ my $hi = $to < $prev->[1] ? $to : $prev->[1];
Branch: 1 branch
BranchTrueFalseTotal
$to < $prev->[1] ? : 0 0 0
1155 0 die "$what Recipe copies lines $lo-$hi twice\n";
1156 }
1157 0 die "$what Recipe copies lines $from-$to out of order\n";
1158 }
1159 3848 $prev = [$from, $to];
1160 }
1161 4092 return;
1162 }
1163  
1164 513 ▶sub _apply_recipe {
Subroutine _apply_recipe: called CC=2 SCAR=6.9
1165 513 my ($what, $recipe, $old) = @_;
1166 513 _check_recipe($what, $recipe, scalar @$old);
1167  
1168 return map {
1169 498 ▶ ref($_) eq 'ARRAY' ? @$old[$_->[0] - 1 .. $_->[1] - 1] : $_
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 325 1784 2109
1170 } @$recipe;
1171 }
1172  
1173 # Set a message's body to exactly these octets. Email::MIME->body_set encodes
1174 # what it is given according to the Content-Transfer-Encoding header, so on a
1175 # base64 or quoted-printable part the rebuilt previous body -- already in its
1176 # wire encoding, since Recipes work on wire lines -- came back encoded twice,
1177 # and every base64/QP message a list re-encoded failed its m=1 hash on undo
1178 # (2026-10-04: 17 of 88 corpus samples through Mailman; the milter refused to
1179 # sign them). This is Email::MIME::body_set without the encoding step.
1180 137 ▶sub _body_raw_set {
Subroutine _body_raw_set: called CC=1 SCAR=0.0
1181 137 my ($msg, $raw) = @_;
1182 137 $msg->{body_raw} = $raw;
1183 137 $msg->Email::Simple::body_set($raw);
1184 137 return;
1185 }
1186  
1187 340 ▶sub undo {
Subroutine undo: called CC=16 SCAR=27.8
Pod documented
1188 340 my ($class, $msg, %opts) = @_;
1189 340 Mail::DKIM2::Util::check_options("$class->undo", \%opts, qw(HeadersOnly));
1190 339 ▶ croak "need a message" unless $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless $msg 0 339 339
1191  
1192 339 ▶ unless (ref($msg) && $msg->isa('Email::MIME')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $msg and $msg->isa("Email::MIME")) 43 296 339
Condition66%2/3
ref $msg and $msg->isa("Email::MIME")
!ll&&!rl&&r
430296
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
1193 43 $msg = parse_mime($msg);
1194 }
1195  
1196 339 ▶ if (my $error = _chain_error($msg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = _chain_error($msg)) 2 337 339
1197 2 die "$error\n";
1198 }
1199  
1200 337 my %map = map { extract_mi_version($_) => $_ } $msg->header_raw('Message-Instance');
1201 337 ▶ my $num = keys %map ? max(keys %map) : 0;
Branch: 1 branch
BranchTrueFalseTotal
keys %map ? : 337 0 337
1202 337 ▶ return unless $num;
Branch: 1 branch
BranchTrueFalseTotal
unless $num 0 337 337
1203  
1204 337 ▶ $msg->header_obj->header_filter('Message-Instance', sub { extract_mi_version(shift) < $num });
Subroutine __ANON__: called CC=1 SCAR=0.0
1205  
1206 337 my $self = $class->parse($map{$num});
1207  
1208 306 my $rb = $self->get_tag('rb');
1209 306 my $rh = $self->get_tag('rh');
1210  
1211 306 ▶ if ($rb && !$opts{HeadersOnly}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($rb and not $opts{'HeadersOnly'}) { } 145 161 306
elsif ($rb) { } 2 159 161
Condition100%3/3
$rb and not $opts{"HeadersOnly"}
!ll&&!rl&&r
1592145
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
1212 # Every line, trailing blank ones too: they are not hashed (§6.1),
1213 # but a Recipe may number and copy them, as the other
1214 # implementations in the interop set allow. Only the empty piece
1215 # after the last line break is not a line.
1216 145 my @old = split /\r?\n/, $msg->body_raw, -1;
1217 145 ▶ pop @old if @old && $old[-1] eq '';
Branch: 1 branch
BranchTrueFalseTotal
if @old and $old[-1] eq "" 142 3 145
Condition100%3/3
@old and $old[-1] eq ""
!ll&&!rl&&r
21142
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
1218 145 my @new = _apply_recipe('body', $rb, \@old);
1219 137 _body_raw_set($msg, join("\r\n", @new, ''));
1220 } elsif ($rb) {
1221 # The body is not rebuilt, but the Recipe must still be well formed.
1222 2 _check_recipe('body', $rb);
1223 }
1224  
1225 298 ▶ if ($rh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rh) 152 146 298
1226 152 for my $h (sort keys %$rh) {
1227 361 my $v = $rh->{$h};
1228 361 ▶ next unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 361 361
1229 # Message-Instance and DKIM2-Signature fields are not content (-09
1230 # section 6.2): a Recipe naming one acts on content fields of that
1231 # name, of which there are none, and what it rebuilds is not hashed.
1232 # Applying it to the received fields would let a hop rewrite the
1233 # instances below its own -- a forged history the walk then checks.
1234 361 ▶ 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 356 361
1235 5 _apply_recipe("$h header", $v, []);
1236 3 next;
1237 }
1238 356 my @old = reverse Mail::DKIM2::Canon::header_values($msg, $h);
1239 356 my @new = _apply_recipe("$h header", $v, \@old);
1240 351 $msg->header_obj->header_set_reverse($h, @new);
1241 }
1242 }
1243  
1244 291 return $msg;
1245 }
1246  
1247 # Verify the WHOLE Message-Instance chain reverses cleanly: check the top
1248 # instance against the current content, then undo it and check the next one
1249 # down, until m=1; past an instance with a null body Recipe, header-only
1250 # (the body is gone but the header history is still checked). This is the
1251 # undo check a recipient performs — running it before signing catches an
1252 # upstream that emitted a non-reversible Recipe.
1253 # Returns (1, undef) on success or (0, reason) on the first failure.
1254 132 ▶sub chain_verifies {
Subroutine chain_verifies: called CC=16 SCAR=28.3
Pod documented
1255 132 my ($class, $msg, %opts) = @_;
1256 132 Mail::DKIM2::Util::check_options("$class->chain_verifies", \%opts,
1257 qw(IgnorePrefixes));
1258 131 check_ignore_prefixes($opts{IgnorePrefixes});
1259 131 ▶ unless (ref($msg) && $msg->isa('Email::MIME')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $msg and $msg->isa("Email::MIME")) 131 0 131
Condition33%1/3
ref $msg and $msg->isa("Email::MIME")
!ll&&!rl&&r
13100
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
1260 131 $msg = parse_mime("$msg");
1261 }
1262 131 ▶ if (my $error = _chain_error($msg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = _chain_error($msg)) 5 126 131
1263 5 return (0, $error);
1264 }
1265 126 my $headers_only = 0;
1266 126 while (1) {
1267 211 my @mi = $msg->header_raw('Message-Instance');
1268 211 ▶ my %by_v = map { (extract_mi_version($_) // 0) => $_ } @mi;
Condition50%1/2
extract_mi_version($_) // 0
l!l
8310
MC/DC0%0/1
extract_mi_version($_) // 0
extract_mi_version($_)
Truth table50%1/2
A
A= extract_mi_version($_)
Aresult
11
00
1269 211 ▶ my $num = %by_v ? (sort { $b <=> $a } keys %by_v)[0] : 0;
Branch: 1 branch
BranchTrueFalseTotal
%by_v ? : 210 1 211
1270 211 ▶ last unless $num;
Branch: 1 branch
BranchTrueFalseTotal
unless $num 1 210 211
1271  
1272 210 my ($ok, $err) = $class->verify($msg, %opts, HeadersOnly => $headers_only);
1273 210 ▶ return (0, $err // "FAIL: Message-Instance m=$num header hash mismatch") unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 69 141 210
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
1274  
1275 141 ▶ last if $num <= 1;
Branch: 1 branch
BranchTrueFalseTotal
if $num <= 1 53 88 141
1276 # A null body Recipe loses the previous body, not the header
1277 # history: from here down, undo header Recipes only and check each
1278 # instance's header hashes, down to m=1.
1279 88 ▶ $headers_only = 1 if $class->parse($by_v{$num})->unrecoverable;
Branch: 1 branch
BranchTrueFalseTotal
if $class->parse($by_v{$num})->unrecoverable 14 74 88
1280  
1281 88 my $prev = eval { $class->undo($msg, HeadersOnly => $headers_only) };
1282 88 ▶ die $@ if ref $@;
Branch: 1 branch
BranchTrueFalseTotal
if ref $@ 0 88 88
1283 # A bad step is already a verdict (parse: "Recipe <path> is
1284 # invalid", D6). A range past the lines it copies is found here, as
1285 # "contains invalid JSON"; a third value says which range, for a log.
1286 88 ▶ if ($@ || !$prev) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $prev) 3 85 88
Condition66%2/3
$@ or not $prev
l!l&&r!l&&!r
3085
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
1287 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
1288 3 ▶ return (0, $why) if $why =~ /\A(?:PERMERROR|FAIL|TEMPERROR): /;
Branch: 1 branch
BranchTrueFalseTotal
if $why =~ /\A(?:PERMERROR|FAIL|TEMPERROR): / 0 3 3
1289 3 return (0, "PERMERROR: Message-Instance m=$num contains invalid JSON", $why);
1290 }
1291 85 $msg = $prev;
1292 }
1293 54 return (1, undef);
1294 }
1295  
1296  
1297 212 1;
1298  
1299 __END__
« lib/Mail/Milter/Authentication/Handler/DKIM2Sign.pm ↑ Summary lib/Mail/DKIM2/BodyPlan.pm »