<commit_before>#
# This file is best read with ``perldoc plugins.pod''
#

### 
# Conventions:
#  plugin names:  F<myplugin>, F<qpsmtpd-async>
#  constants:     I<LOGDEBUG>
#  smtp commands, answers: B<HELO>, B<250 Queued!>
#
# Notes: 
#  * due to restrictions of some POD parsers, no C<<$object->method()>>
#    are allowed, use C<$object-E<gt>method()> 
# 

=head1 Introduction

Plugins are the heart of qpsmtpd. The core implements only basic SMTP protocol
functionality. No useful function can be done by qpsmtpd without loading 
plugins.

Plugins are loaded on startup where each of them register their interest in 
various I<hooks> provided by the qpsmtpd core engine.

At least one plugin B<must> allow or deny the B<RCPT> command to enable 
receiving mail. The F<check_relay> plugin is the standard plugin for this.
Other plugins provide extra functionality related to this; for example the
F<require_resolvable_fromhost> plugin.

=head2 Loading Plugins

The list of plugins to load are configured in the I<config/plugins>
configuration file. One plugin per line, empty lines and lines starting
with I<#> are ignored. The order they are loaded is the same as given 
in this config file. This is also the order the registered I<hooks>
are run. The plugins are loaded from the F<plugins/> directory or 
from a subdirectory of it. If a plugin should be loaded from such a 
subdirectory, the directory must also be given, like the 
F<virus/clamdscan> in the example below. Alternate plugin directories
may be given in the F<config/plugin_dirs> config file, one directory
per line, these will be searched first before using the builtin fallback
of F<plugins/> relative to the qpsmtpd root directory. It may be 
necessary, that the F<config/plugin_dirs> must be used (if you're using 
F<Apache::Qpsmtpd>, for example).

Some plugins may be configured by passing arguments in the F<plugins>
config file.

A plugin can be loaded two or more times with different arguments by adding
I<:N> to the plugin filename, with I<N> being a number, usually starting at 
I<0>. 

Another method to load a plugin is to create a valid perl module, drop this
module in perl's C<@INC> path and give the name of this module as
plugin name. The only restriction to this is, that the module name B<must>
contain I<::>, e.g. C<My::Plugin> would be ok, C<MyPlugin> not. Appending of
I<:0>, I<:1>, ... does not work with module plugins.

 check_relay
 virus/clamdscan
 spamassassin reject_threshold 7
 my_rcpt_check example.com
 my_rcpt_check:0 example.org
 My::Plugin

=head1 Anatomy of a plugin

A plugin has at least one method, which inherits from the 
C<Qpsmtpd::Plugin> object. The first argument for this method is always the 
plugin object itself (and usually called C<$self>). The most simple plugin 
has one method with a predefined name which just returns one constant.

 # plugin temp_disable_connection
 sub hook_connect {
    return(DENYSOFT, "Sorry, server is temporarily unavailable.");
 }

While this is a valid plugin, it is not very useful except for rare 
circumstances. So let us see what happens when a plugin is loaded.

=head2 Initialisation

After the plugin is loaded the C<init()> method of the plugin is called, 
if present. The arguments passed to C<init()> are 

=over 4

=item $self 

the current plugin object, usually called C<$self>

=item $qp

the Qpsmtpd object, usually called C<$qp>.

=item @args

the values following the plugin name in the F<plugins> config, split by 
white space. These arguments can be used to configure the plugin with 
default and/or static config settings, like database paths, 
timeouts, ...

=back

This is mainly used for inheriting from other plugins, but may be used to do
the same as in C<register()>.

The next step is to register the hooks the plugin provides. Any method which 
is named C<hook_$hookname> is automagically added.

Plugins should be written using standard named hook subroutines. This 
allows them to be overloaded and extended easily. Because some of the 
callback names have characters invalid in subroutine names , they must be 
translated. The current translation routine is C<s/\W/_/g;>. If you choose 
not to use the default naming convention, you need to register the hooks in 
your plugin in the C<register()> method (see below) with the 
C<register_hook()> call on the plugin object.

  sub register {
    my ($self, $qp, @args) = @_;
    $self->register_hook("mail", "mail_handler");
    $self->register_hook("rcpt", "rcpt_handler");
  }
  sub mail_handler { ... }
  sub rcpt_handler { ... }

The C<register()> method is called last. It receives the same arguments as 
C<init()>. There is no restriction, what you can do in C<register()>, but 
creating database connections and reuse them later in the process may not be
a good idea. This initialisation happens before any C<fork()> is done. 
Therefore the file handle will be shared by all qpsmtpd processes and the 
database will probably be confused if several different queries arrive on 
the same file handle at the same time (and you may get the wrong answer, if
any). This is also true for F<qpsmtpd-async> and the pperl flavours, but 
not for F<qpsmtpd> started by (x)inetd or tcpserver. 

In short: don't do it if you want to write portable plugins.

=head2 Inheritance

Inheriting methods from other plugins is an advanced topic. You can alter 
arguments for the underlying plugin, prepare something for the I<real> 
plugin or skip a hook with this. Instead of modifying C<@ISA>
directly in your plugin, use the C<isa_plugin()> method from the 
C<init()> subroutine.

  # rcpt_ok_child
  sub init {
    my ($self, $qp, @args) = @_;
    $self->isa_plugin("rcpt_ok");
  }
  
  sub hook_rcpt {
    my ($self, $transaction, $recipient) = @_;
    # do something special here...
    $self->SUPER::hook_rcpt($transaction, $recipient);
  }

=head2 Config files

Most of the existing plugins fetch their configuration data from files in the
F<config/> sub directory. This data is read at runtime and may be changed
without restarting qpsmtpd. 
B<(FIXME: caching?!)>
The contents of the files can be fetched via

  @lines = $self->qp->config("my_config");

All empty lines and lines starting with C<#> are ignored.

If you don't want to read your data from files, but from a database you can 
still use this syntax and write another plugin hooking the C<config>
hook. 

=head2 Logging

Log messages can be written to the log file (or STDERR if you use the 
F<logging/warn> plugin) with 

  $self->qp->log($loglevel, $logmessage);

The log level is one of (from low to high priority)

=over 4

=item LOGDEBUG

=item LOGINFO

=item LOGNOTICE

=item LOGWARN

=item LOGERROR

=item LOGCRIT

=item LOGALERT

=item LOGEMERG

=back

While debugging your plugins, you want to set the log level in the F<logging>
config file to I<LOGDEBUG>. This will log very much data. To restrict this 
output just to the plugin you are debugging, you can use the following plugin: 

=cut

FIXME: Test if this really works as inteded ;-)

=pod

 # logging/debug_plugin - just show LOGDEBUG messages of one plugin
 # Usage: 
 #  logging/debug_plugin my_plugin LOGLEVEL
 #
 #  LOGLEVEL is the log level for all other log messages
 use Qpsmtpd::Constants;
 
 sub register {
   my ($self, $qp, $plugin, $loglevel) = @_;
   die "no plugin name given"
     unless $plugin;
   $loglevel = "LOGWARN"
     unless defined $loglevel;
   $self->{_plugin} = $plugin;
   $self->{_level}  = Qpsmtpd::Constants::log_level($loglevel);
   $self->{_level}  = LOGWARN 
     unless defined $self->{_level};
 }
 
 sub hook_logging {
   my ($self, $transaction, $trace, $hook, $plugin, @log) = @_;
   return(OK) # drop these lines
     if $plugin ne $self->{_plugin} and $trace > $self->{_level};
   return(DECLINED);
 }

The above plugin should be loaded before the default logging plugin, which 
logs with I<LOGDEBUG>. The plugin name must be the one returned by the 
C<plugin_name()> method of the debugged plugin. This is probably not 
the same as the name of the plugin (i.e. not the same you write in the 
F<plugins> config file). In doubt: take a look in the log file for lines 
like C<queue::qmail_2dqueue hooking queue> (here: F<queue/qmail-queue> 
=E<gt> F<queue::qmail_2dqueue>).

=head2 Information about the current plugin

Each plugin inherits the public methods from C<Qpsmtpd::Plugin>. 

=over 4

=item plugin_name()

Returns the name of the currently running plugin

=item hook_name()

Returns the name of the running hook

=item auth_user()

Returns the name of the user the client is authed as (if authentication is 
used, of course)

=item auth_mechanism()

Returns the auth mechanism if authentication is used

=item connection()

Returns the C<Qpsmtpd::Connection> object associated with the current 
connection

=item transaction()

Returns the C<Qpsmtpd::Transaction> object associated with the current 
transaction

=back

=head2 Temporary Files

The temporary file and directory functions can be used for plugin specific 
workfiles and will automatically be deleted at the end of the current 
transaction.

=over 4

=item temp_file()

Returns a unique name of a file located in the default spool directory, 
but does not open that file (i.e. it is the name not a file handle).

=item temp_dir()

Returns the name of a unique directory located in the default spool 
directory, after creating the directory with 0700 rights. If you need a 
directory with different rights (say for an antivirus daemon), you will
need to use the base function C<$self-E<gt>qp-E<gt>temp_dir()>, which takes a 
single parameter for the permissions requested (see L<mkdir> for details). 
A directory created like this will not be deleted when the transaction 
is ended.

=item spool_dir()

Returns the configured system-wide spool directory.

=back


=head2 Connection and Transaction Notes

Both may be used to share notes across plugins and/or hooks. The only real
difference is their life time. The connection notes start when a new 
connection is made and end, when the connection ends. This can, for example,
be used to count the number of none SMTP commands. The plugin which uses 
this is the F<count_unrecognized_commands> plugin from the qpsmtpd core
distribution.

The transaction note starts after the B<MAIL FROM: > command and are just 
valid for the current transaction, see below in the I<reset_transaction>
hook when the transaction ends.


=head1 Return codes

Each plugin must return an allowed constant for the hook and (usually)
optionally a ``message'' for the client.
Generally all plugins for a hook are processed until one returns 
something other than I<DECLINED>.

Plugins are run in the order they are listed in the F<plugins> 
configuration file.

The return constants are defined in C<Qpsmtpd::Constants> and have
the following meanings:

=over 4

=item DECLINED

Plugin declined work; proceed as usual. This return code is I<always allowed>
unless noted otherwise.

=item OK

Action allowed.

=item DENY

Action denied.

=item DENYSOFT

Action denied; return a temporary rejection code (say B<450> instead 
of B<550>).

=item DENY_DISCONNECT

Action denied; return a permanent rejection code and disconnect the client. 
Use this for "rude" clients. Note that you're not supposed to do this 
according to the SMTP specs, but bad clients don't listen sometimes.

=item DENYSOFT_DISCONNECT

Action denied; return a temporary rejection code and disconnect the client. 
See note above about SMTP specs.

=item DONE

Finishing processing of the request. Usually used when the plugin sent the 
response to the client.

=back

The I<YIELD> constant is not mentioned here, because it is not used by
plugins directly.

=head1 SMTP hooks

This section covers the hooks, which are run in a normal SMTP connection. 
The order of these hooks is like you will (probably) see them, while a mail
is received. 

Every hook receives a C<Qpsmtpd::Plugin> object of the currently 
running plugin as the first argument. A C<Qpsmtpd::Transaction> object is 
the second argument of the current transaction in the most hooks, exceptions 
are noted in the description of the hook. If you need examples how the 
hook can be used, see the source of the plugins, which are given as 
example plugins.

=head2 hook_pre_connection

Called by a controlling process (e.g. forkserver or prefork) after accepting 
the remote server, but before beginning a new instance (or handing the 
connection to the worker process).

Useful for load-management and rereading large config files at some
frequency less than once per session.

This hook only works in the F<qpsmtpd-forkserver> and F<qpsmtpd-prefork>
flavours. 

=cut 

NOT FOR: -async, apache, -server and inetd/pperl

=pod

B<NOTE:> You should not use this hook to do major work and / or use lookup 
methods which (I<may>) take some time, like DNS lookups. This will slow down
B<all> incoming connections, no other connection will be accepted while this
hook is running!

Arguments this hook receives are:

  my ($self,$transaction,%args) = @_;
  # %args is:
  # %args = ( remote_ip    => inet_ntoa($iaddr),
  #           remote_port  => $port,
  #           local_ip     => inet_ntoa($laddr),
  #           local_port   => $lport,
  #           max_conn_ip  => $MAXCONNIP,
  #           child_addrs  => [values %childstatus],
  #         );

B<NOTE:> the C<$transaction> is of course C<undef> at this time.

Allowed return codes are

=over 4

=item DENY / DENY_DISCONNECT

returns a B<550> to the client and ends the connection

=item DENYSOFT / DENYSOFT_DISCONNECT

returns a B<451> to the client and ends the connection

=back

Anything else is ignored.

Example plugins are F<hosts_allow> and F<connection_time>. 

=head2 hook_connect

It is called at the start of a connection before the greeting is sent to 
the connecting client.

Arguments for this hook are

  my $self = shift;

B<NOTE:> in fact you get passed two more arguments, which are C<undef> at this
early stage of the connection, so ignore them.

Allowed return codes are

=over 4

=item OK

Stop processing plugins, give the default response

=item DECLINED

Process the next plugin

=item DONE

Stop processing plugins and dont give the default response, i.e. the plugin 
gave the response

=item DENY

Return hard failure code and disconnect

=item DENYSOFT

Return soft failure code and disconnect

=back

Example plugin for this hook is the F<check_relay> plugin. 

=head2 hook_helo / hook_ehlo

It is called after the client sent B<EHLO> (hook_ehlo) or B<HELO> (hook_helo)
Allowed return codes are

=over 4

=item DENY

Return a 550 code

=item DENYSOFT

Return a B<450> code

=item DENY_DISCONNECT / DENYSOFT_DISCONNECT

as above but with disconnect

=item DONE

Qpsmtpd wont do anything, the plugin sent the message

=item DECLINED 

Qpsmtpd will send the standard B<EHLO>/B<HELO> answer, of course only 
if all plugins hooking I<helo/ehlo> return I<DECLINED>.

=back

Arguments of this hook are

  my ($self, $transaction, $host) = @_;
  # $host: the name the client sent in the 
  # (EH|HE)LO line

B<NOTE:> C<$transaction> is C<undef> at this point.

=head2 hook_mail_pre

After the B<MAIL FROM: > line sent by the client is broken into 
pieces by the C<hook_mail_parse()>, this hook recieves the results.
This hook may be used to pre-accept adresses without the surrounding 
I<E<lt>E<gt>> (by adding them) or addresses like 
I<E<lt><EMAIL>.E<gt>> or I<E<lt><EMAIL> E<gt>> by 
removing the trailing I<"."> / C<" ">.

Expected return values are I<OK> and an address which must be parseable
by C<Qpsmtpd::Address-E<gt>parse()> on success or any other constant to
indicate failure.

Arguments are 

  my ($self, $transaction, $addr) = @_;

=head2 hook_mail

Called right after the envelope sender line is parsed (the B<MAIL FROM: >
command). The plugin gets passed a C<Qpsmtpd::Address> object, which means 
the parsing and verifying the syntax of the address (and just the syntax, 
no other checks) is already done. Default is to allow the sender address. 
The remaining arguments are the extensions defined in RFC 1869 (if sent by 
the client).

B<NOTE:> According to the SMTP protocol, you can not reject an invalid
sender until after the B<RCPT> stage (except for protocol errors, i.e.
syntax errors in address). So store it in an C<$transaction-E<gt>note()> and 
process it later in an rcpt hook.

Allowed return codes are

=over 4

=item OK

sender allowed

=item DENY

Return a hard failure code

=item DENYSOFT

Return a soft failure code

=item DENY_DISCONNECT / DENYSOFT_DISCONNECT

as above but with disconnect

=item DECLINED

next plugin (if any)

=item DONE

skip further processing, plugin sent response

=back

Arguments for this hook are 

  my ($self,$transaction, $sender, %args) = @_;
  # $sender: an Qpsmtpd::Address object for 
  # sender of the message

Example plugins for the C<hook_mail> are F<require_resolvable_fromhost>
and F<check_badmailfrom>.

=head2 hook_rcpt_pre

See C<hook_mail_pre>, s/MAIL FROM:/RCPT TO:/.

=head2 hook_rcpt

This hook is called after the client sent an I<RCPT TO: > command (after 
parsing the line). The given argument is parsed by C<Qpsmtpd::Address>, 
then this hook is called. Default is to deny the mail with a soft error 
code. The remaining arguments are the extensions defined in RFC 1869
(if sent by the client).

Allowed return codes

=over 4

=item OK

recipient allowed

=item DENY

Return a hard failure code, for example for an I<User does not exist here> 
message.

=item DENYSOFT

Return a soft failure code, for example if the connect to a user lookup 
database failed

=item DENY_DISCONNECT / DENYSOFT_DISCONNECT

as above but with disconnect

=item DONE

skip further processing, plugin sent response

=back

Arguments are

  my ($self, $transaction, $recipient, %args) = @_;
  # $rcpt = Qpsmtpd::Address object with 
  # the given recipient address

Example plugin is F<rcpt_ok>.

=head2 hook_data

After the client sent the B<DATA> command, before any data of the message
was sent, this hook is called. 

B<NOTE:> This hook, like B<EHLO>, B<VRFY>, B<QUIT>, B<NOOP>, is an 
endpoint of a pipelined command group (see RFC 1854) and may be used to 
detect ``early talkers''. Since svn revision 758 the F<check_earlytalker>
plugin may be configured to check at this hook for ``early talkers''.

Allowed return codes are

=over 4

=item DENY

Return a hard failure code

=item DENYSOFT

Return a soft failure code

=item DENY_DISCONNECT / DENYSOFT_DISCONNECT

as above but with disconnect

=item DONE

Plugin took care of receiving data and calling the queue (not recommended)

B<NOTE:> The only real use for I<DONE> is implementing other ways of
receiving the message, than the default... for example the CHUNKING SMTP
extension (RFC 1869, 1830/3030) ... a plugin for this exists at 
http://svn.perl.org/qpsmtpd/contrib/vetinari/experimental/chunking, but it
was never tested ``in the wild''.

=back

Arguments:

  my ($self, $transaction) = @_;

Example plugin is F<greylisting>.

=head2 hook_data_post

The C<data_post> hook is called after the client sent the final C<.\r\n> 
of a message, before the mail is sent to the queue.

Allowed return codes are

=over 4

=item DENY

Return a hard failure code

=item DENYSOFT

Return a soft failure code<commit_msg>include received_line hook from ../README.plugins<commit_after>#
# This file is best read with ``perldoc plugins.pod''
#

### 
# Conventions:
#  plugin names:  F<myplugin>, F<qpsmtpd-async>
#  constants:     I<LOGDEBUG>
#  smtp commands, answers: B<HELO>, B<250 Queued!>
#
# Notes: 
#  * due to restrictions of some POD parsers, no C<<$object->method()>>
#    are allowed, use C<$object-E<gt>method()> 
# 

=head1 Introduction

Plugins are the heart of qpsmtpd. The core implements only basic SMTP protocol
functionality. No useful function can be done by qpsmtpd without loading 
plugins.

Plugins are loaded on startup where each of them register their interest in 
various I<hooks> provided by the qpsmtpd core engine.

At least one plugin B<must> allow or deny the B<RCPT> command to enable 
receiving mail. The F<check_relay> plugin is the standard plugin for this.
Other plugins provide extra functionality related to this; for example the
F<require_resolvable_fromhost> plugin.

=head2 Loading Plugins

The list of plugins to load are configured in the I<config/plugins>
configuration file. One plugin per line, empty lines and lines starting
with I<#> are ignored. The order they are loaded is the same as given 
in this config file. This is also the order the registered I<hooks>
are run. The plugins are loaded from the F<plugins/> directory or 
from a subdirectory of it. If a plugin should be loaded from such a 
subdirectory, the directory must also be given, like the 
F<virus/clamdscan> in the example below. Alternate plugin directories
may be given in the F<config/plugin_dirs> config file, one directory
per line, these will be searched first before using the builtin fallback
of F<plugins/> relative to the qpsmtpd root directory. It may be 
necessary, that the F<config/plugin_dirs> must be used (if you're using 
F<Apache::Qpsmtpd>, for example).

Some plugins may be configured by passing arguments in the F<plugins>
config file.

A plugin can be loaded two or more times with different arguments by adding
I<:N> to the plugin filename, with I<N> being a number, usually starting at 
I<0>. 

Another method to load a plugin is to create a valid perl module, drop this
module in perl's C<@INC> path and give the name of this module as
plugin name. The only restriction to this is, that the module name B<must>
contain I<::>, e.g. C<My::Plugin> would be ok, C<MyPlugin> not. Appending of
I<:0>, I<:1>, ... does not work with module plugins.

 check_relay
 virus/clamdscan
 spamassassin reject_threshold 7
 my_rcpt_check example.com
 my_rcpt_check:0 example.org
 My::Plugin

=head1 Anatomy of a plugin

A plugin has at least one method, which inherits from the 
C<Qpsmtpd::Plugin> object. The first argument for this method is always the 
plugin object itself (and usually called C<$self>). The most simple plugin 
has one method with a predefined name which just returns one constant.

 # plugin temp_disable_connection
 sub hook_connect {
    return(DENYSOFT, "Sorry, server is temporarily unavailable.");
 }

While this is a valid plugin, it is not very useful except for rare 
circumstances. So let us see what happens when a plugin is loaded.

=head2 Initialisation

After the plugin is loaded the C<init()> method of the plugin is called, 
if present. The arguments passed to C<init()> are 

=over 4

=item $self 

the current plugin object, usually called C<$self>

=item $qp

the Qpsmtpd object, usually called C<$qp>.

=item @args

the values following the plugin name in the F<plugins> config, split by 
white space. These arguments can be used to configure the plugin with 
default and/or static config settings, like database paths, 
timeouts, ...

=back

This is mainly used for inheriting from other plugins, but may be used to do
the same as in C<register()>.

The next step is to register the hooks the plugin provides. Any method which 
is named C<hook_$hookname> is automagically added.

Plugins should be written using standard named hook subroutines. This 
allows them to be overloaded and extended easily. Because some of the 
callback names have characters invalid in subroutine names , they must be 
translated. The current translation routine is C<s/\W/_/g;>. If you choose 
not to use the default naming convention, you need to register the hooks in 
your plugin in the C<register()> method (see below) with the 
C<register_hook()> call on the plugin object.

  sub register {
    my ($self, $qp, @args) = @_;
    $self->register_hook("mail", "mail_handler");
    $self->register_hook("rcpt", "rcpt_handler");
  }
  sub mail_handler { ... }
  sub rcpt_handler { ... }

The C<register()> method is called last. It receives the same arguments as 
C<init()>. There is no restriction, what you can do in C<register()>, but 
creating database connections and reuse them later in the process may not be
a good idea. This initialisation happens before any C<fork()> is done. 
Therefore the file handle will be shared by all qpsmtpd processes and the 
database will probably be confused if several different queries arrive on 
the same file handle at the same time (and you may get the wrong answer, if
any). This is also true for F<qpsmtpd-async> and the pperl flavours, but 
not for F<qpsmtpd> started by (x)inetd or tcpserver. 

In short: don't do it if you want to write portable plugins.

=head2 Inheritance

Inheriting methods from other plugins is an advanced topic. You can alter 
arguments for the underlying plugin, prepare something for the I<real> 
plugin or skip a hook with this. Instead of modifying C<@ISA>
directly in your plugin, use the C<isa_plugin()> method from the 
C<init()> subroutine.

  # rcpt_ok_child
  sub init {
    my ($self, $qp, @args) = @_;
    $self->isa_plugin("rcpt_ok");
  }
  
  sub hook_rcpt {
    my ($self, $transaction, $recipient) = @_;
    # do something special here...
    $self->SUPER::hook_rcpt($transaction, $recipient);
  }

=head2 Config files

Most of the existing plugins fetch their configuration data from files in the
F<config/> sub directory. This data is read at runtime and may be changed
without restarting qpsmtpd. 
B<(FIXME: caching?!)>
The contents of the files can be fetched via

  @lines = $self->qp->config("my_config");

All empty lines and lines starting with C<#> are ignored.

If you don't want to read your data from files, but from a database you can 
still use this syntax and write another plugin hooking the C<config>
hook. 

=head2 Logging

Log messages can be written to the log file (or STDERR if you use the 
F<logging/warn> plugin) with 

  $self->qp->log($loglevel, $logmessage);

The log level is one of (from low to high priority)

=over 4

=item LOGDEBUG

=item LOGINFO

=item LOGNOTICE

=item LOGWARN

=item LOGERROR

=item LOGCRIT

=item LOGALERT

=item LOGEMERG

=back

While debugging your plugins, you want to set the log level in the F<logging>
config file to I<LOGDEBUG>. This will log very much data. To restrict this 
output just to the plugin you are debugging, you can use the following plugin: 

=cut

FIXME: Test if this really works as inteded ;-)

=pod

 # logging/debug_plugin - just show LOGDEBUG messages of one plugin
 # Usage: 
 #  logging/debug_plugin my_plugin LOGLEVEL
 #
 #  LOGLEVEL is the log level for all other log messages
 use Qpsmtpd::Constants;
 
 sub register {
   my ($self, $qp, $plugin, $loglevel) = @_;
   die "no plugin name given"
     unless $plugin;
   $loglevel = "LOGWARN"
     unless defined $loglevel;
   $self->{_plugin} = $plugin;
   $self->{_level}  = Qpsmtpd::Constants::log_level($loglevel);
   $self->{_level}  = LOGWARN 
     unless defined $self->{_level};
 }
 
 sub hook_logging {
   my ($self, $transaction, $trace, $hook, $plugin, @log) = @_;
   return(OK) # drop these lines
     if $plugin ne $self->{_plugin} and $trace > $self->{_level};
   return(DECLINED);
 }

The above plugin should be loaded before the default logging plugin, which 
logs with I<LOGDEBUG>. The plugin name must be the one returned by the 
C<plugin_name()> method of the debugged plugin. This is probably not 
the same as the name of the plugin (i.e. not the same you write in the 
F<plugins> config file). In doubt: take a look in the log file for lines 
like C<queue::qmail_2dqueue hooking queue> (here: F<queue/qmail-queue> 
=E<gt> F<queue::qmail_2dqueue>).

=head2 Information about the current plugin

Each plugin inherits the public methods from C<Qpsmtpd::Plugin>. 

=over 4

=item plugin_name()

Returns the name of the currently running plugin

=item hook_name()

Returns the name of the running hook

=item auth_user()

Returns the name of the user the client is authed as (if authentication is 
used, of course)

=item auth_mechanism()

Returns the auth mechanism if authentication is used

=item connection()

Returns the C<Qpsmtpd::Connection> object associated with the current 
connection

=item transaction()

Returns the C<Qpsmtpd::Transaction> object associated with the current 
transaction

=back

=head2 Temporary Files

The temporary file and directory functions can be used for plugin specific 
workfiles and will automatically be deleted at the end of the current 
transaction.

=over 4

=item temp_file()

Returns a unique name of a file located in the default spool directory, 
but does not open that file (i.e. it is the name not a file handle).

=item temp_dir()

Returns the name of a unique directory located in the default spool 
directory, after creating the directory with 0700 rights. If you need a 
directory with different rights (say for an antivirus daemon), you will
need to use the base function C<$self-E<gt>qp-E<gt>temp_dir()>, which takes a 
single parameter for the permissions requested (see L<mkdir> for details). 
A directory created like this will not be deleted when the transaction 
is ended.

=item spool_dir()

Returns the configured system-wide spool directory.

=back


=head2 Connection and Transaction Notes

Both may be used to share notes across plugins and/or hooks. The only real
difference is their life time. The connection notes start when a new 
connection is made and end, when the connection ends. This can, for example,
be used to count the number of none SMTP commands. The plugin which uses 
this is the F<count_unrecognized_commands> plugin from the qpsmtpd core
distribution.

The transaction note starts after the B<MAIL FROM: > command and are just 
valid for the current transaction, see below in the I<reset_transaction>
hook when the transaction ends.


=head1 Return codes

Each plugin must return an allowed constant for the hook and (usually)
optionally a ``message'' for the client.
Generally all plugins for a hook are processed until one returns 
something other than I<DECLINED>.

Plugins are run in the order they are listed in the F<plugins> 
configuration file.

The return constants are defined in C<Qpsmtpd::Constants> and have
the following meanings:

=over 4

=item DECLINED

Plugin declined work; proceed as usual. This return code is I<always allowed>
unless noted otherwise.

=item OK

Action allowed.

=item DENY

Action denied.

=item DENYSOFT

Action denied; return a temporary rejection code (say B<450> instead 
of B<550>).

=item DENY_DISCONNECT

Action denied; return a permanent rejection code and disconnect the client. 
Use this for "rude" clients. Note that you're not supposed to do this 
according to the SMTP specs, but bad clients don't listen sometimes.

=item DENYSOFT_DISCONNECT

Action denied; return a temporary rejection code and disconnect the client. 
See note above about SMTP specs.

=item DONE

Finishing processing of the request. Usually used when the plugin sent the 
response to the client.

=back

The I<YIELD> constant is not mentioned here, because it is not used by
plugins directly.

=head1 SMTP hooks

This section covers the hooks, which are run in a normal SMTP connection. 
The order of these hooks is like you will (probably) see them, while a mail
is received. 

Every hook receives a C<Qpsmtpd::Plugin> object of the currently 
running plugin as the first argument. A C<Qpsmtpd::Transaction> object is 
the second argument of the current transaction in the most hooks, exceptions 
are noted in the description of the hook. If you need examples how the 
hook can be used, see the source of the plugins, which are given as 
example plugins.

=head2 hook_pre_connection

Called by a controlling process (e.g. forkserver or prefork) after accepting 
the remote server, but before beginning a new instance (or handing the 
connection to the worker process).

Useful for load-management and rereading large config files at some
frequency less than once per session.

This hook only works in the F<qpsmtpd-forkserver> and F<qpsmtpd-prefork>
flavours. 

=cut 

NOT FOR: -async, apache, -server and inetd/pperl

=pod

B<NOTE:> You should not use this hook to do major work and / or use lookup 
methods which (I<may>) take some time, like DNS lookups. This will slow down
B<all> incoming connections, no other connection will be accepted while this
hook is running!

Arguments this hook receives are:

  my ($self,$transaction,%args) = @_;
  # %args is:
  # %args = ( remote_ip    => inet_ntoa($iaddr),
  #           remote_port  => $port,
  #           local_ip     => inet_ntoa($laddr),
  #           local_port   => $lport,
  #           max_conn_ip  => $MAXCONNIP,
  #           child_addrs  => [values %childstatus],
  #         );

B<NOTE:> the C<$transaction> is of course C<undef> at this time.

Allowed return codes are

=over 4

=item DENY / DENY_DISCONNECT

returns a B<550> to the client and ends the connection

=item DENYSOFT / DENYSOFT_DISCONNECT

returns a B<451> to the client and ends the connection

=back

Anything else is ignored.

Example plugins are F<hosts_allow> and F<connection_time>. 

=head2 hook_connect

It is called at the start of a connection before the greeting is sent to 
the connecting client.

Arguments for this hook are

  my $self = shift;

B<NOTE:> in fact you get passed two more arguments, which are C<undef> at this
early stage of the connection, so ignore them.

Allowed return codes are

=over 4

=item OK

Stop processing plugins, give the default response

=item DECLINED

Process the next plugin

=item DONE

Stop processing plugins and dont give the default response, i.e. the plugin 
gave the response

=item DENY

Return hard failure code and disconnect

=item DENYSOFT

Return soft failure code and disconnect

=back

Example plugin for this hook is the F<check_relay> plugin. 

=head2 hook_helo / hook_ehlo

It is called after the client sent B<EHLO> (hook_ehlo) or B<HELO> (hook_helo)
Allowed return codes are

=over 4

=item DENY

Return a 550 code

=item DENYSOFT

Return a B<450> code

=item DENY_DISCONNECT / DENYSOFT_DISCONNECT

as above but with disconnect

=item DONE

Qpsmtpd wont do anything, the plugin sent the message

=item DECLINED 

Qpsmtpd will send the standard B<EHLO>/B<HELO> answer, of course only 
if all plugins hooking I<helo/ehlo> return I<DECLINED>.

=back

Arguments of this hook are

  my ($self, $transaction, $host) = @_;
  # $host: the name the client sent in the 
  # (EH|HE)LO line

B<NOTE:> C<$transaction> is C<undef> at this point.

=head2 hook_mail_pre

After the B<MAIL FROM: > line sent by the client is broken into 
pieces by the C<hook_mail_parse()>, this hook recieves the results.
This hook may be used to pre-accept adresses without the surrounding 
I<E<lt>E<gt>> (by adding them) or addresses like 
I<E<lt><EMAIL>.E<gt>> or I<E<lt><EMAIL> E<gt>> by 
removing the trailing I<"."> / C<" ">.

Expected return values are I<OK> and an address which must be parseable
by C<Qpsmtpd::Address-E<gt>parse()> on success or any other constant to
indicate failure.

Arguments are 

  my ($self, $transaction, $addr) = @_;

=head2 hook_mail

Called right after the envelope sender line is parsed (the B<MAIL FROM: >
command). The plugin gets passed a C<Qpsmtpd::Address> object, which means 
the parsing and verifying the syntax of the address (and just the syntax, 
no other checks) is already done. Default is to allow the sender address. 
The remaining arguments are the extensions defined in RFC 1869 (if sent by 
the client).

B<NOTE:> According to the SMTP protocol, you can not reject an invalid
sender until after the B<RCPT> stage (except for protocol errors, i.e.
syntax errors in address). So store it in an C<$transaction-E<gt>note()> and 
process it later in an rcpt hook.

Allowed return codes are

=over 4

=item OK

sender allowed

=item DENY

Return a hard failure code

=item DENYSOFT

Return a soft failure code

=item DENY_DISCONNECT / DENYSOFT_DISCONNECT

as above but with disconnect

=item DECLINED

next plugin (if any)

=item DONE

skip further processing, plugin sent response

=back

Arguments for this hook are 

  my ($self,$transaction, $sender, %args) = @_;
  # $sender: an Qpsmtpd::Address object for 
  # sender of the message

Example plugins for the C<hook_mail> are F<require_resolvable_fromhost>
and F<check_badmailfrom>.

=head2 hook_rcpt_pre

See C<hook_mail_pre>, s/MAIL FROM:/RCPT TO:/.

=head2 hook_rcpt

This hook is called after the client sent an I<RCPT TO: > command (after 
parsing the line). The given argument is parsed by C<Qpsmtpd::Address>, 
then this hook is called. Default is to deny the mail with a soft error 
code. The remaining arguments are the extensions defined in RFC 1869
(if sent by the client).

Allowed return codes

=over 4

=item OK

recipient allowed

=item DENY

Return a hard failure code, for example for an I<User does not exist here> 
message.

=item DENYSOFT

Return a soft failure code, for example if the connect to a user lookup 
database failed

=item DENY_DISCONNECT / DENYSOFT_DISCONNECT

as above but with disconnect

=item DONE

skip further processing, plugin sent response

=back

Arguments are

  my ($self, $transaction, $recipient, %args) = @_;
  # $rcpt = Qpsmtpd::Address object with 
  # the given recipient address

Example plugin is F<rcpt_ok>.

=head2 hook_data

After the client sent the B<DATA> command, before any data of the message
was sent, this hook is called. 

B<NOTE:> This hook, like B<EHLO>, B<VRFY>, B<QUIT>, B<NOOP>, is an 
endpoint of a pipelined command group (see RFC 1854) and may be used to 
detect ``early talkers''. Since svn revision 758 the F<check_earlytalker>
plugin may be configured to check at this hook for ``early talkers''.

Allowed return codes are

=over 4

=item DENY

Return a hard failure code

=item DENYSOFT

Return a soft failure code

=item DENY_DISCONNECT / DENYSOFT_DISCONNECT

as above but with disconnect

=item DONE

Plugin took care of receiving data and calling the queue (not recommended)

B<NOTE:> The only real use for I<DONE> is implementing other ways of
receiving the message, than the default... for example the CHUNKING SMTP
extension (RFC 1869, 1830/3030) ... a plugin for this exists at 
http://svn.perl.org/qpsmtpd/contrib/vetinari/experimental/chunking, but it
was never tested ``in the wild''.

=back

Arguments:

  my ($self, $transaction) = @_;

Example plugin is F<greylisting>.

=head2 hook_received_line

If you wish to provide your own Received header line, do it here. You can use
or discard any of the given arguments (see below).

Allowed return codes:

=over 4

=item OK, $string

use this string for the Received header.

=item anything else

use the default Received header

=back

Arguments are

 my ($self, $transaction, $smtp, $auth, $sslinfo) = @_;
 # $smtp - the SMTP type used (e.g. "SMTP" or "ESMTP").
 # $auth - the Auth header additionals.
 # $sslinfo - information about SSL for the header.

=head2 hook_data_post

The C<data_post> hook is called after the client sent the final C<.\r\n> 
of a message, before the mail is sent to the queue.

Allowed return codes are

=over 4

=item DENY

Return a hard failure code

=item DENYSOFT

Return a soft failure code
{'fraction_non_alphanumeric': 0.07044371384152713, 'fraction_numerical': 0.004740423579784387, 'mean_word_length': 4.123123123123123, 'pattern_counts': {'":': 0, '<': 319, '<?xml version=': 0, '>': 363, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5347932', 'n_tokens_mistral': 12103, 'n_tokens_neox': 11697, 'n_words': 5667}