lib/Mail/Send/DKIM.pm

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