lib/Mail/Send/DKIM.pm

filter: Statementstmt 100% 333 / 333 Branchbran 98.0% 102 / 104 Conditioncond 92.1% 118 / 128 MC/DCmcdc 80.0% 60 / 75 Subroutinesub 100% 62 / 62 Podpod 100% 7 / 7 totaltotal 96.1% 682 / 709 CC 106 SCAR 18.7
CC
106
Cov
98%
new
14.1
_choose_format
13.0
_parse_sendmail_args
11.0
CRAP 6.5
« bin/dmarc-summary ↑ Summary bin/dmarc-report.pl »
1 package Mail::Send::DKIM;
2  
3 # The signing half of bin/mail-dkim: given an object configured with the
4 # domains this host signs for, a message either comes back signed or comes back
5 # as undef and the caller sends it as it is. Nothing here dies on a signing
6 # problem, because a missing key must never stop mail being delivered.
7  
8 19 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 19 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 # Not :all - that wraps the socket builtin send(), which this package's
11 # documented send() method would then redefine. Sockets are not used here.
12 19 ▶use autodie qw(:file :filesys :system);
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 19 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 19 ▶use Errno qw(ENOENT);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 19 ▶use File::Basename qw(basename);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 19 ▶use Mail::Address;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 19 ▶use Mail::DKIM::Signer;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 # Mail::DKIM folds the signature header only when this has been loaded.
20 19 ▶use Mail::DKIM::TextWrap;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 19 ▶use MIME::Base64 qw(decode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
22 19 ▶use Object::Configure;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 19 ▶use Params::Get;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 19 ▶use Params::Validate::Strict qw(validate_strict);
Subroutine BEGIN: called CC=1 SCAR=0.0
25 19 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 19 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
27 # Helpers are private to this package, enforced at call time so that method
28 # dispatch ($self->_helper) is covered as well as plain function calls.
29 19 ▶use Sub::Private { 'mode' => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
30 19 ▶use Sub::Protected;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 19 ▶use Sys::Syslog ();
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 19 ▶use version; our $VERSION = version->declare('0.005.0');
Subroutine BEGIN: called CC=1 SCAR=0.0
34  
35 # What the signature is made with: the shape receiving sites expect.
36 19 Readonly my $ALGORITHM => 'rsa-sha256';
37 # Both halves are named: "relaxed" alone leaves the body "simple" (RFC 6376, 3.5).
38 19 Readonly my $CANONICALIZATION => 'relaxed/relaxed';
39 # RFC 8301, 3.2: signers must not use a smaller RSA key.
40 19 Readonly my $MINIMUM_KEY_BITS => 1024;
41  
42 # Where keys are kept, and what a key file is called.
43 19 Readonly my $KEY_SUFFIX => '.private';
44 19 Readonly my $KEYFILE_NAME_SUFFIX => qr/\.(?:private|key|pem)\z/;
45 19 Readonly my $DEFAULT_KEYDIR_NAME => 'dkim';
46 19 Readonly my $DEFAULT_SENDMAIL => '/usr/sbin/sendmail';
47 19 Readonly my $DOMAIN_SEPARATOR => qr/[\s,]+/;
48 19 Readonly my $DOMAIN_SYNTAX => qr/\A[A-Za-z0-9.-]+\z/;
49 # Both go into the signature header, and the selector names a key file too.
50 19 Readonly my $SELECTOR_SYNTAX => qr/\A[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*\z/;
51  
52 # The exit statuses of send(): sendmail's own, or ours when it never ran.
53 19 Readonly my $EXIT_ACCEPTED => 0;
54 19 Readonly my $EXIT_CANNOT_RUN => 1;
55  
56 # The syslog line. A missing value is logged as a dash so that every field
57 # is always present and the line can be split on spaces.
58 19 Readonly my $SYSLOG_IDENT => 'mail-dkim';
59 19 Readonly my $SYSLOG_OPTIONS => 'pid,ndelay';
60 19 Readonly my $SYSLOG_FACILITY => 'mail';
61 19 Readonly my $SYSLOG_LEVEL => 'info';
62 19 Readonly my $MISSING_VALUE => '-';
63 19 Readonly my @RECIPIENT_HEADERS => qw(To Cc Bcc);
64  
65 # sendmail options that take a value, either attached (-fuser) or as the next
66 # argument (-f user). Knowing them is what stops a value being taken for a
67 # recipient, or a letter inside a value being taken for a flag.
68 19 Readonly my $VALUE_OPTIONS => 'fBboprRVNLXAqFC';
69  
70 # Every sentence this module can say. An entry is a format with named
71 # placeholders, %{name}s or %{name}d, or a hash of such formats chosen by the
72 # arguments' "count" (zero, one, other) and/or "variant" (a gender or other
73 # context, alone or as "variant.count"). A language is added by passing a
74 # "messages" option to new(), which may be set from an Object::Configure file.
75 19 Readonly my %DEFAULT_MESSAGES => (
76 'key_unreadable' => 'Mail::Send::DKIM: no readable key at %{keyfile}s; sending %{domain}s unsigned',
77 'sign_failed' => 'Mail::Send::DKIM: cannot sign for %{domain}s (%{error}s); sending unsigned',
78 'key_too_small' => 'Mail::Send::DKIM: the key %{keyfile}s has %{bits}d bits, fewer than %{minimum}d; sending %{domain}s unsigned',
79 'bad_name' => 'Mail::Send::DKIM: cannot sign with the selector "%{selector}s" and the domain "%{signing}s"; sending %{domain}s unsigned',
80 'from_unsigned' => 'Mail::Send::DKIM: the signature would not cover From: (does the message start with a blank line?); sending %{domain}s unsigned',
81 'sendmail_failed' => 'Mail::Send::DKIM: cannot run %{sendmail}s: %{os_error}s',
82 'keydir_unreadable' => 'Mail::Send::DKIM: cannot read %{keydir}s: %{os_error}s',
83 'keys_ambiguous' => {
84 'one' => 'Mail::Send::DKIM: %{keydir}s holds %{count}d key; name the selector to choose one',
85 'other' => 'Mail::Send::DKIM: %{keydir}s holds %{count}d keys; name the selector to choose one',
86 },
87 'syslog_failed' => 'Mail::Send::DKIM: cannot write to syslog: %{error}s',
88 'bad_arguments' => 'Mail::Send::DKIM: the arguments of a message must be a hash reference, not %{type}s',
89 'unknown_message' => 'Mail::Send::DKIM: no message is defined for the key "%{key}s"',
90 'missing_argument' => 'Mail::Send::DKIM: the message "%{key}s" needs the argument "%{argument}s"',
91 );
92  
93 # The options new() accepts. Anything else - Object::Configure adds some of its
94 # own - is ignored rather than refused.
95 19 Readonly my %NEW_SCHEMA => (
96 'domains' => { 'type' => ['string', 'arrayref'], 'optional' => 1 },
97 'signing_domain' => { 'type' => 'string', 'optional' => 1 },
98 'keydir' => { 'type' => 'string', 'optional' => 1 },
99 'selector' => { 'type' => 'string', 'optional' => 1 },
100 'keyfile' => { 'type' => 'string', 'optional' => 1 },
101 'sendmail' => { 'type' => 'string', 'optional' => 1 },
102 'home' => { 'type' => 'string', 'optional' => 1 },
103 'messages' => { 'type' => 'hashref', 'optional' => 1 },
104 );
105  
106 =encoding utf-8
107  
108 =head1 NAME
109  
110 Mail::Send::DKIM - sign a message with DKIM and hand it to sendmail
111  
112 =head1 VERSION
113  
114 0.005.0
115  
116 =head1 SYNOPSIS
117  
118 use Mail::Send::DKIM;
119  
120 my $dkim = Mail::Send::DKIM->new(
121 domains => ['example.org'],
122 keydir => "$ENV{HOME}/dkim",
123 );
124  
125 my $signed = $dkim->sign($message);
126 $message = $signed if(defined($signed));
127  
128 exit($dkim->send($message, '-t', '-f', 'alerts@example.org'));
129  
130 More ways to use it:
131  
132 # 1. Settings from the environment (DKIM_DOMAINS, DKIM_KEYDIR, ...)
133 # This is how the mail-dkim program works.
134 my $dkim = Mail::Send::DKIM->new();
135  
136 # 2. One key file that you name yourself, for a test
137 my $dkim = Mail::Send::DKIM->new(
138 domains => 'example.org example.net',
139 keyfile => '/etc/dkim/2026.private',
140 );
141  
142 # 3. Sign and send, then write a line to the system log
143 my @sendmail_args = ('-t', '-f', 'alerts@example.org');
144 my $signed = $dkim->sign($message);
145 $message = $signed if(defined($signed));
146 if($dkim->send($message, @sendmail_args) == 0) {
147 $dkim->log_send($message, @sendmail_args);
148 }
149  
150 # 4. Only ask whose mail it is, or which key would be used
151 my $domain = Mail::Send::DKIM::from_domain($message);
152 my $selector = $dkim->selector();
153  
154 # 5. Warnings in your own words
155 my $dkim = Mail::Send::DKIM->new(
156 messages => { key_unreadable => 'No key at %{keyfile}s' },
157 );
158  
159 =head1 DESCRIPTION
160  
161 Signs a message with DKIM when its C<From:> domain is one this host signs for,
162 and hands it to sendmail with whatever arguments sendmail should have. The
163 signed form is C<rsa-sha256> with C<relaxed/relaxed> canonicalization (headers
164 and body), which is the shape receiving sites expect.
165  
166 The signature follows RFC 6376 and
167 L<RFC 8301|https://www.rfc-editor.org/rfc/rfc8301>. C<From:> is always signed, and is
168 oversigned (named once more than it appears), so that another cannot be added
169 without breaking the signature. The C<l=> tag is never used: the whole body is
170 signed. A key of fewer than 1024 bits is not used; 2048 bits or more is
171 recommended. The signature header is folded.
172  
173 The signature covers the message in the form DKIM defines, where every line
174 ends CRLF. What is handed to sendmail is the local form instead: LF line
175 endings, and no carriage return anywhere, whatever arrived. A CR would be data
176 to the MTA that keeps the message - Postfix and Exim both write the CRLF of
177 SMTP themselves - so a message that had travelled with CRLF in it would reach
178 the receiver with the CRs doubled and fail the signature it had just been given.
179  
180 Nothing here dies because a key is missing: signing either produces a signed
181 message or produces nothing and says why on standard error, so a caller can
182 always fall back to sending the message as it is.
183  
184 =head1 PLATFORMS
185  
186 Windows is not supported. L<Mail::DKIM> needs L<Crypt::OpenSSL::RSA>, and that
187 module and its prerequisites, L<Crypt::OpenSSL::Random> and
188 L<Crypt::OpenSSL::Bignum>, do not link on Windows: Strawberry Perl's static
189 OpenSSL needs the C<crypt32> library, which their F<Makefile.PL> files do not
190 ask for. F<Makefile.PL> stops with C<OS unsupported> there, rather than failing
191 part-way through the install.
192  
193 =head1 ENVIRONMENT
194  
195 B<DKIM_DOMAINS>, B<DKIM_SIGNING_DOMAIN>, B<DKIM_KEYDIR>, B<DKIM_SELECTOR>,
196 B<DKIM_KEYFILE> and B<SENDMAIL> are read by B<new> when the corresponding option is not given,
197 so the command line programs need no configuration of their own.
198  
199 B<new> also reads its options through L<Object::Configure>, so that how a
200 program is configured is kept apart from its code. An entry in a configuration
201 file, or an environment variable named after the class and the option, such as
202 C<Mail__Send__DKIM__selector> or C<Mail__Send__DKIM__sendmail>, B<overrides>
203 the option given to B<new>. The order, strongest first, is: what
204 L<Object::Configure> supplies; the option given to B<new>; the C<DKIM_*> or
205 C<SENDMAIL> variable; the built-in default.
206  
207 =head1 PROGRAMS
208  
209 The distribution is named after this module and installs five programs with
210 it, each with a page of its own: C<perldoc bin/mail-dkim>,
211 C<perldoc bin/dmarc-report.pl>, C<perldoc bin/dmarc-summary>,
212 C<perldoc bin/dmarc-check-mail.pl> and C<perldoc bin/dmarc-weekly.sh> in a
213 checkout, and the same pages as manual pages once installed.
214  
215 =over 4
216  
217 =item L<mail-dkim|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/mail-dkim>
218  
219 The front end to this module: a message on standard input is signed when its
220 C<From:> domain is one named in C<DKIM_DOMAINS>, and handed to sendmail(1) with
221 the arguments it was given. Put it where a script or a crontab calls sendmail
222 and the mail is signed without the script being changed. Its page has the
223 environment variables, the key layout and the exit status.
224  
225 =item L<dmarc-report|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/dmarc-report.pl>
226  
227 Reads a directory of DMARC aggregate reports and says who sent mail for each
228 domain, marking every source that is not an expected one (C<DMARC_EXPECTED>),
229 every expected one whose mail did not authenticate, and every message that was
230 quarantined or rejected by policy despite passing. The exit status is non-zero
231 when anything needs looking at. Its page has the options.
232  
233 =item L<dmarc-summary|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/dmarc-summary>
234  
235 The shorter reading of the same reports: a line per source address with its
236 DKIM and SPF verdicts, the disposition applied, whether the address is one of
237 ours and who owns it, over every report in F<~/Downloads>, plain, gzipped or zipped.
238 Where B<dmarc-report.pl> decides whether anything needs acting on and says so
239 in its exit status, this one is for reading.
240  
241 =item L<dmarc-weekly.sh|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/dmarc-weekly.sh>
242  
243 The cron wrapper around it: silent when the week is clean, a mail with the full
244 output when it is not, and the reports moved aside to an archive afterwards.
245 C<DRY_RUN=1> rehearses a run and C<--crontab> prints the line to paste into a
246 crontab; see L</A CRONTAB ENTRY> below.
247  
248 =item L<dmarc-check-mail.pl|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/dmarc-check-mail.pl>
249  
250 Sends one message, signed with this module, to a mailbox that can be read, so
251 that the C<Authentication-Results> header at the far end shows what receivers
252 make of this host's mail before the DMARC policy is tightened. C<--plain>
253 sends the same message unsigned, which is what a cron job without the module
254 looks like.
255  
256 =back
257  
258 The four DMARC programs are the reason the module exists: they report on the
259 mail it signs, and the weekly one sends its own report through it.
260  
261 =head1 METHODS
262  
263 =head2 B<new> %options
264  
265 A setting from a L<Object::Configure> configuration file or variable overrides
266 the option given here; see L</ENVIRONMENT>. The defaults below apply when
267 neither supplies the option.
268  
269 =over 4
270  
271 =item C<domains>
272  
273 The domains to sign for, either an array reference or a string of them
274 separated by commas or spaces. Defaults to C<$ENV{DKIM_DOMAINS}>. A message
275 from any other domain is left alone.
276  
277 =item C<signing_domain>
278  
279 The domain put in the signature (its C<d=> tag), when it is not the domain in
280 the C<From:> header - for a host that signs with the key of a parent or
281 organisational domain, say. Defaults to C<$ENV{DKIM_SIGNING_DOMAIN}>; with
282 neither set, the C<From:> domain is used. Which messages are signed is still
283 decided by B<domains>, which is matched against the C<From:> domain. The
284 receiver finds the public key at
285 F<< <selector>._domainkey.<signing_domain> >>, and DMARC accepts the signature
286 only if that domain aligns with the C<From:> domain.
287  
288 =item C<keydir>
289  
290 Where the private keys are. Defaults to C<$ENV{DKIM_KEYDIR}>, or F<~/dkim>.
291 The value is used as it stands: a relative path is taken from the working
292 directory, and C<~> is not expanded - the shell does that, and only when the
293 assignment is written unquoted.
294  
295 =item C<selector>
296  
297 The selector the key is published under, which names the key file
298 F<< <keydir>/<selector>.private >>. Defaults to C<$ENV{DKIM_SELECTOR}>; with
299 neither set, the key file's own name is the selector when B<keyfile> is given,
300 and otherwise the only F<*.private> file in B<keydir> is used and its name is
301 the selector.
302  
303 =item C<keyfile>
304  
305 The private key to sign with, when it does not live at
306 F<< <keydir>/<selector>.private >> - a tester given one key to try, for
307 instance. Defaults to C<$ENV{DKIM_KEYFILE}>. It is used as it stands, and
308 the selector comes from its name unless one is given.
309  
310 =item C<sendmail>
311  
312 The program B<send> hands the message to. Defaults to C<$ENV{SENDMAIL}>, or
313 F</usr/sbin/sendmail>.
314  
315 =item C<home>
316  
317 The directory the default B<keydir> is made from, as F<< <home>/dkim >>.
318 Defaults to C<$ENV{HOME}>, then the home directory in the password file entry,
319 then the current directory. It matters only when B<keydir> is not given.
320  
321 =item C<messages>
322  
323 A hash reference of message formats that replace or add to the ones this
324 module speaks with, keyed by message key, for a language other than English or
325 wording of your own. See B<i18n> for the format. Because B<new> reads its
326 options through L<Object::Configure>, the same hash can come from a
327 configuration file.
328  
329 =back
330  
331 =head3 PURPOSE
332  
333 Builds the signer. No file is read and no program is run here, so a mistake
334 in B<keydir> or B<keyfile> shows when a message is signed, not when the object
335 is made.
336  
337 =head3 EXAMPLE
338  
339 # Everything from the environment: DKIM_DOMAINS, DKIM_KEYDIR, ...
340 my $dkim = Mail::Send::DKIM->new();
341  
342 # Everything given, a list of domains, a named key and a test sendmail
343 my $dkim = Mail::Send::DKIM->new(
344 domains => 'example.org, example.net',
345 keyfile => '/etc/dkim/2026.private',
346 sendmail => '/usr/local/bin/capture-sendmail',
347 );
348  
349 # A message in another language
350 my $dkim = Mail::Send::DKIM->new(
351 messages => { sendmail_failed => 'sendmail %{sendmail}s: %{os_error}s' },
352 );
353  
354 =head3 API SPECIFICATION
355  
356 =head4 Input (Params::Validate::Strict)
357  
358 {
359 domains => { type => ['string', 'arrayref'], optional => 1 },
360 signing_domain => { type => 'string', optional => 1 },
361 keydir => { type => 'string', optional => 1 },
362 selector => { type => 'string', optional => 1 },
363 keyfile => { type => 'string', optional => 1 },
364 sendmail => { type => 'string', optional => 1 },
365 home => { type => 'string', optional => 1 },
366 messages => { type => 'hashref', optional => 1 },
367 }
368  
369 Options not listed are ignored. The options may be given as a hash or as a
370 hash reference.
371  
372 =head4 Output (Return::Set)
373  
374 { type => 'object', isa => 'Mail::Send::DKIM' }
375  
376 =head3 MESSAGES
377  
378 An option of the wrong type is refused with the message of
379 L<Params::Validate::Strict>, which names the option. Nothing else is said.
380  
381 =head3 PSEUDOCODE
382  
383 options = get_params(args)
384 options = Object::Configure(options) # config files, environment: these win
385 options = validate(options, NEW_SCHEMA) # croak on a wrong type
386 home = options.home or $HOME or passwd entry or "."
387 domains = split(options.domains or $DKIM_DOMAINS), lower-cased, as a set
388 messages = defaults overlaid with options.messages
389 return object(domains, keydir, selector, keyfile, sendmail, messages)
390  
391 =cut
392  
393 sub new
394 175 ▶{
Subroutine new: called CC=14 SCAR=26.4
Pod documented
395 175 my $class = shift;
396  
397 # Handle hash or hashref arguments
398 175 ▶ my $params = Params::Get::get_params(undef, \@_) // {};
Condition100%2/2
Params::Get::get_params(undef, \@_) // {}
l!l
16014
MC/DC100%1/1
Params::Get::get_params(undef, \@_) // {}
Params::Get::get_params(undef, \@_)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
399  
400 # Configuration files and the environment override what the code passes, so
401 # that a site can be configured without editing its programs.
402 174 $params = Object::Configure::configure($class, $params);
403 173 $params = validate_strict(
404 'schema' => \%NEW_SCHEMA,
405 'input' => $params,
406 'unknown_parameter_handler' => 'ignore',
407 );
408  
409 167 ▶ my $home = $params->{'home'} || $ENV{'HOME'} || (getpwuid($<))[7] || '.';
Condition62%5/8
$params->{'home'} || $ENV{'HOME'} || (getpwuid $<)[7] || '.'
l!l
1670
$params->{"home"} or $ENV{"HOME"} or (getpwuid $<)[7]
l!l&&r!l&&!r
16520
$params->{"home"} or $ENV{"HOME"}
l!l&&r!l&&!r
01652
MC/DC0%0/3
$params->{'home'} || $ENV{'HOME'} || (getpwuid $<)[7] || '.'
$params->{"home"} $ENV{"HOME"} (getpwuid $<)[7]
Truth table50%2/4
A or B or C
A= $params->{"home"}B= $ENV{"HOME"}C= (getpwuid $<)[7]
ABCresult
1XX1
01X1
0011
0000
410  
411 my $self = {
412 'domains' => _domain_set($params->{'domains'} // $ENV{'DKIM_DOMAINS'}),
413 'signing_domain' => _signing_domain($params->{'signing_domain'} // $ENV{'DKIM_SIGNING_DOMAIN'}),
414 'keydir' => $params->{'keydir'} // $ENV{'DKIM_KEYDIR'} // "$home/$DEFAULT_KEYDIR_NAME",
415 'selector' => $params->{'selector'} // $ENV{'DKIM_SELECTOR'},
416 'keyfile' => $params->{'keyfile'} // $ENV{'DKIM_KEYFILE'},
417 'sendmail' => $params->{'sendmail'} // $ENV{'SENDMAIL'} // $DEFAULT_SENDMAIL,
418 # Shallow overlay: a caller's entry replaces the default one whole.
419 167 ▶ 'messages' => { %DEFAULT_MESSAGES, %{ $params->{'messages'} // {} } },
Condition100%25/25
$params->{"domains"} // $ENV{"DKIM_DOMAINS"}
l!l&&r!l&&!r
3214121
$params->{"signing_domain"} // $ENV{"DKIM_SIGNING_DOMAIN"}
l!l&&r!l&&!r
32162
($params->{"keydir"} // $ENV{"DKIM_KEYDIR"}) // "$home/$DEFAULT_KEYDIR_NAME"
l!l
14225
$params->{"keydir"} // $ENV{"DKIM_KEYDIR"}
l!l&&r!l&&!r
135725
$params->{"selector"} // $ENV{"DKIM_SELECTOR"}
l!l&&r!l&&!r
113153
$params->{"keyfile"} // $ENV{"DKIM_KEYFILE"}
l!l&&r!l&&!r
212144
($params->{"sendmail"} // $ENV{"SENDMAIL"}) // $DEFAULT_SENDMAIL
l!l&&r!l&&!r
381236
$params->{"sendmail"} // $ENV{"SENDMAIL"}
l!l&&r!l&&!r
317129
$params->{"messages"} // {}
l!l
6161
MC/DC100%2/2
$params->{"domains"} // $ENV{"DKIM_DOMAINS"}
$params->{"domains"} $ENV{"DKIM_DOMAINS"}
MC/DC100%2/2
$params->{"signing_domain"} // $ENV{"DKIM_SIGNING_DOMAIN"}
$params->{"signing_domain"} $ENV{"DKIM_SIGNING_DOMAIN"}
MC/DC100%2/2
($params->{"keydir"} // $ENV{"DKIM_KEYDIR"}) // "$home/$DEFAULT_KEYDIR_NAME"
$params->{"keydir"} $ENV{"DKIM_KEYDIR"}
MC/DC100%2/2
$params->{"selector"} // $ENV{"DKIM_SELECTOR"}
$params->{"selector"} $ENV{"DKIM_SELECTOR"}
MC/DC100%2/2
$params->{"keyfile"} // $ENV{"DKIM_KEYFILE"}
$params->{"keyfile"} $ENV{"DKIM_KEYFILE"}
MC/DC100%3/3
($params->{"sendmail"} // $ENV{"SENDMAIL"}) // $DEFAULT_SENDMAIL
$params->{"sendmail"} $ENV{"SENDMAIL"} $DEFAULT_SENDMAIL
MC/DC100%1/1
$params->{"messages"} // {}
$params->{"messages"}
Truth table100%3/3
A // B
A= $params->{"domains"}B= $ENV{"DKIM_DOMAINS"}
ABresult
1X1
011
000
Truth table100%3/3
A // B
A= $params->{"signing_domain"}B= $ENV{"DKIM_SIGNING_DOMAIN"}
ABresult
1X1
011
000
Truth table100%3/3
A // B
A= $params->{"keydir"}B= $ENV{"DKIM_KEYDIR"}
ABresult
1X1
011
000
Truth table100%3/3
A // B
A= $params->{"selector"}B= $ENV{"DKIM_SELECTOR"}
ABresult
1X1
011
000
Truth table100%3/3
A // B
A= $params->{"keyfile"}B= $ENV{"DKIM_KEYFILE"}
ABresult
1X1
011
000
Truth table100%4/4
A // B // C
A= $params->{"sendmail"}B= $ENV{"SENDMAIL"}C= $DEFAULT_SENDMAIL
ABCresult
1XX1
01X1
0011
0000
Truth table100%2/2
A
A= $params->{"messages"}
Aresult
11
00
420 };
421  
422 167 return bless($self, $class);
423 }
424  
425 =head2 B<sign> $message
426  
427 Returns the message with a C<DKIM-Signature> header added, or C<undef> when
428 there is nothing to do or nothing that can be done: the domain is not one of
429 B<domains>, there is no C<From:> header, no key can be found or read, the key
430 has fewer than 1024 bits, the signature would not cover C<From:>, or the signer
431 failed. The reasons are warnings on standard error; the message itself
432 is never altered in the undef case, so the caller sends it unchanged.
433 Carriage returns are folded to LF on the way, so what comes back is in the
434 local form.
435  
436 =head3 PURPOSE
437  
438 Signs the message when, and only when, a key for its C<From:> domain can be
439 found and used. Nothing is raised for a failure to sign: the caller sends the
440 message as it is.
441  
442 The selector must be letters, digits, hyphens and underscores, in one or more
443 parts separated by dots, and the domain that goes in the signature must be
444 letters, digits, hyphens and dots. Otherwise nothing is signed.
445  
446 The key must be a regular file that can be read. A directory whose name ends
447 in F<.private> is not a key, and is reported as one that cannot be read.
448  
449 A message that starts with a blank line has no headers as far as DKIM is
450 concerned, whatever follows, so it is not signed.
451  
452 =head3 EXAMPLE
453  
454 my $signed = $dkim->sign($message);
455 $message = $signed if(defined($signed));
456  
457 =head3 API SPECIFICATION
458  
459 =head4 Input (Params::Validate::Strict)
460  
461 { message => { type => 'string' } }
462  
463 An undefined message is treated as an empty one, which has no C<From:>. It
464 may be given positionally or as C<< message => $text >>.
465  
466 =head4 Output (Return::Set)
467  
468 { type => 'string', optional => 1 }
469  
470 The signed message in the local form, or C<undef>.
471  
472 =head3 MESSAGES
473  
474 Message key Text Meaning and resolution
475 key_unreadable no readable key at FILE; sending DOMAIN The key file is absent or not
476 unsigned readable: fix the path or the mode.
477 sign_failed cannot sign for DOMAIN (REASON); ... Mail::DKIM refused the key or
478 the message: see REASON.
479 key_too_small the key FILE has N bits, fewer than 1024 RFC 8301 forbids it: make a
480 key of 2048 bits and publish it.
481 bad_name cannot sign with the selector S and the Correct the selector or the
482 domain D signing_domain.
483 from_unsigned the signature would not cover From: The headers do not start the
484 message: remove the blank line.
485 keydir_unreadable, keys_ambiguous As for selector, below.
486  
487 Each is a warning, and the return is C<undef>.
488  
489 =cut
490  
491 sub sign
492 69 ▶{
Subroutine sign: called CC=4 SCAR=13.9
Pod documented
493 69 my $self = shift;
494  
495 69 my $params = Params::Get::get_params('message', \@_);
496 68 ▶ my $message = validate_strict('schema' => { 'message' => { 'type' => 'string' } }, 'input' => $params)->{'message'} // '';
Condition100%2/2
validate_strict("schema", {"message", {"type", "string"}}, "input", $params)->{"message"} // ""
l!l
622
MC/DC100%1/1
validate_strict("schema", {"message", {"type", "string"}}, "input", $params)->{"message"} // ""
validate_strict("schema", {"message", {"type", "string"}}, "input", $params)->{"message"}
Truth table100%2/2
A
A= validate_strict("schema", {"message", {"type", "string"}}, "input", $params)->{"message"}
Aresult
11
00
497  
498 64 my $domain = from_domain($message);
499  
500 # Only a domain this host signs for is worth looking for a key.
501 64 ▶ return (defined($domain) && $self->{'domains'}->{$domain}) ? $self->_sign_for($domain, $message) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $domain && $self->{'domains'}{$domain} ? : 31 33 64
Condition100%3/3
defined $domain and $self->{"domains"}{$domain}
!ll&&!rl&&r
191431
MC/DC100%2/2
defined $domain and $self->{"domains"}{$domain}
defined $domain $self->{"domains"}{$domain}
Truth table100%3/3
A and B
A= defined $domainB= $self->{"domains"}{$domain}
ABresult
0X0
100
111
502 }
503  
504 # Purpose: Find the key for a domain we sign for and sign with it.
505 # Entry criteria: $domain is a lower-case domain in the signing set; $message
506 # is the message as it arrived.
507 # Exit status: The signed message in the local form, or undef - after a
508 # warning that says why - when there is no usable key.
509 # Side effects: Reads the key file; may warn.
510 35 ▶sub _sign_for :Private
Subroutine _sign_for: called CC=8 SCAR=20.8
511 {
512 35 my ($self, $domain, $message) = @_;
513  
514 35 my $selector = $self->selector();
515 35 my $signed;
516  
517 35 ▶ if(defined($selector)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $selector) 30 5 35
518 # A key file named outright needs neither the directory nor the naming
519 # convention; otherwise the key is <keydir>/<selector>.private.
520 30 ▶ my $keyfile = $self->{'keyfile'} // "$self->{'keydir'}/$selector$KEY_SUFFIX";
Condition100%2/2
$self->{"keyfile"} // qq[$self->{"keydir"}/$selector$KEY_SUFFIX]
l!l
822
MC/DC100%1/1
$self->{"keyfile"} // qq[$self->{"keydir"}/$selector$KEY_SUFFIX]
$self->{"keyfile"}
Truth table100%2/2
A
A= $self->{"keyfile"}
Aresult
11
00
521  
522 # A directory is readable too, but it is not a key.
523 30 ▶ if(-f $keyfile && -r $keyfile) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $keyfile and -r $keyfile) { } 26 4 30
Condition100%3/3
-f $keyfile and -r $keyfile
!ll&&!rl&&r
3126
MC/DC100%2/2
-f $keyfile and -r $keyfile
-f $keyfile -r $keyfile
Truth table100%3/3
A and B
A= -f $keyfileB= -r $keyfile
ABresult
0X0
100
111
524 26 ▶ my $signing = $self->{'signing_domain'} // $domain;
Condition66%2/3
$self->{"signing_domain"} // $domain
l!l&&r!l&&!r
3230
MC/DC0%0/2
$self->{"signing_domain"} // $domain
$self->{"signing_domain"} $domain
Truth table66%2/3
A // B
A= $self->{"signing_domain"}B= $domain
ABresult
1X1
011
000
525 26 ▶ if(($signing =~ $DOMAIN_SYNTAX) && ($selector =~ $SELECTOR_SYNTAX)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($signing =~ /$DOMAIN_SYNTAX/ and $selector =~ /$SELECTOR_SYNTAX/) { } 23 3 26
Condition100%3/3
$signing =~ /$DOMAIN_SYNTAX/ and $selector =~ /$SELECTOR_SYNTAX/
!ll&&!rl&&r
1223
MC/DC100%2/2
$signing =~ /$DOMAIN_SYNTAX/ and $selector =~ /$SELECTOR_SYNTAX/
$signing =~ /$DOMAIN_SYNTAX/ $selector =~ /$SELECTOR_SYNTAX/
Truth table100%3/3
A and B
A= $signing =~ /$DOMAIN_SYNTAX/B= $selector =~ /$SELECTOR_SYNTAX/
ABresult
0X0
100
111
526 23 $signed = $self->_dkim_sign($signing, $selector, $keyfile, $message);
527 } else {
528 3 $self->_say('bad_name', { 'selector' => $selector, 'signing' => $signing, 'domain' => $domain });
529 }
530 } else {
531 4 $self->_say('key_unreadable', { 'keyfile' => $keyfile, 'domain' => $domain });
532 }
533 }
534  
535 35 return $signed;
536 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
537  
538 # Purpose: Make the DKIM signature and put it on the front of the message.
539 # Entry criteria: $keyfile is readable; $selector and $domain are not empty.
540 # Exit status: The signed message in the local form, or undef after a warning
541 # when Mail::DKIM could not sign (a key it cannot load, say), the
542 # From: header was not covered, or the key is too small.
543 # Side effects: May warn. Nothing is raised: a failure to sign must not
544 # become a failure to deliver.
545 33 ▶sub _dkim_sign :Private
Subroutine _dkim_sign: called CC=7 SCAR=19.5
546 {
547 33 my ($self, $domain, $selector, $keyfile, $message) = @_;
548  
549 # eval sets $@, which belongs to the caller.
550 33 local $@ = '';
551  
552 # DKIM hashes the message in the form it travels in, where every line
553 # ends CRLF, so the signature is made over a CRLF copy of what arrived,
554 # while what is returned has the local line endings.
555 33 my $local = _local($message);
556 33 (my $wire = $local) =~ s/\n/\r\n/g;
557  
558 33 my ($signature, $header, %signed_headers, $bits);
559 33 my $ok = eval {
560 33 my $signer = Mail::DKIM::Signer->new(
561 'Algorithm' => $ALGORITHM,
562 'Method' => $CANONICALIZATION,
563 'Domain' => $domain,
564 'Selector' => $selector,
565 'KeyFile' => $keyfile,
566 # Every From: there is, and one more, so that none can be added.
567 # A new hash each time, as the signer changes it.
568 'ExtendedHeaders' => { 'from' => '+' },
569 );
570 30 $signer->PRINT($wire);
571 29 $signer->CLOSE();
572  
573 28 $signature = $signer->signature();
574 28 $header = _local($signature->as_string());
575 27 $signed_headers{$_}++ foreach($signature->headerlist());
576 # An RSA signature is as long as the key it was made with.
577 27 $bits = 8 * length(decode_base64($signature->data()));
578 27 1;
579 };
580  
581 33 my $signed;
582 33 ▶ if(!$ok) {
Branch: 3 branches
BranchTrueFalseTotal
if (not $ok) { } 6 27 33
elsif (($signed_headers{'from'} // 0) < 2) { } 3 24 27
elsif ($bits < $MINIMUM_KEY_BITS) { } 2 22 24
583 6 ▶ $self->_say('sign_failed', { 'domain' => $domain, 'error' => _trim_error($@ || 'unknown error') });
Condition50%1/2
$@ || 'unknown error'
l!l
60
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
584 ▶ } elsif(($signed_headers{'from'} // 0) < 2) {
Condition50%1/2
$signed_headers{"from"} // 0
l!l
270
MC/DC0%0/1
$signed_headers{"from"} // 0
$signed_headers{"from"}
Truth table50%1/2
A
A= $signed_headers{"from"}
Aresult
11
00
585 # The one extra name is there even when no From: header was seen.
586 3 $self->_say('from_unsigned', { 'domain' => $domain });
587 } elsif($bits < $MINIMUM_KEY_BITS) {
588 2 $self->_say('key_too_small', { 'keyfile' => $keyfile, 'bits' => $bits, 'minimum' => $MINIMUM_KEY_BITS, 'domain' => $domain });
589 } else {
590 22 $signed = "$header\n$local";
591 }
592  
593 33 return $signed;
594 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
595  
596 =head2 B<send> $message, @arguments
597  
598 Pipes the message to B<sendmail> with the arguments given - C<-t>, C<-f> and
599 the rest are sendmail's own - and returns C<0> when sendmail accepted the
600 message, and sendmail's exit status when it did not. It returns C<1> when
601 sendmail cannot be run at all, when it is killed by a signal, and when it
602 exits C<0> without the whole message having been written to it. An undefined
603 message is sent as an empty one. The message is normalised to LF first, so nothing that arrived
604 with CRLF - signed or passed through unsigned - carries a carriage return to
605 the MTA.
606  
607 =head3 PURPOSE
608  
609 Delivers the message to the local MTA and reports what the MTA said.
610  
611 A B<sendmail> that is an empty string is the same failure as a program that is
612 not there: the return is C<1> and the message is C<sendmail_failed>. The
613 caller's C<$@>, C<$?> and C<$SIG{PIPE}> are the same after the call as before
614 it.
615  
616 =head3 EXAMPLE
617  
618 my $status = $dkim->send($message, '-t', '-f', 'alerts@example.org');
619 exit($status);
620  
621 =head3 API SPECIFICATION
622  
623 =head4 Input (Params::Validate::Strict)
624  
625 {
626 message => { type => 'string' },
627 arguments => { type => 'arrayref', optional => 1 }, # the rest of @_
628 }
629  
630 =head4 Output (Return::Set)
631  
632 { type => 'integer', min => 0, max => 255 }
633  
634 =head3 MESSAGES
635  
636 Message key Meaning and resolution
637 sendmail_failed The sendmail program could not be started (not found,
638 not executable): fix the sendmail option or SENDMAIL.
639 The return is 1.
640  
641 A sendmail that exits before it has read the whole message does not stop the
642 caller with SIGPIPE: its exit status is returned.
643  
644 =head3 PSEUDOCODE
645  
646 ignore SIGPIPE's default action (a handler, so sendmail does not inherit it)
647 open a pipe to sendmail with the arguments, as a list so no shell is involved
648 if that fails: warn sendmail_failed, return 1
649 write the local form of the message, then close the pipe
650 if the write and the close both succeeded: return 0
651 return sendmail's exit status, or 1 when that would have been 0
652  
653 =cut
654  
655 # send() is the documented name of this method, though perl has a builtin of that
656 # name: the builtin is for sockets, which this package does not use.
657 sub send ## no critic (Subroutines::ProhibitBuiltinHomonyms)
658 43 ▶{
Subroutine send: called CC=8 SCAR=20.8
Pod documented
659 43 my ($self, $message, @args) = @_;
660  
661 # A sendmail that cannot be run, or that refuses the message, is a status
662 # for the caller, not an exception, so autodie stands aside for the pipe.
663 19 ▶ no autodie qw(open close);
Subroutine BEGIN: called CC=1 SCAR=0.0
664 # perl would add its own "Can't exec" to the warning given below.
665 19 ▶ no warnings 'exec';
Subroutine BEGIN: called CC=1 SCAR=0.0
666 # A sendmail that refuses a message may exit before reading it, and the
667 # write would then kill us with SIGPIPE before its status could be read.
668 # A handler, not IGNORE: an ignored signal is also ignored by the child.
669 43 ▶ local $SIG{'PIPE'} = sub { };
Subroutine __ANON__: called CC=1 SCAR=0.0
670 # close() leaves sendmail's wait status in $?, which belongs to the caller.
671 43 local $? = 0;
672  
673 43 my $status = $EXIT_CANNOT_RUN;
674  
675 # An empty name would make perl complain about the open itself, not about the program.
676 43 ▶ if(length($self->{'sendmail'}) && open(my $sendmail, '|-', $self->{'sendmail'}, @args)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{'sendmail'} and open my $sendmail, '|-', $self->{'sendmail'}, @args) { } 33 10 43
Condition100%3/3
length $self->{"sendmail"} and open my $sendmail, "|-", $self->{"sendmail"}, @args
!ll&&!rl&&r
1933
MC/DC100%2/2
length $self->{"sendmail"} and open my $sendmail, "|-", $self->{"sendmail"}, @args
length $self->{"sendmail"} open my $sendmail, "|-", $self->{"sendmail"}, @args
Truth table100%3/3
A and B
A= length $self->{"sendmail"}B= open my $sendmail, "|-", $self->{"sendmail"}, @args
ABresult
0X0
100
111
677 # Nothing may be left in the buffer for close() to write: if sendmail
678 # has gone, that write fails and $? becomes -1, not its wait status.
679 33 $sendmail->autoflush(1);
680 33 ▶ my $written = print {$sendmail} _local($message // '');
Condition100%2/2
$message // ""
l!l
321
MC/DC100%1/1
$message // ""
$message
Truth table100%2/2
A
A= $message
Aresult
11
00
681  
682 # close() waits for sendmail; its exit status is in $? afterwards.
683 33 ▶ $status = close($sendmail) ? ($written ? $EXIT_ACCEPTED : $EXIT_CANNOT_RUN) : (($? >> 8) || $EXIT_CANNOT_RUN);
Branch: 2 branches
BranchTrueFalseTotal
close $sendmail ? : 26 7 33
$written ? : 26 0 26
Condition66%2/3
$? >> 8 or $EXIT_CANNOT_RUN
l!l&&r!l&&!r
520
MC/DC0%0/2
$? >> 8 or $EXIT_CANNOT_RUN
$? >> 8 $EXIT_CANNOT_RUN
Truth table66%2/3
A or B
A= $? >> 8B= $EXIT_CANNOT_RUN
ABresult
1X1
011
000
684 } else {
685 10 ▶ local $! = ENOENT unless(length($self->{'sendmail'}));
Branch: 1 branch
BranchTrueFalseTotal
unless length $self->{"sendmail"} 1 9 10
686 10 $self->_say('sendmail_failed', { 'sendmail' => $self->{'sendmail'}, 'os_error' => "$!" });
687 }
688  
689 43 return $status;
690 }
691  
692 =head2 B<log_send> $message, @arguments
693  
694 Records in syslog, under the identity C<mail-dkim> and the C<mail> facility,
695 the sender, the recipients and the subject of a message that has been sent.
696 The arguments are those given to B<send>. The sender is the address after
697 C<-f> when there is one, and the address in the C<From:> header otherwise. The
698 recipients are the arguments that are not options and, when C<-t> was given,
699 the addresses in the C<To:>, C<Cc:> and C<Bcc:> headers too. A value that is
700 missing is logged as C<->, and control characters in the subject are replaced
701 by spaces so that a message cannot forge a log line.
702  
703 Returns true when the line was written. Logging never stands between a message
704 and its recipient: a syslog that cannot be reached is a warning, and a false
705 return.
706  
707 =head3 PURPOSE
708  
709 Leaves a trace, in the system log, of every message that was passed on.
710  
711 The arguments are read the way sendmail reads them. These options take a
712 value, which is the rest of the argument or else the next argument, and the
713 value is never a recipient: C<-f -F -o -b -p -r -R -V -N -L -X -A -q -C -B>.
714 Only C<-f> is used. A C<-f> with an empty value is a null sender, and is
715 logged as C<->. C<-t> counts when it is alone or in a group of flags
716 (C<-ti>), but not when it is inside a value, as in C<-FNigelTest>, and not in
717 C<-bt>. An empty argument names nobody. The members of an empty group, such
718 as C<undisclosed-recipients:;>, are not recipients.
719  
720 =head3 EXAMPLE
721  
722 $dkim->log_send($message, '-t', '-f', 'alerts@example.org')
723 if($dkim->send($message, '-t', '-f', 'alerts@example.org') == 0);
724  
725 =head3 API SPECIFICATION
726  
727 =head4 Input (Params::Validate::Strict)
728  
729 {
730 message => { type => 'string' },
731 arguments => { type => 'arrayref', optional => 1 },
732 }
733  
734 =head4 Output (Return::Set)
735  
736 { type => 'boolean' }
737  
738 =head3 MESSAGES
739  
740 Message key Meaning and resolution
741 syslog_failed openlog or syslog failed: check that a syslog daemon is
742 running and its socket is reachable. The return is 0.
743  
744 =head3 PSEUDOCODE
745  
746 parse the arguments into (sender, recipients, whether -t was given), where an
747 option that takes a value, attached or separate, never yields a recipient
748 parse the headers of the message once
749 sender = the -f value, else the first address of From
750 if -t was given: add the addresses of To, Cc and Bcc to the recipients
751 subject = the Subject, or "-"
752 make the line, replace control characters by spaces
753 write it to syslog; if that fails, warn syslog_failed and return 0
754 return 1
755  
756 =cut
757  
758 sub log_send
759 48 ▶{
Subroutine log_send: called CC=9 SCAR=22.0
Pod documented
760 48 my ($self, $message, @args) = @_;
761  
762 48 my $parsed = _parse_sendmail_args(\@args);
763 48 ▶ my $headers = _parse_headers($message // '');
Condition100%2/2
$message // ""
l!l
471
MC/DC100%1/1
$message // ""
$message
Truth table100%2/2
A
A= $message
Aresult
11
00
764  
765 48 my @recipients = @{ $parsed->{'recipients'} };
766 # With -t sendmail reads the recipients from the headers as well.
767 48 ▶ push(@recipients, map { @{ _addresses($headers->{lc($_)}) } } @RECIPIENT_HEADERS) if($parsed->{'reads_headers'});
Branch: 1 branch
BranchTrueFalseTotal
if $parsed->{"reads_headers"} 14 34 48
768  
769 48 my $subject = $headers->{'subject'};
770 48 ▶ $subject = $MISSING_VALUE unless(defined($subject) && length($subject));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $subject and length $subject 19 29 48
Condition100%3/3
defined $subject and length $subject
!ll&&!rl&&r
18129
MC/DC100%2/2
defined $subject and length $subject
defined $subject length $subject
Truth table100%3/3
A and B
A= defined $subjectB= length $subject
ABresult
0X0
100
111
771  
772 # -f wins over the From: header, and an empty -f (a bounce) stays empty.
773 48 ▶ my $sender = $parsed->{'sender'} // _addresses($headers->{'from'})->[0];
Condition100%3/3
$parsed->{"sender"} // _addresses($headers->{"from"})->[0]
l!l&&r!l&&!r
11343
MC/DC100%2/2
$parsed->{"sender"} // _addresses($headers->{"from"})->[0]
$parsed->{"sender"} _addresses($headers->{"from"})->[0]
Truth table100%3/3
A // B
A= $parsed->{"sender"}B= _addresses($headers->{"from"})->[0]
ABresult
1X1
011
000
774  
775 48 ▶ my $line = sprintf('sender=%s recipient=%s subject=%s',
Branch: 1 branch
BranchTrueFalseTotal
@recipients ? : 33 15 48
Condition66%2/3
$sender || $MISSING_VALUE
l!l&&r!l&&!r
4440
MC/DC0%0/2
$sender || $MISSING_VALUE
$sender $MISSING_VALUE
Truth table66%2/3
A || B
A= $senderB= $MISSING_VALUE
ABresult
1X1
011
000
776 $sender || $MISSING_VALUE,
777 @recipients ? join(',', @recipients) : $MISSING_VALUE,
778 $subject);
779  
780 # The subject and the addresses come from the message, so a line break in
781 # any of them would otherwise let it forge a second log line.
782 48 $line =~ s/[[:cntrl:]]/ /g;
783  
784 48 ▶ return $self->_write_syslog($line) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->_write_syslog($line) ? : 44 4 48
785 }
786  
787 # Purpose: Split the arguments sendmail was given into what the log needs.
788 # Entry criteria: $args is an array reference of the arguments, as given.
789 # Exit status: A hash reference: sender (the -f value, or absent),
790 # recipients (array reference), reads_headers (true for -t).
791 # Side effects: None.
792 74 ▶sub _parse_sendmail_args :Private
Subroutine _parse_sendmail_args: called CC=11 SCAR=24.0
793 {
794 74 my $args = shift;
795  
796 74 my %parsed = ('recipients' => []);
797 # The letter of an option that is still waiting for its value.
798 74 my $pending;
799  
800 74 foreach my $arg (@{$args}) {
801 10111 ▶ if(defined($pending)) {
Branch: 5 branches
BranchTrueFalseTotal
if (defined $pending) { } 15 10096 10111
elsif ($arg eq '--') { } 3 10093 10096
elsif ($arg =~ /\A-([$VALUE_OPTIONS])(.*)\z/s) { } 33 10060 10093
elsif ($arg =~ /\A-(.*)\z/s) { } 21 10039 10060
elsif (length $arg) { } 10036 3 10039
802 # The value of -f is the sender; the others are not logged.
803 15 ▶ $parsed{'sender'} = $arg if($pending eq 'f');
Branch: 1 branch
BranchTrueFalseTotal
if $pending eq "f" 12 3 15
804 15 undef($pending);
805 } elsif($arg eq '--') {
806 3 next;
807 } elsif($arg =~ /\A-([$VALUE_OPTIONS])(.*)\z/s) {
808 # Like getopt, the rest of the argument is the value when there is any.
809 33 my ($letter, $attached) = ($1, $2);
810 33 ▶ if(length($attached)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $attached) { } 16 17 33
811 16 ▶ $parsed{'sender'} = $attached if($letter eq 'f');
Branch: 1 branch
BranchTrueFalseTotal
if $letter eq "f" 7 9 16
812 } else {
813 17 $pending = $letter;
814 }
815 } elsif($arg =~ /\A-(.*)\z/s) {
816 # A cluster of flags, such as -ti, none of which takes a value.
817 21 ▶ $parsed{'reads_headers'} = 1 if($1 =~ /t/);
Branch: 1 branch
BranchTrueFalseTotal
if $1 =~ /t/ 18 3 21
818 } elsif(length($arg)) {
819 # An empty argument names nobody.
820 10036 push(@{ $parsed{'recipients'} }, $arg);
821 }
822 }
823  
824 74 return \%parsed;
825 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
826  
827 # Purpose: Send one line to syslog.
828 # Entry criteria: $line holds no control characters.
829 # Exit status: True when syslog took the line, false - after a warning -
830 # when it could not be reached.
831 # Side effects: Opens and closes the syslog connection.
832 30 ▶sub _write_syslog :Private
Subroutine _write_syslog: called CC=2 SCAR=6.9
833 {
834 30 my ($self, $line) = @_;
835  
836 # eval sets $@, which belongs to the caller.
837 30 local $@ = '';
838  
839 30 my $written = eval {
840 30 Sys::Syslog::openlog($SYSLOG_IDENT, $SYSLOG_OPTIONS, $SYSLOG_FACILITY);
841 28 Sys::Syslog::syslog($SYSLOG_LEVEL, '%s', $line);
842 27 1;
843 };
844 30 my $error = $@;
845  
846 # The connection is closed whether or not the line went in, and a failure
847 # to close it must not turn a line that was written into a failure.
848 30 eval { Sys::Syslog::closelog(); 1 }; ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
849  
850 30 ▶ $self->_say('syslog_failed', { 'error' => _trim_error($error) }) unless($written);
Branch: 1 branch
BranchTrueFalseTotal
unless $written 3 27 30
851  
852 30 return $written;
853 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
854  
855 # Purpose: Read the header block of a message into a hash.
856 # Entry criteria: $message is a string, with LF or CRLF line endings.
857 # Exit status: A hash reference from lower-case header name to the unfolded
858 # value of the first header of that name. A message with no
859 # blank line is all header.
860 # Side effects: None.
861 134 ▶sub _parse_headers :Private
Subroutine _parse_headers: called CC=5 SCAR=16.2
862 {
863 134 my $message = shift;
864  
865 134 my ($block) = $message =~ /\A(.*?)\r?\n\r?\n/s;
866 134 ▶ $block //= $message;
Condition66%2/3
$block //= $message
l!l&&r!l&&!r
121130
MC/DC0%0/2
$block //= $message
$block $message
Truth table66%2/3
A //= B
A= $blockB= $message
ABresult
1X1
011
000
867  
868 # A header can be folded over several lines; join them back.
869 134 $block =~ s/\r?\n[ \t]+/ /g;
870  
871 134 my %headers;
872 134 foreach my $line (split(/\r?\n/, $block)) {
873 1410 ▶ $headers{lc($1)} //= $2 if($line =~ /\A([^\s:]+):[ \t]*(.*?)\s*\z/);
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /\A([^\s:]+):[ \t]*(.*?)\s*\z/ 1399 11 1410
Condition66%2/3
$headers{lc $1} //= $2
l!l&&r!l&&!r
10013980
MC/DC0%0/2
$headers{lc $1} //= $2
$headers{lc $1} $2
Truth table66%2/3
A //= B
A= $headers{lc $1}B= $2
ABresult
1X1
011
000
874 }
875  
876 134 return \%headers;
877 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
878  
879 # Purpose: Parse a header value into addresses.
880 # Entry criteria: $value is a string.
881 # Exit status: The list of Mail::Address objects, in order, as many as could
882 # be made of it.
883 # Side effects: None. The parser's complaints about a malformed header are
884 # dropped: a header is the sender's to get wrong, and a
885 # warning in the log for it would be noise.
886 137 ▶sub _parse_addresses :Private
Subroutine _parse_addresses: called CC=1 SCAR=0.0
887 {
888 137 my $value = shift;
889  
890 137 ▶ local $SIG{'__WARN__'} = sub { };
Subroutine __ANON__: called CC=1 SCAR=0.0
891  
892 137 return Mail::Address->parse($value);
893 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
894  
895 # Purpose: The addresses in a header value.
896 # Entry criteria: $value is a header value, or undef.
897 # Exit status: An array reference of the addresses, in order; empty when
898 # there are none. Display names and comments are dropped.
899 # Side effects: None.
900 93 ▶sub _addresses :Private
Subroutine _addresses: called CC=4 SCAR=13.9
901 {
902 93 my $value = shift;
903  
904 # A group with no members, "undisclosed-recipients:;", comes back as its name.
905 93 ▶ return defined($value) ? [ grep { length && !/:\z/ } map { $_->address() // '' } _parse_addresses($value) ] : [];
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 65 28 93
Condition100%5/5
length $_ && !/:\z/
!ll&&!rl&&r
315065
$_->address // ""
l!l
50681
MC/DC100%2/2
length $_ && !/:\z/
length $_ !/:\z/
MC/DC100%1/1
$_->address // ""
$_->address
Truth table100%3/3
A && not(B)
A= length $_B= !/:\z/
ABresult
0X0
100
111
Truth table100%2/2
A
A= $_->address
Aresult
11
00
906 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
907  
908 =head2 B<from_domain> $message
909  
910 The domain of the address in the first C<From:> header, in lower case, or
911 C<undef> when there is no such header. Folded headers and display names are
912 understood. A line with white space between the name and the colon, such as
913 C<From :>, is not taken for a C<From:> header, so such a message is not signed.
914  
915 =head3 PURPOSE
916  
917 Says whose domain a message claims to be from, which is what decides whether
918 it is signed. The address is read by L<Mail::Address>, so quoted display
919 names, comments and groups are handled by a parser that has seen them before.
920 Only a plain host name is accepted as a domain (letters, digits, dots and
921 hyphens).
922  
923 A C<From:> header that holds a control character, other than a tab, gives
924 C<undef>. A NUL or an escape character can make two programs read two
925 different addresses from the same header, so no domain is trusted from it.
926  
927 =head3 EXAMPLE
928  
929 my $domain = Mail::Send::DKIM::from_domain($message); # 'example.org'
930 my $same = $dkim->from_domain($message);
931  
932 =head3 API SPECIFICATION
933  
934 =head4 Input (Params::Validate::Strict)
935  
936 { message => { type => 'string' } }
937  
938 It may be called as a function or as a method.
939  
940 =head4 Output (Return::Set)
941  
942 { type => 'string', optional => 1, matches => qr/\A[a-z0-9.-]+\z/ }
943  
944 =head3 MESSAGES
945  
946 None: a message without a usable From: is not an error, the answer is C<undef>.
947  
948 =cut
949  
950 sub from_domain
951 92 ▶{
Subroutine from_domain: called CC=8 SCAR=20.8
Pod documented
952 # Called as a method, the first argument is the object, not the message.
953 92 ▶ shift if(@_ > 1);
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 3 89 92
954 92 ▶ my $message = validate_strict('schema' => { 'message' => { 'type' => 'string' } }, 'input' => { 'message' => $_[0] })->{'message'} // '';
Condition100%2/2
validate_strict("schema", {"message", {"type", "string"}}, "input", {"message", $_[0]})->{"message"} // ""
l!l
883
MC/DC100%1/1
validate_strict("schema", {"message", {"type", "string"}}, "input", {"message", $_[0]})->{"message"} // ""
validate_strict("schema", {"message", {"type", "string"}}, "input", {"message", $_[0]})->{"message"}
Truth table100%2/2
A
A= validate_strict("schema", {"message", {"type", "string"}}, "input", {"message", $_[0]})->{"message"}
Aresult
11
00
955  
956 91 my $from = _parse_headers($message)->{'from'};
957 91 my $host;
958  
959 # A control character in the header, a NUL especially, can make two
960 # parsers read two different addresses, so no domain is trusted from it.
961 91 ▶ if(defined($from) && $from !~ /[\x00-\x08\x0b-\x1f\x7f]/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $from and not $from =~ /[\x00-\x08\x0b-\x1f\x7f]/) 71 20 91
Condition100%3/3
defined $from and not $from =~ /[\x00-\x08\x0b-\x1f\x7f]/
!ll&&!rl&&r
16471
MC/DC100%2/2
defined $from and not $from =~ /[\x00-\x08\x0b-\x1f\x7f]/
defined $from not $from =~ /[\x00-\x08\x0b-\x1f\x7f]/
Truth table100%3/3
A and not(B)
A= defined $fromB= not $from =~ /[\x00-\x08\x0b-\x1f\x7f]/
ABresult
0X0
100
111
962 # The first address is the author; display names and comments around
963 # it are Mail::Address's to deal with, not ours.
964 71 my ($address) = _parse_addresses($from);
965 71 ▶ $host = $address->host() if(defined($address));
Branch: 1 branch
BranchTrueFalseTotal
if defined $address 68 3 71
966 }
967  
968 # Only a plain host name is a domain; the result is put in the signature.
969 91 ▶ return (defined($host) && $host =~ $DOMAIN_SYNTAX) ? lc($host) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $host && $host =~ /$DOMAIN_SYNTAX/ ? : 54 37 91
Condition100%3/3
defined $host and $host =~ /$DOMAIN_SYNTAX/
!ll&&!rl&&r
261154
MC/DC100%2/2
defined $host and $host =~ /$DOMAIN_SYNTAX/
defined $host $host =~ /$DOMAIN_SYNTAX/
Truth table100%3/3
A and B
A= defined $hostB= $host =~ /$DOMAIN_SYNTAX/
ABresult
0X0
100
111
970 }
971  
972 =head2 B<selector>
973  
974 The selector the message will be signed under: the one given to B<new> or read
975 from C<DKIM_SELECTOR>, otherwise the name of the B<keyfile> when one is given,
976 otherwise the name of the only F<*.private> file in B<keydir>. C<undef> when it
977 cannot be decided - no key, or several keys and no name - and the reason is a
978 warning on standard error. B<sign> asks this before doing anything else.
979  
980 =head3 PURPOSE
981  
982 Settles which of the keys is to be used, once, in one place.
983  
984 A key in B<keydir> is a regular file with a name in front of F<.private>.
985 A directory with such a name, and a file that is only F<.private>, are not
986 keys and are not counted. A selector that is an empty string is the same as
987 none.
988  
989 =head3 EXAMPLE
990  
991 my $selector = $dkim->selector();
992 die 'no usable key' unless(defined($selector));
993  
994 =head3 API SPECIFICATION
995  
996 =head4 Input (Params::Validate::Strict)
997  
998 {}
999  
1000 =head4 Output (Return::Set)
1001  
1002 { type => 'string', optional => 1 }
1003  
1004 =head3 MESSAGES
1005  
1006 Message key Meaning and resolution
1007 keydir_unreadable keydir cannot be opened: create it, or fix the mode or
1008 the keydir option.
1009 keys_ambiguous keydir holds no key, or more than one, and no selector
1010 was named: add the key, or set DKIM_SELECTOR.
1011  
1012 =head3 PSEUDOCODE
1013  
1014 if a selector was given: return it
1015 if a key file was given: return its name without .private, .key or .pem
1016 list the *.private files in keydir (a warning and undef if it cannot be read)
1017 if there is not exactly one: warn, return undef
1018 return its name without .private
1019  
1020 =cut
1021  
1022 sub selector
1023 51 ▶{
Subroutine selector: called CC=7 SCAR=19.5
Pod documented
1024 51 my $self = shift;
1025  
1026 51 my $selector = $self->{'selector'};
1027 51 ▶ return $selector if(defined($selector) && length($selector));
Branch: 1 branch
BranchTrueFalseTotal
if defined $selector and length $selector 8 43 51
Condition100%3/3
defined $selector and length $selector
!ll&&!rl&&r
4218
MC/DC100%2/2
defined $selector and length $selector
defined $selector length $selector
Truth table100%3/3
A and B
A= defined $selectorB= length $selector
ABresult
0X0
100
111
1028  
1029 # A named key file carries its selector in its name, which is the layout
1030 # the keys are kept in: <keydir>/<selector>.private.
1031 43 ▶ if(defined($self->{'keyfile'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"keyfile"}) 13 30 43
1032 13 ($selector = basename($self->{'keyfile'})) =~ s/$KEYFILE_NAME_SUFFIX//;
1033 13 ▶ return $selector if(length($selector));
Branch: 1 branch
BranchTrueFalseTotal
if length $selector 11 2 13
1034 }
1035  
1036 32 my $keys = $self->_private_keys();
1037 # undef, as the POD says: a bare return would be an empty list when the
1038 # result is used in a list, as in a hash of options.
1039 32 ▶ return undef unless(defined($keys)); ## no critic (Subroutines::ProhibitExplicitReturnUndef)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $keys 8 24 32
1040  
1041 24 ▶ unless(@{$keys} == 1) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@{$keys;} == 1) 7 17 24
1042 7 $self->_say('keys_ambiguous', { 'keydir' => $self->{'keydir'}, 'count' => scalar(@{$keys}) });
1043 7 return undef; ## no critic (Subroutines::ProhibitExplicitReturnUndef)
1044 }
1045  
1046 17 ($selector = $keys->[0]) =~ s/\Q$KEY_SUFFIX\E\z//;
1047  
1048 17 return $selector;
1049 }
1050  
1051 # Purpose: List the keys in the key directory.
1052 # Entry criteria: $self->{keydir} is set.
1053 # Exit status: An array reference of the names of the files ending .private, sorted;
1054 # undef, after a warning, when the directory cannot be read.
1055 # Side effects: Reads a directory; may warn.
1056 70 ▶sub _private_keys :Private
Subroutine _private_keys: called CC=3 SCAR=11.0
1057 {
1058 70 my $self = shift;
1059  
1060 # An unreadable directory is a warning and an unsigned message, so autodie
1061 # stands aside.
1062 19 ▶ no autodie qw(opendir closedir);
Subroutine BEGIN: called CC=1 SCAR=0.0
1063  
1064 70 my $keys;
1065 70 ▶ if(opendir(my $dh, $self->{'keydir'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (opendir my $dh, $self->{'keydir'}) { } 40 30 70
1066 # A key is a file with a name before the suffix: a directory called
1067 # x.private, or a file called just .private, is not one.
1068 40 ▶ $keys = [ sort grep { /\A.+\Q$KEY_SUFFIX\E\z/s && -f "$self->{'keydir'}/$_" } readdir($dh) ];
Condition100%3/3
/\A.+\Q$KEY_SUFFIX\E\z/s && -f "$self->{'keydir'}/$_"
!ll&&!rl&&r
841105020
MC/DC100%2/2
/\A.+\Q$KEY_SUFFIX\E\z/s && -f "$self->{'keydir'}/$_"
/\A.+\Q$KEY_SUFFIX\E\z/s -f "$self->{'keydir'}/$_"
Truth table100%3/3
A && B
A= /\A.+\Q$KEY_SUFFIX\E\z/sB= -f "$self->{'keydir'}/$_"
ABresult
0X0
100
111
1069 40 closedir($dh);
1070 } else {
1071 30 $self->_say('keydir_unreadable', { 'keydir' => $self->{'keydir'}, 'os_error' => "$!" });
1072 }
1073  
1074 70 return $keys;
1075 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1076  
1077 =head2 B<i18n> $key, \%arguments
1078  
1079 Returns the text of a message, in the language this object speaks, with the
1080 arguments put in. This is the one place any sentence is made, so a caller can
1081 change every message by giving B<new> a C<messages> option.
1082  
1083 A message is a format whose placeholders are named, C<%{name}s> or
1084 C<%{name}d>, and which may carry the usual C<sprintf> width and flags
1085 (C<%{name}-8s>). It may instead be a hash of formats, from which one is chosen
1086 by the arguments: C<count> selects C<zero>, C<one> or C<other> (C<other> when
1087 there is no better one), and C<variant> - a grammatical gender, for instance -
1088 selects the entry of that name, or C<variant.one>, C<variant.other> and so on
1089 when the choice is both. An argument a format asks for and was not given is an
1090 error, not an empty string. An argument that is given as C<undef> is an empty
1091 string (C<0> in a C<%{name}d>). A C<count> that is not a number selects no
1092 plural form. C<%%> is a percent sign, and any other C<%> that is not part of a
1093 placeholder is plain text. An entry that is an empty hash says nothing.
1094  
1095 Croaks if C<$key> is not a message that is defined.
1096  
1097 =head3 EXAMPLE
1098  
1099 my $text = $dkim->i18n('keys_ambiguous', { keydir => '/etc/dkim', count => 2 });
1100 # '... /etc/dkim holds 2 keys; name the selector to choose one'
1101  
1102 my $french = Mail::Send::DKIM->new(messages => {
1103 'keys_ambiguous' => {
1104 'one' => '%{keydir}s contient %{count}d cle',
1105 'other' => '%{keydir}s contient %{count}d cles',
1106 },
1107 });
1108  
1109 =head3 API SPECIFICATION
1110  
1111 =head4 Input (Params::Validate::Strict)
1112  
1113 {
1114 key => { type => 'string' },
1115 arguments => { type => 'hashref', optional => 1 },
1116 }
1117  
1118 =head4 Output (Return::Set)
1119  
1120 { type => 'string' }
1121  
1122 =head3 MESSAGES
1123  
1124 Message key Meaning and resolution
1125 unknown_message The key is not in the catalogue: fix the caller, or add it to messages.
1126 bad_arguments The arguments were not a hash reference: pass { name => value }.
1127 missing_argument A placeholder has no argument: pass it.
1128  
1129 =cut
1130  
1131  
1132 sub i18n
1133 102 ▶{
Subroutine i18n: called CC=7 SCAR=19.5
Pod documented
1134 102 my ($self, $key, $args) = @_;
1135  
1136 102 ▶ $args //= {};
Condition100%2/2
$args //= {}
l!l
7725
MC/DC100%1/1
$args //= {}
$args
Truth table100%2/2
A
A= $args
Aresult
11
00
1137 102 ▶ $key //= '';
Condition100%2/2
$key //= ""
l!l
1011
MC/DC100%1/1
$key //= ""
$key
Truth table100%2/2
A
A= $key
Aresult
11
00
1138 102 ▶ croak($self->i18n('bad_arguments', { 'type' => ref($args) || 'a plain value' })) unless(ref($args) eq 'HASH');
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "HASH" 3 99 102
Condition100%2/2
ref $args || 'a plain value'
l!l
21
MC/DC100%1/1
ref $args || 'a plain value'
ref $args
Truth table100%2/2
A
A= ref $args
Aresult
11
00
1139  
1140 # The default catalogue is the fallback, so a caller's catalogue cannot
1141 # take away the message that reports a missing message.
1142 99 ▶ my $entry = $self->{'messages'}->{$key} // $DEFAULT_MESSAGES{$key};
Condition100%3/3
$self->{"messages"}{$key} // $DEFAULT_MESSAGES{$key}
l!l&&r!l&&!r
74322
MC/DC100%2/2
$self->{"messages"}{$key} // $DEFAULT_MESSAGES{$key}
$self->{"messages"}{$key} $DEFAULT_MESSAGES{$key}
Truth table100%3/3
A // B
A= $self->{"messages"}{$key}B= $DEFAULT_MESSAGES{$key}
ABresult
1X1
011
000
1143 99 ▶ croak($self->i18n('unknown_message', { 'key' => $key })) unless(defined($entry));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry 22 77 99
1144  
1145 77 return $self->_interpolate($key, _choose_format($entry, $args), $args);
1146 }
1147  
1148 # Purpose: Pick the format of a message that has variants.
1149 # Entry criteria: $entry is a string, or a hash reference of formats keyed by
1150 # zero, one, other, a variant name, or "variant.count".
1151 # Exit status: The format. The most specific variant that exists wins, and
1152 # "other" is the fall-back, then any entry at all.
1153 # Side effects: None.
1154 100 ▶sub _choose_format :Private
Subroutine _choose_format: called CC=13 SCAR=25.6
1155 {
1156 100 my ($entry, $args) = @_;
1157  
1158 100 my $format = $entry;
1159  
1160 100 ▶ if(ref($entry) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $entry eq "HASH") 38 62 100
1161 38 my $variant = $args->{'variant'};
1162 38 my $count = $args->{'count'};
1163 # A count that is not a number selects no plural form.
1164 38 ▶ my $plural = !looks_like_number($count // '') ? undef : ($count == 0 ? 'zero' : ($count == 1 ? 'one' : 'other'));
Branch: 3 branches
BranchTrueFalseTotal
!&looks_like_number(scalar($count // '')) ? : 14 24 38
$count == 0 ? : 6 18 24
$count == 1 ? : 9 9 18
Condition100%2/2
$count // ""
l!l
299
MC/DC100%1/1
$count // ""
$count
Truth table100%2/2
A
A= $count
Aresult
11
00
1165  
1166 38 ▶ my @candidates = (
Branch: 3 branches
BranchTrueFalseTotal
defined $variant && defined $plural ? : 6 32 38
defined $variant ? : 10 28 38
defined $plural ? : 24 14 38
Condition100%3/3
defined $variant and defined $plural
!ll&&!rl&&r
2846
MC/DC100%2/2
defined $variant and defined $plural
defined $variant defined $plural
Truth table100%3/3
A and B
A= defined $variantB= defined $plural
ABresult
0X0
100
111
1167 (defined($variant) && defined($plural) ? "$variant.$plural" : ()),
1168 (defined($variant) ? $variant : ()),
1169 (defined($plural) ? $plural : ()),
1170 'other',
1171 );
1172 38 my ($chosen) = grep { exists($entry->{$_}) } @candidates;
1173 # An empty entry says nothing, rather than failing.
1174 38 ▶ my $name = $chosen // (sort keys %{$entry})[0];
Condition100%3/3
$chosen // (sort keys %{$entry;})[0]
l!l&&r!l&&!r
3611
MC/DC100%2/2
$chosen // (sort keys %{$entry;})[0]
$chosen (sort keys %{$entry;})[0]
Truth table100%3/3
A // B
A= $chosenB= (sort keys %{$entry;})[0]
ABresult
1X1
011
000
1175 38 ▶ $format = defined($name) ? ($entry->{$name} // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 37 1 38
Condition100%2/2
$entry->{$name} // ""
l!l
361
MC/DC100%1/1
$entry->{$name} // ""
$entry->{$name}
Truth table100%2/2
A
A= $entry->{$name}
Aresult
11
00
1176 }
1177  
1178 100 return $format;
1179 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1180  
1181 # Purpose: Put the arguments into a format with named placeholders.
1182 # Entry criteria: $format uses %{name}s / %{name}d placeholders, and %% for a
1183 # percent sign. Anything else in it is plain text.
1184 # Exit status: The text. Croaks, with the missing_argument message, if a
1185 # placeholder has no argument.
1186 # Side effects: None.
1187 88 ▶sub _interpolate :Private
Subroutine _interpolate: called CC=6 SCAR=17.9
1188 {
1189 88 my ($self, $key, $format, $args) = @_;
1190  
1191 # Only the placeholders are handed to sprintf, one at a time, so a stray
1192 # percent sign in the text, or in a value, can never be taken for a
1193 # directive of its own.
1194 88 my $text = '';
1195 88 foreach my $part (split(/(%\{\w+\}[-+ 0#]*\d*(?:\.\d+)?[sd])/, $format)) {
1196 290 ▶ if($part =~ /\A%\{(\w+)\}(.+)\z/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /\A%\{(\w+)\}(.+)\z/s) { } 121 169 290
1197 121 my ($name, $spec) = ($1, $2);
1198 121 ▶ croak($self->i18n('missing_argument', { 'key' => $key, 'argument' => $name })) unless(exists($args->{$name}));
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args->{$name} 6 115 121
1199  
1200 # A value that is not a number is a caller's mistake in a %d, not worth a warning.
1201 19 ▶ no warnings 'numeric';
Subroutine BEGIN: called CC=1 SCAR=0.0
1202 115 ▶ $text .= sprintf("%$spec", $args->{$name} // ($spec =~ /d\z/ ? 0 : ''));
Branch: 1 branch
BranchTrueFalseTotal
$spec =~ /d\z/ ? : 0 1 1
Condition100%2/2
$args->{$name} // ($spec =~ /d\z/ ? 0 : "")
l!l
1141
MC/DC100%1/1
$args->{$name} // ($spec =~ /d\z/ ? 0 : "")
$args->{$name}
Truth table100%2/2
A
A= $args->{$name}
Aresult
11
00
1203 } else {
1204 169 (my $plain = $part) =~ s/%%/%/g;
1205 169 $text .= $plain;
1206 }
1207 }
1208  
1209 82 return $text;
1210 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1211  
1212 # Purpose: Make the form of a message that is handed to sendmail.
1213 # Entry criteria: $message is a string.
1214 # Exit status: The message with LF line endings and no carriage return
1215 # anywhere, whatever arrived. A CR is data to the MTA that
1216 # keeps the message - Postfix's sendmail_fix_line_endings and
1217 # Exim both write the CRLF of SMTP themselves - so one that
1218 # survived would reach the receiver doubled, and the message
1219 # would fail the signature it was just given.
1220 # Side effects: None.
1221 98 ▶sub _local :Private
Subroutine _local: called CC=1 SCAR=0.0
1222 {
1223 98 my $message = shift;
1224  
1225 98 $message =~ tr/\r//d;
1226  
1227 98 return $message;
1228 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1229  
1230 # Purpose: Normalise the domain to put in the signature.
1231 # Entry criteria: $domain is a string or undef.
1232 # Exit status: The lower-case domain, or undef when none is given (an empty
1233 # or blank value counts as none).
1234 167 ▶sub _signing_domain :Private
Subroutine _signing_domain: called CC=3 SCAR=11.0
1235 {
1236 167 my $domain = shift;
1237  
1238 167 ▶ return undef unless(defined($domain) && $domain =~ /\S/); ## no critic (ProhibitExplicitReturnUndef)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $domain and $domain =~ /\S/ 163 4 167
Condition100%3/3
defined $domain and $domain =~ /\S/
!ll&&!rl&&r
16214
MC/DC100%2/2
defined $domain and $domain =~ /\S/
defined $domain $domain =~ /\S/
Truth table100%3/3
A and B
A= defined $domainB= $domain =~ /\S/
ABresult
0X0
100
111
1239 4 $domain =~ s/\A\s+|\s+\z//g;
1240  
1241 4 return lc($domain);
1242 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1243  
1244 # Purpose: Make the set of domains this host signs for.
1245 # Entry criteria: $domains is an array reference, a string separated by commas
1246 # or spaces, or undef.
1247 # Exit status: A hash reference whose keys are the lower-case domains.
1248 # Side effects: None.
1249 177 ▶sub _domain_set :Private
Subroutine _domain_set: called CC=4 SCAR=13.9
1250 {
1251 177 my $domains = shift;
1252  
1253 177 ▶ my @domains = ref($domains) eq 'ARRAY' ? @{$domains} : split($DOMAIN_SEPARATOR, $domains // '');
Branch: 1 branch
BranchTrueFalseTotal
ref $domains eq 'ARRAY' ? : 26 151 177
Condition100%2/2
$domains // ""
l!l
29122
MC/DC100%1/1
$domains // ""
$domains
Truth table100%2/2
A
A= $domains
Aresult
11
00
1254  
1255 177 ▶ return { map { lc($_) => 1 } grep { defined && length } @domains };
Condition100%3/3
defined $_ && length $_
!ll&&!rl&&r
225060
MC/DC100%2/2
defined $_ && length $_
defined $_ length $_
Truth table100%3/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
1256 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1257  
1258 # Purpose: Tidy an error for use inside a sentence.
1259 # Entry criteria: $text is a string, perhaps with a trailing newline.
1260 # Exit status: The text without its trailing whitespace.
1261 # Side effects: None.
1262 16 ▶sub _trim_error :Private
Subroutine _trim_error: called CC=1 SCAR=0.0
1263 {
1264 16 my $text = shift;
1265  
1266 16 $text =~ s/\s+\z//;
1267  
1268 16 return $text;
1269 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1270  
1271 # Purpose: Warn, in the language of this object.
1272 # Entry criteria: $key is in the message catalogue.
1273 # Exit status: $self, so calls can be chained.
1274 # Side effects: A warning on standard error, reported where the caller of this
1275 # module called it, by Carp. Protected, so that a subclass may
1276 # say things in the same way.
1277 26 ▶sub _say :Protected
Subroutine _say: called CC=1 SCAR=0.0
1278 {
1279 26 my ($self, $key, $args) = @_;
1280  
1281 26 carp($self->i18n($key, $args));
1282  
1283 24 return $self;
1284 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1285  
1286 19 1;
1287  
1288 __END__
« bin/dmarc-summary ↑ Summary bin/dmarc-report.pl »