It logs lines like:

Wed Mar 12 23:14:12 2008 c6[19799]: `L=194.145.201.216; R=193.200.132.135; 
F=<[EMAIL PROTECTED]>; T=<[EMAIL PROTECTED]>,<[EMAIL PROTECTED]>; P=queued; 
S=""; I=<msgid>; H="feather.perl6.nl (EHLO feather)"

Wed Mar 12 23:14:13 2008 c6[19819]: `L=193.200.132.185; 
R=190.172.177.<censored>; F=""; T=""; P=greylisting; S=DENYSOFT; I="This mail 
is temporarily denied"; H="<censored>.speedy.com.ar (HELO delphi.com)"

And it is based on logterse, but makes it easier to configure the
format. For example, I need the connection's unique ID, stored in
$connection-> notes("connection_id"). I can easily define a format that
includes this information.

Please review my plugin and let me know your suggestions.

Cheers!

Juerd


The full source:

our $VERSION = '0.01';

=head1 NAME

logcompact - qpsmtpd plugin for concise logging

=head1 DESCRIPTION

This plugin logs a single line for each command denied or message queued. The
logged line is configurable, and is written using qpsmtpd's normal logging
mechanism.

=head2 Configuration

The suggested filename for this plugin is "logging/logcompact". To enable the
plugin, add "logging/logcompact" to your qpsmtpd plugins file.

The following configuration options are available:

=over 20

=item format

A string describing the line to be written. The default begins with a backtick
character to ease grepping it from the mail log file.

See L</FORMAT> for a list of supported values, and modifiers.

Because there cannot be any whitespace in a qpsmtpd plugin config string, any ^
is replaced by whitespace. There is currently no way to use a literal ^.

Default value: `L=%L%;^R=%R%;^F=%F%;^T=%T%;^P=%P%;^S=%S%;^I=%I%;^H=%H%

=item loglevel

The level with which to log the line. Must be a valid qpsmtpd loglevel name.

Default value: LOGALERT

=item autoquote_regex

A regular expression to override the definition of "sufficiently special" as
mentioned under L</FORMAT>.

Default value: [\0\s;"]|^\s*$

(That is, by default it will use quoting/escaping when there's a null byte,
whitespace, semicolon, double quote or nothing at all.)

=back

=head1 FORMAT

Variables:

    %L%     - Local IP address
    %R%     - Remote IP address
    %H%     - Remote hostname and HELO/EHLO line in parens if given
    %F%     - Envelope sender (MAIL FROM)
    %T%     - Envelope recipient (RCPT TO)
    %S%     - Status (return value: DENY or DENYSOFT)
    %P%     - Plugin that denied, or "queued"
    %I%     - Info (deny message or <message ID>)
    %X:foo% - Value in connection note "foo"
    %N:foo% - Value in transaction note "foo"

Modifiers:

    %A%     - Quote if containing sufficiently special chars
    %-A%    - Never quote the value
    %+A%    - Always quote the value

Unquoted strings have non-printable/non-ascii characters replaced by question
marks.

Quoted strings have non-printable/non-ascii characters escaped as \x00, where
00 is the hexadecimal character code, and have " and \ escaped as \" and
\\. The entire value is surrounded in "".

=head1 CAVEATS

Only information that qpsmtpd has recorded, is logged. When a plugin denies a
certain command, its value is not recorded.

Denied recipients get a log line each, even though they belong to a single
transaction. So if a message is sent to [EMAIL PROTECTED] and [EMAIL PROTECTED],
and you have a plugin that checks if recipients exist, you may see a line
with I="No mailbox here by that name" for [EMAIL PROTECTED], but a P=queued for
[EMAIL PROTECTED]

Many protocol errors are handled by qpsmtpd internally, and not logged.

Hostnames and addresses are lowercased, except for the HELO string.

=head1 AUTHOR

Juerd Waalboer <[EMAIL PROTECTED]>

=head1 ACKNOWLEDGEMENTS

This plugin was inspired by, and is based on, the "logterse" plugin, written by
Charles Butcher who took a lot from logging/adaptive by John Peacock. Thank you
both.

=head1 LICENSE

(MIT License)

 Copyright (c) 2008
     - Juerd Waalboer  <http://juerd.nl/>
     - TNX             <http://tnx.nl/>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

The software is provided "as is", without warranty of any kind, express or
implied, including but not limited to the warranties of merchantability,
fitness for a particular purpose and noninfringement. In no event shall the
authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising from,
out of or in connection with the software or the use or other dealings in the
software.

=cut

use strict;

sub register {
    my ($self, $qp, %args) = @_;

    $self->{_loglevel} = defined $args{loglevel}
        ? log_level($args{loglevel})
        : LOGALERT;

    $self->{_format}   = defined $args{format}
        ? $args{format}
        : "`L=%L%;^R=%R%;^F=%F%;^T=%T%;^P=%P%;^S=%S%;^I=%I%;^H=%H%";
    $self->{_format} =~ s/\^/ /g;

    $self->{_special}  = defined $args{autoquote_regex}
        ? qr/$args{autoquote_regex}/
        : qr/[\0\s;"]|^\s*$/;
}


sub hook_deny {
    my ($self, $transaction, $prev_hook, $retval, $return_text) = @_;

    $self->_log($transaction, $prev_hook, $retval, $return_text);
    return DECLINED;
}

sub hook_queue {
    my ($self, $transaction) = @_;

    my $msg_id = $transaction->header->get('Message-Id') || '';
    $msg_id = "<$msg_id>" unless $msg_id =~ /^<.*>$/;

    $self->_log($transaction, "queued", "", $msg_id);
    return DECLINED;
}

sub _quote {
    my ($string) = @_;
    $string =~ s/([\\"])/\\$1/g;
    $string =~ s/([^\x20-\x7e])/sprintf "\\x%02x", ord $1/ge;
    return qq("$string");
}

sub _strip {
    my ($string) = @_;
    $string =~ s/([^\x20-\x7e])/?/g;
    return $string;
}

my %retval = (
    DENY()                => "DENY",
    DENYSOFT()            => "DENYSOFT",
    DENY_DISCONNECT()     => "DENY+",
    DENYSOFT_DISCONNECT() => "DENYSOFT+",
);

sub _log {
    my ($self, $transaction, $plugin, $retval, $info) = @_;

    my $c = $self->qp->connection;
    my $t = $transaction;

    my %info = (
        L => $c->local_ip,
        R => $c->remote_ip,
        H => lc($c->remote_host),
        F => lc($t->sender),  # also forces string overloading :)
        T => join(',', map lc, $t->recipients),
        S => $retval{$retval},
        P => $plugin,
        I => $info,
        X => sub { $c->notes(shift) },
        N => sub { $t->notes(shift) },
    );
    not defined and $_ = "" for values %info;

    my $hello = $c->hello;
    $info{H} .= " (\U$hello\E " . $c->hello_host . ")" if $hello;

    my $string = $self->{_format};
    $string =~ s[%([-+]?)(\w)(?::([^%]+))?%] {
        my ($mod, $letter, $arg) = ($1, $2, $3);

        my $val = $info{$letter};
        $val = eval { $val->($arg) } if ref $val;

        + $mod eq '-'                 ? _strip($val)
        : $mod eq '+'                 ? _quote($val)
        : $val =~ /$self->{_special}/ ? _quote($val)
        :                               _strip($val);
    }ge;

    $self->log($self->{_loglevel}, $string);
}

1;

Reply via email to