Name

Log::Dispatch::Email::DKIM - Log::Dispatch appender that DKIM-signs its mail

Version

Version 0.001.0

Synopsis

Pattern 1: from a log4perl configuration file.

log4perl.appender.A2=Log::Dispatch::Email::DKIM
log4perl.appender.A2.from=webmaster@example.com
log4perl.appender.A2.to=admin@example.com
log4perl.appender.A2.subject=Error in shop/index.fcgi

Pattern 2: directly from Log::Dispatch, sending each message at once.

use Log::Dispatch;

my $log = Log::Dispatch->new(
    outputs => [ [
        'Email::DKIM',
        'min_level' => 'error',
        'from' => 'webmaster@example.com',
        'to' => ['admin@example.com'],
        'subject' => 'Error in shop/index.fcgi',
        'buffered' => 0,
    ] ],
);
$log->error("Something went wrong\n");

Pattern 3: choose the key and the selector with environment variables (for example in the web server settings).

SetEnv DKIM_KEYFILE /home/site/dkim/202611.private
SetEnv DKIM_SELECTOR 202611

Pattern 4: in a test, send to a script that saves the message instead of to sendmail.

local $ENV{'DKIM_SENDMAIL'} = '/tmp/capture-script';
$log->error("Test message\n");

Description

Sends a log message the way Log::Dispatch::Email::Sendmail does, but signs it with Mail::Send::DKIM first, so the message carries a DKIM-Signature for the domain it claims to come from. An unsigned webmaster@ message and a forgery are indistinguishable in a DMARC report; signing is what tells them apart, and what lets the copy a mailing list forwards still authenticate.

The signing key is found rather than configured. Log::Dispatch validates each appender's arguments and passes on only name, min_level, max_level, callbacks and newline, so a keyfile= line in the log4perl configuration never reaches this object. Instead the domain is taken from the from address and the selector from the key's file name.

Configuration

The defaults suit this host: the key in ~/dkim/*.private with the highest name is used, and its name is the selector. Each can be overridden in the environment, which is also how a test points it at a capture script. An empty variable counts as unset.

DKIM_DOMAIN changes only the domain in the signature. Whether a message is signed at all is still decided by the domain in from, so a message from an address this host has no key for is sent unsigned whatever DKIM_DOMAIN says. DKIM_SENDMAIL wins over SENDMAIL, the variable Mail::Send::DKIM and its mail-dkim programme read, so a host that sets only SENDMAIL gets the same sendmail from both. With neither set, /usr/sbin/sendmail is used.

The home directory comes from File::HomeDir, so it is found even when the process (a CGI script, say) has no HOME in its environment.

Common Pitfalls

Encoding

This module does not convert text. It passes the bytes it is given to sendmail and it adds no Content-Type or charset header.

Methods

Send_Email

Purpose

Builds the message, signs it and hands it to sendmail(1). Log::Dispatch calls this itself, once per message when unbuffered and once per flush when buffered, so applications do not normally call it.

Args

A hash or hash reference with message, the text of the message body. Any other key (level, name, ...) is ignored.

Returns

$self, so calls can be chained. The outcome of the delivery is reported by warning, not by the return value, because Log::Dispatch ignores it.

Side Effects

Runs sendmail(1). While it runs, STDERR is pointed at the null device because some sendmail implementations write a warning there that would corrupt CGI output.

A missing or unreadable key is not an error: it warns and sends the message unsigned, which is what Mail::Send::DKIM does for a signing problem of any kind. A line break in the subject, From or To is replaced by a space, so a logged value cannot add a header of its own.

When there is no recipient, or the from address cannot be parsed, nothing is sent and the problem is written straight to STDERR, not warned: a warning could be routed back into this appender and loop. from may carry a display name ("Web Master" <webmaster@example.com>); the bare address is used as the sendmail envelope sender and as the signing domain.

Usage

$appender->send_email(message => "Something went wrong\n");

Example

use Log::Dispatch;

my $log = Log::Dispatch->new(
    outputs => [ [
        'Email::DKIM',
        'min_level' => 'error',
        'from' => 'webmaster@example.com',
        'to' => ['admin@example.com'],
        'subject' => 'Error in shop/index.fcgi',
    ] ],
);

# Sent, signed with the highest ~/dkim/*.private, when $log goes away
$log->error("Something went wrong\n");

# Test a different key and a capture script instead of sendmail
local $ENV{'DKIM_KEYFILE'} = '/tmp/keys/202611.private';
local $ENV{'DKIM_SENDMAIL'} = '/tmp/capture';

Api Specification

Input
{
    message => { type => 'string', min => 0 },
}

Unknown keys are ignored.

Output
{ type => 'object', isa => 'Log::Dispatch::Email::DKIM' }

Messages

Pseudocode

validate the arguments (croak if there is no message)
parse From into an address (undef if it is not one)
if there is no recipient or no address
    write the reason to STDERR and stop
find domain, selector and keyfile (environment, then From, then ~/dkim)
warn if any is missing or the keyfile is unreadable
build the message with a sanitised To, From and Subject
run sendmail with STDERR on the null device
warn if it failed
return self

i18n

Purpose

Turns a message key into text for the user, so that every warning and error this class raises can be translated or reworded by a subclass or by assigning to %Log::Dispatch::Email::DKIM::MESSAGES. Protected: callable from this class and its subclasses only.

Args

The message key, then an optional hash reference of arguments. count selects the one or other variant of a message, and gender selects the variant of that name, with other as the fallback.

Returns

The message text. An unknown key returns the key itself, so a missing translation is visible rather than fatal.

Side Effects

None.

Usage

my $text = $self->i18n('no_key', { 'domain' => 'example.com' });

Example

# A catalogue entry is [ $sprintf_format, @argument_names ], or a hash
# of variants of one
local $Log::Dispatch::Email::DKIM::MESSAGES{'files'} = {
    'one' => ['%s file', 'count'],
    'other' => ['%s files', 'count'],
};
$self->i18n('files', { 'count' => 2 });     # "2 files"

Api Specification

Input
{
    key => { type => 'string', min => 1 },
    args => { type => 'hashref', optional => 1 },
}
Output
{ type => 'string' }

Messages

None of its own. An unknown key is returned as the text.

Pseudocode

look the key up; if absent, return the key
if the entry is a hash of variants, choose one by gender, then count
format the entry with its named arguments

Examples

A complete log4perl configuration file, which logs everything to a file and emails anything of level WARN or above. Save it as, say, myapp.l4pconf and load it with Log::Log4perl->init('myapp.l4pconf').

log4perl.logger.myapp=TRACE, A1, A2

log4perl.appender.A1=Log::Dispatch::File
log4perl.appender.A1.Filter=RangeAll
log4perl.appender.A1.filename=/tmp/myapp.log
log4perl.appender.A1.mode=append
log4perl.appender.A1.layout=Log::Log4perl::Layout::PatternLayout
log4perl.appender.A1.layout.ConversionPattern=%d %p> %F{1}:%L %M - %m%n

log4perl.appender.A2=Log::Dispatch::Email::DKIM
log4perl.appender.A2.Filter=RangeError
log4perl.appender.A2.from=webmaster@example.com
log4perl.appender.A2.to=admin@example.com
log4perl.appender.A2.subject=Error in myapp
log4perl.appender.A2.layout=Log::Log4perl::Layout::PatternLayout
log4perl.appender.A2.layout.ConversionPattern=%d %p> %F{1}:%L %M - %m%n

log4perl.filter.RangeAll=Log::Log4perl::Filter::LevelRange
log4perl.filter.RangeAll.LevelMin=TRACE
log4perl.filter.RangeAll.LevelMax=FATAL
log4perl.filter.RangeAll.AcceptOnMatch=true

log4perl.filter.RangeError=Log::Log4perl::Filter::LevelRange
log4perl.filter.RangeError.LevelMin=WARN
log4perl.filter.RangeError.LevelMax=FATAL
log4perl.filter.RangeError.AcceptOnMatch=true

Limitations

See Also

Author

Nigel Horne, <njh at nigelhorne.com>

Formal Specification

The notation is Z. Config is what an appender holds after new. A message is signed only when a readable key, a domain and a selector are all found.

[STRING, ADDRESS, PATH]

┌─ Config ─────────────────────────────────────────────────
│ from : STRING
│ to : seq STRING
│ subject : STRING
│ buffered : 𝔹
│ buffer : seq STRING
├──────────────────────────────────────────────────────────
│ buffered = false ⇒ buffer = ⟨ ⟩
└──────────────────────────────────────────────────────────

Send_Email

┌─ SendEmail ──────────────────────────────────────────────
│ Ξ Config
│ message? : STRING
│ sender : ADDRESS ⇸ ADDRESS        (the parse of from)
│ key : PATH ⇸ PATH                 (the key file, if any)
│ sent! : 𝔹
│ signed! : 𝔹
├──────────────────────────────────────────────────────────
│ message? is defined
│ sent! = (to ≠ ⟨ ⟩ ∧ sender ≠ ∅ ∧ sendmail succeeds)
│ signed! = (sent! ∧ key ≠ ∅ ∧ readable(key) ∧ domain defined
│            ∧ selector defined)
│ sent! ∧ ¬ signed! ⇒ one warning "no DKIM key"
│ to ≠ ⟨ ⟩ ∧ sender ≠ ∅ ∧ ¬ sent! ⇒ one warning "sendmail failed"
│ (to = ⟨ ⟩ ∨ sender = ∅) ⇒ one line on STDERR and no warning
└──────────────────────────────────────────────────────────

i18n

┌─ I18n ───────────────────────────────────────────────────
│ Ξ Config
│ catalogue : STRING ⇸ (ENTRY ∪ (STRING ⇸ ENTRY))
│ key? : STRING
│ args? : STRING ⇸ STRING
│ text! : STRING
├──────────────────────────────────────────────────────────
│ key? ∉ dom catalogue ⇒ text! = key?
│ key? ∈ dom catalogue ⇒
│     text! = sprintf(format(entry), args?(names(entry)))
│ a name missing from args? is replaced by the empty string
└──────────────────────────────────────────────────────────

State Diagram

An appender is always in one of these states:

EMPTY      no message is waiting
PENDING    one or more messages wait in the buffer
SENDING    send_email is running
GONE       the object has been destroyed

                   new
                    |
                    v
              +-----------+  log, buffered=1   +-----------+
              |           |------------------->|           |--+
              |   EMPTY   |                    |  PENDING  |  | log,
              |           |                    |           |<-+ buffered=1
              +-----------+                    +-----------+
                |   ^   |                           |
    log,        |   |   | destroy                   | flush, or
    buffered=0  |   |   v                           | destroy
                |   |  +------+                     |
                |   |  | GONE |                     |
                v   |  +------+                     |
              +-----------+                         |
              |           |<------------------------+
              |  SENDING  |
              |           |
              +-----------+
                send_email ends: back to EMPTY (the buffer is cleared)

The same changes in a table:

From     Trigger                  To       Action or side effect
-------  -----------------------  -------  -----------------------------
(none)   new                      EMPTY    Checks the settings.  Makes an
                                           empty buffer if buffered = 1.
EMPTY    log, buffered = 1        PENDING  Adds the text to the buffer.
PENDING  log, buffered = 1        PENDING  Adds the text to the buffer.
EMPTY    log, buffered = 0        SENDING  Calls send_email at once.
PENDING  flush                    SENDING  Joins the buffer into one text
                                           and calls send_email.
PENDING  object destroyed         SENDING  Same as flush.
SENDING  send_email ends          EMPTY    The buffer is cleared.  The
                                           result is one of:
                                           - signed and sent: no output
                                           - no key: sent, one warning
                                           - sendmail failed: one warning
                                           - no to, or bad from: nothing
                                             sent, one line on STDERR
                                           - no message: croaks and the
                                             buffer is NOT cleared
EMPTY    object destroyed         GONE     Nothing is sent.
PENDING  program is ending        GONE     Log::Dispatch::Email warns
         (global destruction)              that messages were not sent.

Copyright 2026 Nigel Horne.

Usage is subject to the GPL2 licence terms. If you use it, please let me know.