Sendma...PMilter(3pm)

πŸ’– LICENSE πŸ’–

okay bestie, legal girlies first, because we respect the ✨copyright✨ around here:

Copyright (c) 2016-2026 G.W. Haywood. All rights reserved.

With thanks to all those who have trodden these paths before, including Copyright (c) 2002-2004 Todd Vierling. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notices, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notices, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  3. Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. In the case of G.W. Haywood this permission is hereby now granted.

and now the dramatic part, presented exactly as written, because legal text is not a vibe you get to remix:

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

🌸 NAME 🌸

Sendma...PMilter(3pm) β€” yes babe, the manual name really does get chopped off like that in the header, that's just how these pages roll. What it actually is is Sendmail::PMilter, the Perl binding of the Sendmail Milter protocol. πŸ¦‹


✨ SYNOPSIS ✨

    use Sendmail::PMilter;

    my $milter = new Sendmail::PMilter;

    $milter->auto_setconn(NAME);
    $milter->register(NAME, { CALLBACKS }[, FLAGS]);
    $milter->main();

πŸ’… DESCRIPTION πŸ’…

Sendmail::PMilter is a mail filtering API that implements the Sendmail Milter Protocol in Perl. What that means for you, bestie, is that the admin of Sendmail (and maybe other MTAs that also speak the Milter Protocol) can write pure Perl code to filter and modify mail while an SMTP connection is happening. no C required, we stay in our lane and our lane is Perl. 🫢

Over the years, the protocol governing the conversation between Sendmail and its milters has been through a whole bunch of revisions. it's been through eras, honestly.

This documentation is for Sendmail::PMilter versions 1.20 and later, which now support Milter Protocol Version 6. That is a substantial glow-up from earlier versions, which at best supported up to Milter Protocol Version 2 β€” and that one was first seen in Sendmail version 8.14.0, released on January 31st 2007. yes, we're doing history today. πŸ“œ

Also very important: Sendmail::PMilter now uses neither the original Sendmail::Milter (which is obsolete, badly flawed and unmaintained β€” do not look at it, it's giving cursed) nor the Sendmail::Milter that was packaged with earlier versions of Sendmail::PMilter as a temporary workaround for the broken original. we've moved on. we've healed. 🌈

For communications between the MTA and the milter, a 'dispatcher' acts as a go-between. You must choose one when the milter is initialized, before it serves requests. Several dispatchers ship inside the Sendmail::PMilter module, but heads up: in versions before 1.20 all the dispatchers suffered from issues of varying gravity. 😭 The prefork dispatcher (see DISPATCHERS below) has now been extensively exercised by the current maintainer β€” but although the others have been patched from issue reports going back more than a decade from the time of writing (June 2019), THEY HAVE NOT BEEN TESTED. Feedback via the CPAN issue tracking system is encouraged, fr fr. And if you've developed your own dispatcher, you can either pass a code reference to set_dispatcher() or set an environment variable to point to it β€” Sendmail::PMilter will then use yours instead of a built-in one. main character move. πŸ‘‘


πŸ‘‘ METHODS πŸ‘‘

get_max_interpreters()

Returns the maximum number of interpreters passed to main(). This is only useful when called from within the dispatcher, because it is not set before main() is called. (so like, timing matters, bestie.)

get_max_requests()

Returns the maximum number of requests per interpreter passed to main(). Same deal: this is only useful when called from within the dispatcher, since it is not set before main() is called.

main([MAXCHILDREN[, MAXREQ]])

This is the last method called in the main block of a milter program. If it's successful, this call never returns β€” the protocol engine launches and starts accepting connections. you hand over the keys and off it goes. πŸš—πŸ’¨

MAXCHILDREN (default 0, meaning unlimited) specifies the maximum number of connections that may be serviced simultaneously. If a connection arrives while the number of active connections is above this limit, the milter will immediately return a temporary failure condition and close the connection. Passing a value for MAXCHILDREN is optional.

MAXREQ (default 0, meaning unlimited) is the maximum number of requests that a child may service before being recycled. Note the fine print: it is not guaranteed that the interpreter will service this many requests, only that it will not go over the limit. And MAXCHILDREN must be given if MAXREQ is to be set.

Any callback which dies will have its output sent to warn, followed by a clean shutdown of the milter connection. To catch any warnings generated by the callbacks, and any error messages caused by a die, set $SIG{__WARN__} to a user-defined subroutine. (See perlvar.)

register(NAME, CALLBACKS[, FLAGS])

Sets up the main milter loop configuration. the setup era. πŸŽ€

NAME is the name of the milter. It should be the same name as passed to auto_getconn() or auto_setconn() β€” but this PMilter implementation does not enforce that, so it's a suggestion, not a bouncer. πŸ’€

CALLBACKS is a hash reference containing one or more callback subroutines. For example:

  my %callbacks =
  (
    'negotiate' => \&my_negotiate_callback,
    'connect'   => \&my_connect_callback,
    'helo'      => \&my_helo_callback,
    'envfrom'   => \&my_envfrom_callback,
    'close'     => \&my_close_callback,
    'abort'     => \&my_abort_callback,
  );
  $milter->register( $milter_name, \%callbacks );

If a callback is not named in this hashref, the caller's package will be searched for subroutines named CALLBACK_callback, where CALLBACK is the name of the callback function. so it'll go looking for you. πŸ‘€

FLAGS is accepted for backward compatibility with older versions of this module. Consider it deprecated. Set it to SMFI_V6_PROT for all available 'actions' in any recent (last few years) Sendmail version.

If no negotiate callback is registered, then by default the protocol steps available are as described in .../libmilter/engine.c in the Sendmail sources. That means all the registered CALLBACKS plus the SKIP function call which is allowed in the End Of Message callback. Note that SMFIP_RCPT_REJ is specifically not included. πŸ™ˆ

register() must be called successfully exactly once. If called a second time, the previously registered callbacks will be erased. (so don't do that, bestie, that's a delete button you did not mean to press.)

Returns 1 on success, undef on failure.

setconn(DESC[, PERMS])

Sets up the server socket with connection descriptor DESC. This is identical to the descriptor syntax used by the X milter configuration lines in sendmail.cf (if using Sendmail). It should be one of the following:

local:PATH

A local ("UNIX") socket on the filesystem, named PATH. This has some smarts that will auto-delete the pathname if it seems that the milter is not currently running β€” but this currently contains a race condition that may not be fixable; at worst, there could be two milters running with one never receiving connections. 😭 iconic behaviour, honestly.

inet:PORT[@HOST]

An IPv4 socket, bound to address HOST (default INADDR_ANY), on port PORT. It is not recommended to open milter engines to the world, so the @HOST part should be specified. protect your peace. 🫢

inet6:PORT[@HOST]

An IPv6 socket, bound to address HOST (default INADDR_ANY), on port PORT. This requires IPv6 support and the Perl IO::Socket::IP package to be installed. It is not recommended to open milter engines to the world, so the @HOST part SHOULD be specified. (yes, in capitals, it's serious.)

PERMS

Optional permissions mask.

Returns a true value on success, undef on failure.

set_dispatcher(CODEREF)

Sets the dispatcher used to accept socket connections and hand them off to the protocol engine. This allows pluggable resource allocation, so your milter script may use fork, threads, or any other such means of handling milter connections. See "DISPATCHERS" below for more information.

The subroutine (code) reference will be called by main() when the listening socket object is prepared and ready to accept connections. It will be passed the arguments:

    MILTER, LSOCKET, HANDLER

MILTER is the milter object currently running. LSOCKET is a listening socket (an instance of IO::Socket), upon which accept() should be called. HANDLER is a subroutine reference which should be called, passing the socket object returned by LSOCKET->accept().

Note that the dispatcher may also be set from one of the off-the-shelf dispatchers noted in this document by setting the PMILTER_DISPATCHER environment variable. See "DISPATCHERS", below. 🌟

set_listen(BACKLOG)

Set the socket listen backlog to BACKLOG. The default is 5 connections if not set explicitly by this method. Only useful before calling main(). so, like, do it early or don't bother. πŸ’…

set_socket(SOCKET)

Rather than calling setconn(), this method may be called explicitly to set the IO::Socket instance used to accept inbound connections.

πŸ’– SENDMAIL-SPECIFIC METHODS πŸ’–

okay so bestie, heads up: everything in this whole section only works if Sendmail is the actual MTA sliding into this milter's DMs πŸ’Œ. Other MTAs probably don't even read Sendmail's config file, so like… these methods would just be giving nothing. πŸ™ˆ


### auto_getconn(NAME[, CONFIG])

Returns the connection descriptor for milter NAME inside the Sendmail configuration file CONFIG (which defaults to "/etc/mail/sendmail.cf", or whatever set_sendmail_cf() set it to). The whole point is that you can then yeet it straight into setconn(), down below.

Returns a true value when it works, undef when it doesn't. no cap. 😭

### auto_setconn(NAME[, CONFIG])

Creates the server connection socket for milter NAME in the Sendmail configuration file CONFIG.

Essentially it's doing this iconic little move:

$milter->setconn($milter->auto_getconn(NAME, CONFIG))

True value on success, undef on failure. πŸ’…

### get_sendmail_cf()

Returns the pathname of the Sendmail configuration file. If set_sendmail_cf() already set it, that's what you get. Otherwise you get the default pathname "/etc/mail/sendmail.cf". πŸŽ€

### get_sendmail_class(CLASS[, CONFIG])

Returns a list holding every single member of the Sendmail class CLASS, in Sendmail configuration file CONFIG (default "/etc/mail/sendmail.cf", or whatever set_sendmail_cf() set). The classic use case: looking up the entries in class "w", aka the local hostnames class. ✨

### get_sendmail_option(OPTION[, CONFIG])

Returns a list containing the first occurrence of Sendmail option OPTION in the Sendmail configuration file CONFIG (default "/etc/mail/sendmail.cf", or whatever set_sendmail_cf() set). Gives you the value of the option, or undef if it's simply not there. Perfect for learning config parameters like Milter.maxdatasize. πŸ‘‘

### set_sendmail_cf(FILENAME)

Sets the default filename that auto_getconn, auto_setconn, and sendmail_class use to find Sendmail-specific configuration data. If you never explicitly set it with this method, it defaults to "/etc/mail/sendmail.cf". Returns 1. 🌸


πŸ¦‹ DISPATCHERS πŸ¦‹

Milter requests can be dispatched to the protocol handler in a pluggable way (peep the description of the set_dispatcher() method above, iykyk). Sendmail::PMilter comes with some off-the-shelf dispatchers that use different methods of resource allocation β€” like, different flavors of the same slay. 🧚

Each one of these is referenced as a non-object function, and each returns a value you can pass directly to set_dispatcher(). so convenient fr fr.


πŸ’€ Sendmail::PMilter::ithread_dispatcher()

(environment) PMILTER_DISPATCHER=ithread

June 2019: This dispatcher has not been tested adequately. 🚩

The "ithread" dispatcher spins up a brand new thread on every single connection to the milter socket. It's a thread-based model that may be more resource efficient than the similar "postfork" dispatcher. This requires that the Perl interpreter be compiled with -Duseithreads, and it uses the threads module (which is only available on Perl 5.8 or later). 🧡

🌈 Sendmail::PMilter::prefork_dispatcher([PARAMS])

(environment) PMILTER_DISPATCHER=prefork

June 2019: This dispatcher has been tested extensively by the maintainer. βœ…

The "prefork" dispatcher forks the main Perl process before accepting connections, and uses the main process to monitor the children. This should be appropriate for steady traffic flow sites. ngl, note that if MAXINTERP is not set in the call to main() or in PARAMS, an internal default of 10 processes gets used; and similarly, if MAXREQ isn't set, 100 requests will be served per child.

Currently the child process pool is fixed in size: discarded children get replaced immediately. πŸ”„

PARAMS, if you specify it, is a hash of key-value pairs defining parameters for the dispatcher. The available parameters you can set are:

  • child_init β€” a subroutine reference that gets called after each child process is forked. It will be passed the "MILTER" object.
  • child_exit β€” a subroutine reference that gets called just before each child process terminates. It will be passed the "MILTER" object plus current requests handled and maximum requests per child.
  • milter_exit β€” a subroutine reference that gets called just before the milter terminates. It will be passed the "MILTER" object.
  • max_children β€” Maximum number of child processes active at any time. Equivalent to the MAXINTERP option to main() β€” if it's not set in the main() call, this value will be used instead.
  • max_requests_per_child β€” Maximum number of requests a child process may service before being recycled. Equivalent to the MAXREQ option to main() β€” if it's not set in the main() call, this value will be used instead.

πŸŽ€ Sendmail::PMilter::postfork_dispatcher()

(environment) PMILTER_DISPATCHER=postfork

June 2019: This dispatcher has not been tested adequately. 🚩

This one is the default dispatcher for PMilter if you don't set an explicit dispatcher. no notes. πŸ‘‘

The "postfork" dispatcher forks the main Perl process upon each connection to the milter socket. Adequate for machines that get bursty but are otherwise mostly idle on mail traffic, because the idle-time resource consumption is very low. πŸŒ™

If the maximum number of interpreters is already running when a new connection comes in, this dispatcher blocks until a slot opens up for a new interpreter. bestie will literally just wait there. πŸ’€

⭐ Sendmail::PMilter::sequential_dispatcher()

(environment) PMILTER_DISPATCHER=sequential

June 2019: This dispatcher has not been tested adequately. 🚩

The "sequential" dispatcher forces one request to be served at a time, making all the other requests wait on the socket for the next pass through the loop. Not suitable for most production installations, but honestly it may be quite useful for milter debugging or other software development purposes. πŸ›

⚠️ Note that, because the default socket backlog is 5 connections, if you use this dispatcher it may be wise to increase that backlog by calling set_listen() before entering main().

✨ EXPORTS ✨

Each of these symbols may be imported explicitly, imported with the tag ":all", or referenced as part of the "Sendmail::PMilter::" package. pick your lane, girlie πŸ’…

Callback Return Values

  • SMFIS_CONTINUE β€” continue processing the message
  • SMFIS_REJECT β€” reject the message with a 5xx error
  • SMFIS_DISCARD β€” accept, but discard the message
  • SMFIS_ACCEPT β€” accept the message without further processing
  • SMFIS_TEMPFAIL β€” reject the message with a 4xx error
  • SMFIS_MSG_LOOP β€” send a never-ending response to the HELO command

In the "envrcpt" callback, SMFIS_REJECT and SMFIS_TEMPFAIL will reject only the current recipient. Message processing will continue for any other recipients just like SMFIS_CONTINUE had been returned. 🫢

In all callbacks, SMFIS_CONTINUE tells the MTA to keep calling the milter (and any other milters that may be installed) for the remaining message steps. Except as noted for the "envrcpt" callback, all the other return values terminate processing of the message by all the installed milters. Message disposal is according to the return value. so yeah, choose wisely. 😭


πŸ”’ SECURITY CONSIDERATIONS πŸ”’

Running as root

Running Perl as root is dangerous. Running Sendmail::PMilter as root may well be system-assisted suicide at this point πŸ’€. So don't do that. periodt.

More specifically though, it is possible to run a milter frontend as root, in order to gain access to network resources (like a filesystem socket in /var/run), and then drop privileges before accepting connections. To do that, insert drop-privileges code between the calls to setconn/auto_setconn and main; for instance:

$milter->auto_setconn('pmilter');
$> = 65534; # drop root privileges
$milter->main();

The semantics of properly dropping system administrator privileges in Perl are, unfortunately, somewhat OS-specific, so this process is not described in detail here. πŸ’…


πŸ‘‘ AUTHORS πŸ‘‘

Todd Vierling, Ged Haywood.

Maintenance

cpan:GWHAYWOOD now maintains Sendmail::PMilter. Use the CPAN issue tracking system to request more information, or to comment. Private mail is fine but you'll need to use the right email address β€” it should be obvious. πŸ’Œ This module is NOT maintained on Sourceforge/Github/etc.. 😀

See also

Sendmail::PMilter::Context

The Sendmail documentation, especially libmilter/docs/* in the sources of Sendmail version 8.15.2 and later. πŸ“š


🌸 THANKS 🌸

rob.casey@bluebottle.com - for the prefork mechanism idea Carlos Velasco - for milter_exit and other improvements


and that's the whole manual page bestie, we ate and left no crumbs πŸ“βœ¨ this little love letter to Sendmail comes from User Contributed Perl Documentation, perl v5.40.1, dated 2026-07-05 β€” go forth and milter responsibly πŸ«ΆπŸ’œ

πŸ“¦ where this page comes from