\input texinfo @c -*-texinfo-*- @smallbook @c %**start of header @setfilename mailfromd.info @settitle Mailfromd @c %**end of header @setchapternewpage odd @defcodeindex pr @defcodeindex op @c mt is the same as op, but used for mtasim options. @defcodeindex mt @defcodeindex kw @defcodeindex fl @syncodeindex fn cp @syncodeindex vr cp @syncodeindex ky cp @syncodeindex mt cp @syncodeindex pg cp @syncodeindex tp cp @syncodeindex op cp @syncodeindex pr cp @syncodeindex kw cp @syncodeindex fl cp @include version.texi @include rendition.texi @include macros.texi @include values.texi @ifinfo @dircategory Email @direntry * Mailfromd: (mailfromd). General-purpose mail-filtering software. * mailfromd: (mailfromd) invocation. Mail Filtering and Real-time Modification daemon. * mtasim: (mailfromd) mtasim. MTA simulator. * smap: (mailfromd) smap. A universal socket-map program for MeTA1. * pmult: (mailfromd) pmult. Pmilter multiplexer program. * pies: (mailfromd) pies. Program execution supervisor. @end direntry @end ifinfo @copying Published by the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Copyright @copyright{} 2005, 2006, 2007, 2008, 2009 Sergey Poznyakoff Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, with the Front-Cover texts being ``Mailfromd Manual'', and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled ``GNU Free Documentation License''. (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development.'' @end copying @titlepage @title Mailfromd mail filter @subtitle version @value{VERSION}, @value{UPDATED} @author Sergey Poznyakoff. @page @vskip 0pt plus 1filll @insertcopying @end titlepage @headings off @page @w{ } @sp 9 @quotation @i{Dedico aquest treball a Lluis Llach, per obrir els nous horitzons.} @end quotation @w{ } @page @w{ } @page @headings on @page @summarycontents @page @contents @ifnottex @node Top @top Mailfromd This edition of the @cite{Mailfromd Manual}, last updated @value{UPDATED}, documents @command{mailfromd} Version @value{VERSION}. @end ifnottex @menu * Preface:: Short description of this manual; brief history and acknowledgments. * Intro:: Introduction to Mailfromd. * Building:: Building the Package. * Tutorial:: Mailfromd Tutorial. * MFL:: The Mail Filtering Language. * Using MFL Mode:: Using the GNU Emacs MFL Mode. * Mailfromd Configuration:: Configuring @command{mailfromd}. * Sendmail:: Using @command{mailfromd} with Sendmail. * MeTA1:: Using @command{mailfromd} with MeTA1. * mtasim:: An @acronym{MTA} simulator. * smap:: A universal socket-map program for MeTA1. * pmult:: Pmilter multiplexer program. * pies:: Program execution supervisor. * Reporting Bugs:: How to Report a Bug. Appendices * Gacopyz:: * Time and Date Formats:: * Upgrading:: * Copying This Manual:: The GNU Free Documentation License. * Concept Index:: Index of Concepts. @detailmenu --- The Detailed Node Listing --- Preface * History:: Short @command{mailfromd} history. * Acknowledgments:: Acknowledgments. Introduction to @command{mailfromd} * Conventions:: Typographical conventions. * Overview:: Mailfromd at a first glance * SAV:: Principles of Sender Address Verification. * Rate Limit:: Controlling Mail Sending Rate. * SPF:: Sender Policy Framework. Sender Address Verification. * Limitations:: Tutorial * Start Up:: * Simplest Configurations:: * Conditional Execution:: * Functions and Modules:: * Domain Name System:: * Checking Sender Address:: * SMTP Timeouts:: * Avoiding Verification Loops:: * HELO Domain:: * Controlling Number of Recipients:: * Sending Rate:: * Greylisting:: * Local Account Verification:: * Examining mail contents:: * Databases:: * Testing Filter Scripts:: * Run Mode:: * Logging and Debugging:: * Runtime errors:: * Cautions:: Databases * Database Formats:: * Basic Database Operations:: * Database Maintenance:: Run Mode * getopt:: Parsing Command Line Arguments. Mail Filtering Language * Comments:: Usual and pragmatic comments. * Data Types:: * Numbers:: * Literals:: * Here Documents:: * Sendmail Macros:: * Constants:: * Variables:: * Back references:: * Handlers:: * begin/end:: * Functions:: Functions. * Expressions:: Expressions. * Shadowing:: Variable and Constant Shadowing. * Statements:: * Conditionals:: Conditional Statements. * Loops:: Loop Statements. * Exceptions:: Exceptional Conditions and their Handling. * Polling:: Sender Verification Tests. * Modules:: Modules are Collections of Useful Functions. * Preprocessor:: Input Text Is Preprocessed. * Filter Script Example:: A Working Filter Script Explained. * Reserved Words:: A Reference List of Reserved Words. Comments * option:: Pragma option. * database:: Pragma database. * stacksize:: Pragma stacksize. * regex:: Pragma regex. * dbprop:: Pragma dbprop. * greylist:: Pragma greylist. Constants * Built-in constants:: Variables * Predefined variables:: Functions * Built-in:: Built-in and Library Functions * User-defined:: Syntax for defining user functions Built-in and Library Functions * Macro access:: * String manipulation:: * String formatting:: * Character Type:: * Envelope modification functions:: * Header modification functions:: * Body Modification Functions:: * Mail header functions:: * Mail body functions:: * Mailbox functions:: * Message functions:: * Quarantine functions:: * Polling functions:: * Internet address manipulation functions:: * DNS functions:: * Database functions:: * I/O functions:: * System functions:: * Sieve Interface:: * Interfaces to Third-Party Programs:: * Rate limiting functions:: * Greylisting functions:: * Special test functions:: * Mail Sending Functions:: * NLS Functions:: * Debugging Functions:: * Blacklisting Functions:: * SPF Functions:: User-Defined Functions * Some Useful Functions:: Expressions * Constant expressions:: String and Numeric Constants. * Function calls:: A Function Call is an Expression. * Concatenation:: Adjacent Expressions Concatenate. * Arithmetic operations:: @samp{+}, @samp{-}, etc. * Relational expressions:: @samp{=}, @samp{<}, etc. * Special comparisons:: @code{matches}, @code{mx matches}, etc. * Boolean expressions:: @code{and}, @code{or}, @code{not}. * Precedence:: How various operators nest. * Type casting:: Statements * Actions:: Actions control the handling of the mail. * Assignments:: * Pass:: * Echo:: @c Return statement:: @c Conditionals @c Exception handlers Configuring @command{mailfromd} * invocation:: * options:: Command Line Options. * Starting and Stopping:: How to Start and Shut Down the Daemon. Command Line Options. * Operation Modifiers:: * General Settings:: * Preprocessor Options:: * Timeout Control:: * Logging and Debugging Options:: * Informational Options:: @command{mtasim} --- a testing tool * interactive mode:: * expect commands:: * traces:: * daemon mode:: * option summary:: Pmilter multiplexer program. * pmult configuration:: * pmult example:: * pmult invocation:: Pmult Configuration * pmult-conf:: Multiplexer Configuration. * pmult-macros:: Translating MeTA1 macros. * pmult-client:: Pmult Client Configuration. * pmult-debug:: Debugging Pmult. Pies -- a program execution supervisor. * Pies Configuration File:: * Component Statement:: * include-meta1:: * Global Configuration:: * Pies Debugging:: * Configuration Example:: * Command Line Usage:: * Pies Invocation:: Component Statement * Prerequisites:: * Component Privileges:: * Resources:: * Actions Before Startup:: * Exit Actions:: * Output Redirectors:: * Inetd-Style Components:: * Meta1-Style Components:: * Component Syntax Summary:: Global Configuration * Less Useful Statements:: Configuration Example * Simple Pies:: * Hairy Pies:: * Inetd Pies:: Upgrading * 500-510:: Upgrading from 5.0 to 5.1 * 440-500:: Upgrading from 4.4 to 5.0 * 43x-440:: Upgrading from 4.3.x to 4.4 * 420-43x:: Upgrading from 4.2 to 4.3.x * 410-420:: Upgrading from 4.1 to 4.2 * 400-410:: Upgrading from 4.0 to 4.1 * 31x-400:: Upgrading from 3.1.x to 4.0 * 30x-31x:: Upgrading from 3.0.x to 3.1 * 2x-30x:: Upgrading from 2.x to 3.0.x * 1x-2x:: Upgrading from 1.x to 2.x @end detailmenu @end menu @node Preface @unnumbered Preface Simple Mail Transfer Protocol (@acronym{SMTP}) which is the standard for e-mail transmissions across the internet was designed in the good old days when nobody could even think of the possibility of e-mail being abused to send tons of unsolicited messages of dubious contents. Therefore it lacks mechanisms that could have prevented this abuse (@dfn{spamming}), or at least could have made it difficult. Attempts to introduce such mechanisms (such as @uref{http://tools.ietf.org/html/rfc2554, @acronym{SMTP-AUTH} extension}) are being made, but they are not in wide use yet and, probably, their introduction will not be enough to stop the e-mail abuse. Spamming is today's grim reality and developers spend lots of time and efforts designing new protection measures against it. @command{Mailfromd} is one of such attempts. The package is designed to work with any @acronym{MTA} supporting @samp{Milter} or @samp{Pmilter} protocol, such as @samp{Sendmail}, @samp{MeTA1} or @samp{Postfix}. It allows you to: @itemize @bullet @item Control whether messages come from trustworthy senders, using so called @dfn{callout} or @dfn{Sender Address Verification} (@pxref{SAV}) mechanism. @item Prevent emails coming from forged addresses by use of @acronym{SPF} mechanism (@pxref{SPF Functions}). @item Limit connection and/or sending rates (@pxref{Rate Limit}). @item Use @dfn{black-}, @dfn{white-} and @dfn{greylisting} techniques. @item Invoke external programs or other mail filters. @end itemize @menu * History:: Short @command{mailfromd} history. * Acknowledgments:: Acknowledgments. @end menu @node History @unnumberedsec Short history of @command{mailfromd}. The idea of the utility appeared in 2005, and its first version appeared soon afterward. Back then it was a simple implementation of Sender Address Verification (@pxref{SAV}) for @samp{Sendmail} (hence its name -- @command{mailfromd}) with rudimentary tuning possibilities. After a short run on my mail servers, I discovered that the utility was not flexible enough. It took less than a month to implement a configuration file that allowed to control program and data flow during the @samp{envfrom} @acronym{SMTP} state. The new version, 1.0, appeared in June, 2005. The next major release, 1.2 (1.1 contained mostly bugfixes), appeared two months later, which introduced @dfn{mail sending rate} control (@pxref{Rate Limit}). The program evolved during the next year, which led to the release of version 2.0 in September, 2006. This version was a major change in the main idea of the program. Configuration file become a flexible filter script allowing to control almost all @acronym{SMTP} states. The program supplied in the script file was compiled into a pseudo-code at startup, this code being subsequently evaluated each time the filter was invoked. This caused a considerable speed-up in comparison with the previous versions, where the run-time evaluator was traversing the parse tree. This version also introduced (implicitly, at the time), two separate data types for the entities declared in the script, which also played its role in the speed improvement (in the previous versions all data were considered strings). Lots of improvements were made in the filter language (@acronym{MFL}, @pxref{MFL}) itself, such as user-defined functions, @code{switch} statement, @code{catch} statement that allows to handle run-time errors, etc. The set of built-in functions extended considerably. A testsuite (using @i{DejaGNU}) was introduced in this version. During this initial development period the limitations imposed by @command{libmilter} implementation became obvious. Finally, I felt they were stopping further development, and decided that @command{mailfromd} should use its own @samp{Milter} implementation. This new library, @command{libgacopyz} was the main new feature of the 3.0 release, that was released in November, 2006. Another major feature was the @option{--dump-macros} option and @option{macros} to @command{rc.mailfromd} script, that were intended to facilitate the configuration on @samp{Sendmail} side. The development of 3.@i{x} (more properly, 3.1.@i{x}) series concentrated mainly on bug-fixes, while the main development was done on the next branch. The version 4.0 appeared on May 12, 2007. The full list of changes in this release is more than 500 lines long, so it is impractical to list them here. In particular, this version introduced lots of new features in @acronym{MFL} syntax and the library of useful @acronym{MFL} functions. The runtime engine was also improved, in particular, stack space become expandable which eliminated many run-time errors. This version also introduced the beginnings of the @acronym{MFL} module system. The code generation was re-implemented to facilitate the introduction of object files in future versions. Another new features in this release include @acronym{SPF} support and @command{mtasim} utility, an @acronym{MTA} simulator designed for testing @command{mailfromd} scripts (@pxref{mtasim}). The test suite in this version was made portable by rewriting it in @i{Autotest}. Another big leap forward was the 5.0 release, which appeared on December 26, 2008. It largely enriched a set of available functions (61 new functions were introduced, which amounts to 41% of all the available functions in 5.0 release) and introduced several improvements in the MFL itself. Among others, function aliases and optional arguments in user-defined functions were introduced in this release. The new ``run operation mode'' allowed to execute arbitrary MFL functions from the command line. This release also raised the Mailutils version requirements to at least 2.0. @node Acknowledgments @unnumberedsec Acknowledgments Many people need to be thanked for their assistance in developing and debugging @command{mailfromd}. After S.@: C.@: Johnson, I can say that this program ``@i{owes much to a most stimulating collection of users, who have goaded me beyond my inclination, and frequently beyond my ability in their endless search for "one more feature". Their irritating unwillingness to learn how to do things my way has usually led to my doing things their way; most of the time, they have been right.}'' A real test for a program like @command{mailfromd} cannot be done but in conditions of production environment. A decision to try it in these conditions is by no means an easy one, it requires courage and good faith in the intentions and abilities of the author. To begin with, I would like to thank my contributors for these virtues. @cindex Jan Rafaj Jan Rafaj has intrepidly been using @command{mailfromd} since its early releases and invested lots of efforts in improving the program and its documentation. He is the author of many of the @acronym{MFL} library functions, shipped with the package. Some of his ideas are still waiting in my implementation queue, while new ones are consistently arriving. @cindex Peter Markeloff Peter Markeloff patiently tested every @command{mailfromd} release and helped discover and fix many bugs. @cindex Zeus Panchenko Zeus Panchenko contributed many ideas and gave lots of helpful comments. He offered invaluable help in debugging and testing @command{mailfromd} on @acronym{FreeBSD} platform. @cindex Sergey Afonin Sergey Afonin proposed many improvements and new ideas. He also invested a lot of his time in finding bugs and testing bugfixes. @cindex John McEleney @cindex Ben McKeegan John McEleney and Ben McKeegan contributed the token bucket filter implementation (@pxref{TBF}). @cindex Con Tassios Con Tassios helped to find and fix various bugs and contributed the new implementation of the @code{greylist} function (@pxref{greylisting types}). The following people (in alphabetical order) provided bug reports and helpful comments for various versions of the program: @cindex Alan Dobkin @cindex Brent Spencer @cindex Jeff Ballard @cindex Nacho Gonz@'alez L@'opez @cindex Phil Miller @cindex Simon Christian @cindex Thomas Lynch Alan Dobkin, Brent Spencer, Jeff Ballard, Nacho Gonz@'alez L@'opez, Phil Miller, Simon Christian, Thomas Lynch. @node Intro @chapter Introduction to @command{mailfromd} @command{Mailfromd} is a general-purpose mail filtering daemon and a suite of accompanying utilities for @command{Sendmail}@footnote{See @uref{http://www.sendmail.org}}, @command{MeTA1}@footnote{See @uref{http://www.meta1.org}}, @command{Postfix}@footnote{See @uref{http://www.postfix.org}} or any other @acronym{MTA} that supports @command{Milter} (or @command{Pmilter}) protocol. It is able to filter both incoming and outgoing messages using a filter program, written in @dfn{mail filtering language} (@acronym{MFL}). The daemon interfaces with the @acronym{MTA} using @command{Milter} protocol. The name @command{mailfromd} can be thought of as an abbreviation for @samp{@emph{Mail} @emph{F}iltering and @emph{R}untime @emph{M}odification} @emph{D}aemon, with an @samp{o} for itself. Historically, it stemmed from the fact that the original implementation was a simple filter implementing the @dfn{sender address verification} technique. Since then the program has changed dramatically, and now it is actually a language translator and run-time evaluator providing a set of built-in and library functions for filtering electronic mail. The first part of this manual is an overview, describing the features @command{mailfromd} offers in general. The second part is a tutorial, which provides an introduction for those who have not used @command{mailfromd} previously. It moves from topic to topic in a logical, progressive order, building on information already explained. It offers only the principal information needed to master basic practical usage of @command{mailfromd}, while omitting many subtleties. The other parts are meant to be used as a reference for those who know @command{mailfromd} well enough, but need to look up some notions from time to time. Each chapter presents everything that needs to be said about a specific topic. The manual assumes that the reader has a good knowledge of the @acronym{SMTP} protocol and @command{Sendmail} mail transport system. @menu * Conventions:: Typographical conventions. * Overview:: Mailfromd at a first glance * SAV:: Principles of Sender Address Verification. * Rate Limit:: Controlling Mail Sending Rate. * SPF:: Sender Policy Framework. @end menu @node Conventions @section Typographical conventions @cindex Texinfo This manual is written using Texinfo, the GNU documentation formatting language. The same set of Texinfo source files is used to produce both the printed and online versions of the documentation. @ifnotinfo Because of this, the typographical conventions may be slightly different than in other books you may have read. @end ifnotinfo @ifinfo This section briefly documents the typographical conventions used in this manual. @end ifinfo Examples you would type at the command line are preceded by the common shell primary prompt, @samp{$}. The command itself is printed @kbd{in this font}, and the output it produces @samp{in this font}, for example: @smallexample $ @kbd{mailfromd --version} mailfromd (mailfromd @value{VERSION}) @end smallexample In the text, the command names are printed @command{like this}, command line options are displayed in @option{this font}. Some notions are emphasized @emph{like this}, and if a point needs to be made strongly, it is done @strong{this way}. The first occurrence of a new term is usually its @dfn{definition} and appears in the same font as the previous occurrence of ``definition'' in this sentence. File names are indicated like this: @file{/path/to/ourfile}. The variable names are represented @var{like this}, keywords and fragments of program text are written in @code{this font}. @node Overview @section Mailfromd at a first glance In contrast to the most existing milter filters, @command{mailfromd} does not implement any default filtering policies. Instead, it depends entirely on a @dfn{filter script}, supplied to it by the administrator. The script, written in a specialized and simple to use language, called @acronym{MFL} (@pxref{MFL}), is supposed to run a set of tests and to decide whether the message should be accepted by the @acronym{MTA} or not. To perform the tests, the script can examine the values of @command{Sendmail} macros, use an extensive set of built-in and library functions, and invoke user-defined functions. @node SAV @section Sender Address Verification. @cindex sender address verification, described @cindex callout, described @dfn{Sender address verification} is one of the basic mail verification techniques, implemented by @command{mailfromd}. It consists in probing each @acronym{MX} server for the given address, until one of them gives a definite (positive or negative) reply. Using this technique you can block a sender address if it is not deliverable, thereby cutting off a large amount of spam. It can also be useful to block mail for undeliverable recipients, for example on a mail relay host that does not have a list of all the valid recipient addresses. This prevents undeliverable junk mail from entering the queue, so that your @acronym{MTA} doesn't have to waste resources trying to send @samp{MAILER-DAEMON} messages back. Let's illustrate how it works on an example: @anchor{standard verification} @cindex standard address verification @cindex probe message @cindex account probing Suppose that the user @samp{} is trying to send mail to one of your local users. The remote machine connects to your @acronym{MTA} and issues @code{MAIL FROM: } command. However, your @acronym{MTA} does not have to take its word for it, so it uses @command{mailfromd} to verify the sender address validity. @command{Mailfromd} strips the domain name from the address (@samp{somedomain.net}) and queries @acronym{DNS} about @samp{MX} records for that domain. Suppose, it receives the following list @multitable @columnfractions 0.2 0.7 @item 10 @tab relay1.somedomain.net @item 20 @tab relay2.somedomain.net @end multitable It then connects to first @acronym{MX} server, using @acronym{SMTP} protocol, as if it were going to send a message to @samp{}. This is called sending a @dfn{probe message}. If the server accepts the recipient address, the @command{mailfromd} accepts the incoming mail. Otherwise, if the server rejects the address, the mail is rejected as well. If the @acronym{MX} server cannot be connected, @command{mailfromd} selects next server from the list and continues this process until it finds the answer or the list of servers is exhausted. The @dfn{probe message} is like a normal mail except that no data are ever being sent. The probe message transaction in our example might look as follows (@samp{S:} meaning messages sent by remote @acronym{MTA}, @samp{C:} meaning those sent by @command{mailfromd}): @smallexample C: HELO mydomain.net S: 220 OK, nice to meet you C: MAIL FROM: <> S: 220 <>: Sender OK C: RCPT TO: S: 220 : Recipient OK C: QUIT @end smallexample Probe messages are never delivered, deferred or bounced; they are always discarded. @cindex strict address verification The described method of address verification is called @dfn{standard} method throughout this document. @command{Mailfromd} also implements a method we call @dfn{strict}. When using strict method, @command{mailfromd} first resolves @acronym{IP} address of sender machine to a fully qualified domain name. Then it obtains @samp{MX} records for this machine, and then proceeds with probing as described above. So, the difference between the two methods is in the set of @samp{MX} records that are being probed: standard method queries @samp{MX}s based on the sender email domain, strict method works with @samp{MX}s for the sender @acronym{IP} address. Strict method allows to cut off much larger amount of spam, although it does have many drawbacks. Returning to our example above, consider the following situation: @samp{} is a perfectly normal address, but it is being used by a spammer from some other domain, say @samp{otherdomain.com}. Standard method is not able to cope with such cases, whereas strict one is. An alert reader will ask: what happens if @command{mailfromd} is not able to get a definite answer from any of @acronym{MX} servers? Actually, it depends entirely on how you will instruct it to act in this case, but the general practice is to return temporary failure, which will urge the remote party to retry sending their message later. @cindex caching @acronym{DNS} requests After receiving a definite answer, @command{mailfromd} will cache it in its database, so that next time your @acronym{MTA} receives a message from that address (or from the sender @acronym{IP}/email address pair, for strict method), it will not waste its time trying to reach @acronym{MX} servers again. The records remain in the cache database for a certain time, after which they are discarded. @menu * Limitations:: @end menu @node Limitations @subsection Limitations of Sender Address Verification @cindex sender address verification, limitations Before deciding whether and how to use sender address verification, you should be aware of its limitations. Both standard and strict methods suffer from the following limitations: @itemize @bullet @item The sender verification methods will perform poorly on highly loaded sites. The traffic and/or resource usage overhead may not be feasible for you. However, you may experiment with various @command{mailfromd} options to find an optimal configuration. @item Some sites may blacklist your @acronym{MTA} if it probes them too often. This drawback can to a certain extent be eliminated by raising the expiration timeout in your cache database. @item When verifying the remote address, no attempt to actually deliver the message is made. If @acronym{MTA} accepts the address, @command{mailfromd} assumes it is @sc{ok}. However in reality, mail for a remote address can bounce @emph{after} the nearest @acronym{MTA} accepts the recipient address. This drawback can often be avoided by combining sender address verification with greylisting (@pxref{Greylisting}). @item If the remote server rejects the address, no attempt is being made to discern between various reasons for rejection (client rejected, @samp{HELO rejected}, @samp{MAIL FROM} rejected, etc.) @item Unfortunately, some major sites such as @indicateurl{yahoo.com} do not reject unknown addresses in reply to the @samp{RCPT TO} command, but report a delivery failure in response to end of @samp{DATA} after a message is transferred. Of course, sender address verification does not work with such sites. However, a combination of address verification and greylisting (@pxref{Greylisting}) may be a good choice in such cases. @end itemize In addition, strict verification breaks forward mail delivery. This is obvious, since mail forwarding is based on delivering unmodified message to another location, so the sender address domain will most probably not be the same as that of the @acronym{MTA} doing the forwarding. @node Rate Limit @section Controlling Mail Sending Rate. @cindex mail sending rate, explained @cindex sending rate, explained @dfn{Mail Sending Rate} for a given identity is defined as the number of messages with this identity received within a predefined interval of time. @acronym{MFL} offers a set of functions for limiting mail sending rate (@pxref{Rate limiting functions}), and for controlling broader rate aspects, such as data transfer rates (@pxref{TBF}). @node SPF @section SPF @cindex @acronym{SPF} @cindex Sender Policy Framework @dfn{Sender Policy Framework}, or @acronym{SPF} for short, is an extension to @acronym{SMTP} protocol that allows to identify forged identities supplied with the @code{MAIL FROM} and @code{HELO} commands. The framework is explained in detail in @acronym{RFC} 4408 (@uref{http://tools.ietf.org/html/rfc4408}) and on the @uref{http://www.openspf.org/, SPF Project Site}. Mailfromd provides a set of functions (@pxref{SPF Functions}) for using @acronym{SPF} to control mail flow. @node Building @chapter Building the Package @cindex building @command{mailfromd} @cindex @command{mailfromd}, building This chapter contains a detailed list of steps you need to undertake in order to configure and build the package. @enumerate 1 @item Make sure you have the necessary software installed. To build @command{mailfromd} you will need to have following packages on your machine: @enumerate A @item GNU mailutils version 2.0 or newer. It is available from @uref{http://www.gnu.org/software/mailutils}. @item A @acronym{DBM} library. @anchor{DBM} @cindex @acronym{DBM} @cindex Berkeley DB @cindex @acronym{GDBM} @command{Mailfromd} is able to link with two flavors of @acronym{DBM} libraries: Berkeley DB or @command{gdbm}. It will refuse to build without @acronym{DBM}. By default, @command{configure} will try to find the best implementation installed on your machine (preference is given to Berkeley DB) and will use it. You can, however, explicitly specify which implementation you want to use. @cindex confMAPDEF, @command{Sendmail} macro The following table will help you do that. The column @samp{DB type} lists types of @acronym{DBM} databases supported by @command{mailfromd}. The column @samp{confMAPDEF} lists the value of @code{confMAPDEF} Sendmail configuration macro corresponding to that database type. It is here because it is usually wise to configure @command{mailfromd} to use the same database type as your Sendmail (If you don't know what @code{confMAPDEF} is, you probably are wasting your time reading this. Refer to Sendmail configuration guide first). Finally, the column @samp{configure option} lists the option you should give to @command{configure} to enable using this database. @samp{N/A} in any column means there is no support for this database in @command{Sendmail} or @command{mailfromd}. @cindex @option{--with-berkeley-db}, @command{configure} option @cindex @option{--with-gdbm}, @command{configure} option @multitable @columnfractions 0.25 .25 .50 @headitem DB type @tab confMAPDEF @tab configure option @item NDBM @tab @option{-NNDBM} @tab N/A @item Berkeley DB @tab @option{-NNEWDB} @tab @option{--with-berkeley-db} @item GDBM @tab N/A @tab @option{--with-gdbm} @end multitable The @option{--with-berkeley-db} option needs a special note. By default it will try to determine the version of Berkeley DB installed on your machine. If, however, this autodetection fails, you can explicitly specify the version or the library name to use as the argument to the option. Unless the argument begins with a digit, it is taken as a library name, without the @samp{lib} prefix and library type suffix, so that @smallexample ./configure --with-berkeley-db=db-3.1 @end smallexample @noindent instructs @code{configure} to use library @file{libdb-3.1.so} (or @file{libdb-3.1.a}). Otherwise, if the argument begins with a digit, it is understood as a version number of the library to link to. In this case @code{configure} assumes a Slackware-like installation layout. Thus, the option @smallexample --with-berkeley-db=3.1 @end smallexample @noindent tells @command{configure} to use library @file{libdb-3.1.so} (or @file{libdb-3.1.a}) and header file @file{/usr/include/db31/db.h}. @end enumerate @anchor{default user privileges} @cindex default user privileges @cindex @code{DEFAULT_USER}, @command{configure} variable @item Decide what user privileges will be used to run @command{mailfromd} After startup, the program drops root privileges. By default, it switches to the privileges of user @samp{mail}, group @samp{mail}. If there is no such user on your system, or you wish to use another user account for this purpose, override it using @var{DEFAULT_USER} environment variable. For example for @command{mailfromd} to run as user @samp{nobody}, use @smallexample ./configure DEFAULT_USER=nobody @end smallexample @noindent The user name can also be changed at run-time (@pxref{--user}). @cindex @option{--prefix}, @command{configure} option @item Decide where to install @command{mailfromd} and where its filter script and data files will be located. As usual, the default value for the installation prefix is @file{/usr/local}. If it does not suit you, specify another location using @option{--prefix} option, e.g.: @samp{--prefix=/usr}. During installation phase, the build system will install several files. These files are: @multitable @columnfractions 0.50 .5 @headitem File @tab Purpose @item @file{@var{prefix}/sbin/mailfromd} @tab Main daemon @item @file{@var{prefix}/etc/mailfromd.rc} @tab Main filter script file@footnote{The filter script file will be installed only if it is not already there. Thus, if you are upgrading to a newer version of @command{mailfromd}, your old script file will be preserved with all your changes.} @item @file{@var{prefix}/info/mailfromd.info} @tab Documentation @end multitable @cindex --sysconfdir, @command{configure} option It is advisable to use the same settings for file name prefixes as those you used when configuring @command{mailutils}. In particular, try to use the same @option{--sysconfdir}, since it will facilitate configuring the whole system. @anchor{statedir} @cindex local state directory @cindex DEFAULT_STATE_DIR, @command{configure} variable Another important point is location of @dfn{local state directory}, i.e. a directory where @command{mailfromd} keeps its data files (e.g. communication socket, @acronym{PID}-file and database files). By default, its full name is @file{@var{localstatedir}/mailfromd}. You can change it by setting @code{DEFAULT_STATE_DIR} configuration variable. This value can be changed at run-time using @code{#pragma option state-directory} statement (@pxref{pragma state-directory}). @item Select default communication socket. @cindex default communication socket @cindex default communication port @cindex DEFAULT_SOCKET, @command{configure} variable This is the socket used to communicate with @acronym{MTA}, in the usual @command{Milter} port notation (@pxref{milter port specification}). If the socket name does not begin with a protocol or directory separator, it is assumed to be a @acronym{UNIX} socket, located in the local state directory. The default value is @file{mailfrom}, which is equivalent to @file{unix:@var{localstatedir}/mailfromd/mailfrom}. To alter this, use @code{DEFAULT_SOCKET} environment variable, e.g.: @smallexample ./configure DEFAULT_SOCKET=inet:999@@localhost @end smallexample @noindent The communication socket can be changed at run time using @option{--port} command line option (@pxref{--port}) or @samp{#pragma option port} statement in the filter script (@pxref{pragma port}). @item Select default expiration interval. @cindex default expiration interval @cindex DEFAULT_EXPIRE_INTERVAL, @command{configure} variable @dfn{Expiration interval} defines the period of time during which a record in the @command{mailfromd} database is considered valid. It is described in more detail in @ref{Databases}. The default value is 86400 seconds, i.e. 24 hours. It is @sc{ok} for most sites. If, however, you wish to change it, use @var{DEFAULT_EXPIRE_INTERVAL} environment variable. @cindex DEFAULT_@/DNS_@/NEGATIVE_@/EXPIRE_@/INTERVAL, @command{configure} variable @cindex DEFAULT_EXPIRE_RATES_INTERVAL, @command{configure} variable There are also two variables that allow to control particular expiration intervals: @code{DEFAULT_DNS_NEGATIVE_EXPIRE_INTERVAL} sets expiration time for cached negative @acronym{DNS} answers (@pxref{DNS Cache Management}) (default 3600 seconds) and @code{DEFAULT_EXPIRE_RATES_INTERVAL} sets default expiration time for mail rate database (@pxref{Rate limiting functions}). Expiration settings can be changed at run time using @samp{#pragma database} statement in the filter script file (@pxref{database}). @cindex enable-syslog-async, @option{--enable-syslog-async}, @command{configure} option @cindex syslog, non-blocking @item Select a @command{syslog} implementation to use. @anchor{syslog-async} @command{Mailfromd} uses @code{syslog} for diagnostics output. The default @code{syslog} implementation on most systems (most notably, on GNU/Linux) uses blocking @code{AF_UNIX SOCK_DGRAM} sockets. As a result, when an application calls @code{syslog()}, and @command{syslogd} is not responding and the socket buffers get full, the application will hang. @cindex Simon Kelley For @command{mailfromd}, as for any daemon, it is more important that it continue to run, than that it continue to log. For this purpose, @command{mailfromd} is shipped with a non-blocking @code{syslog} implementation by Simon Kelley. This implementation, instead of blocking, buffers log lines in memory. When the buffer log overflows, some lines are lost, but the daemon continues to run. When lines are lost, this fact is logged with a message of the form: @smallexample async_syslog overflow: 5 log entries lost @end smallexample To enable this implementation, configure the package with @option{--enable-syslog-async} option, e.g.: @smallexample ./configure --enable-syslog-async @end smallexample @cindex @code{DEFAULT_SYSLOG_ASYNC}, @command{configure} variable Additionally, you can instruct @command{mailfromd} to use asynchronous syslog by default. To do so, set @code{DEFAULT_SYSLOG_ASYNC} to 1, as shown in example below: @smallexample ./configure --enable-syslog-async DEFAULT_SYSLOG_ASYNC=1 @end smallexample You will be able to override these defaults at run-time by using @option{--syslog-async} or @option{--no-syslog-async} command line options (@pxref{Logging and Debugging}). @item Run @command{configure} with all the desired options. For example, the following command: @smallexample ./configure DEFAULT_SOCKET=inet:999@@localhost --with-berkeley-db=3 @end smallexample @noindent will configure the package to use Berkeley DB database, version 2, and @samp{inet:999@@localhost} as the default communication socket. At the end of its run @command{configure} will print a concise summary of its configuration settings. It looks like that (with the long lines being split for readability): @smallexample @group ******************************************************************* Mailfromd configured with the following settings: External preprocessor..................... /usr/bin/m4 -s DBM version............................... Berkeley DB v. 3 Default user.............................. mail State directory........................... $(localstatedir)/$(PACKAGE) Socket.................................... mailfrom Expiration interval....................... 86400 Negative DNS answer expiration interval... 3600 Rates expire interval..................... 300 Default syslog implementation............. blocking Readline (for mtasim)..................... yes Documentation rendition type.............. PROOF Enable pmilter support.................... no ******************************************************************* @end group @end smallexample Make sure these settings satisfy your needs. If they do not, reconfigure the package with the right options. @item Run @command{make}. @item Run @command{make} install. @item Make sure @file{@var{localstatedir}/mailfromd} has the right owner and mode. @item Examine filter script file (@file{@var{sysconfdir}/mailfromd.etc}) and edit it, if necessary. @item Upgrading If you are upgrading from an earlier release of Mailfromd, refer to @ref{Upgrading}, for detailed instructions. @end enumerate @node Tutorial @chapter Tutorial This chapter contains a tutorial introduction, guiding you through various @command{mailfromd} configurations, starting from the simplest ones and proceeding up to more advanced forms. It omits most complicated details, concentrating mainly on the common practical tasks. If you are familiar to @command{mailfromd}, you can skip this chapter and go directly to the next one (@pxref{MFL}), which contains detailed discussion of the mail filtering language and @command{mailfromd} interaction with the Mail Transport Agent. @menu * Start Up:: * Simplest Configurations:: * Conditional Execution:: * Functions and Modules:: * Domain Name System:: * Checking Sender Address:: * SMTP Timeouts:: * Avoiding Verification Loops:: * HELO Domain:: * Controlling Number of Recipients:: * Sending Rate:: * Greylisting:: * Local Account Verification:: * Examining mail contents:: * Databases:: * Testing Filter Scripts:: * Run Mode:: * Logging and Debugging:: * Runtime errors:: * Cautions:: @end menu @node Start Up @section Start Up @cindex @acronym{MTA} @cindex Mail Transfer Agent (@acronym{MTA}) The @command{mailfromd} utility runs as a standalone @dfn{daemon} program and listens on a predefined communication channel for requests from the @dfn{Mail Transfer Agent} (@acronym{MTA}, for short). When processing each message, the @acronym{MTA} installs communication with @command{mailfromd}, and goes through several states, collecting the necessary data from the sender. At each state it sends the relevant information to @command{mailfromd}, and waits for it to reply. The @command{mailfromd} filter receives the message data through @dfn{Sendmail macros} and runs a @dfn{handler program} defined for the given state. The result of this run is a @dfn{response code}, that it returns to the @acronym{MTA}. The following response codes are defined: @table @code @item continue @cindex continue action, introduced Continue message processing. @item accept @cindex accept action, introduced Accept this message for delivery. After receiving this code the @acronym{MTA} continues processing this message without further consulting @command{mailfromd} filter. @item reject @cindex reject action, introduced Reject this message. The message processing stops at this stage, and the sender receives the reject reply (@samp{5@var{xx}} reply code). No further @command{mailfromd} handlers are called for this message. @item discard @cindex discard action, introduced Silently discard the message. This means that @acronym{MTA} will continue processing this message as if it were going to deliver it, but will discard it after receiving. No further interaction with @command{mailfromd} occurs. @item tempfail @cindex tempfail action, introduced Temporarily reject the message. The message processing stops at this stage, and the sender receives the @samp{temporary failure} reply (@samp{4@var{xx}} reply code). No further @command{mailfromd} handlers are called for this message. @end table @cindex filter script, described The instructions on how to process the message are supplied to @command{mailfromd} in its @dfn{filter script file}. It is normally called @file{/usr/local/etc/mailfromd.rc} (but can be located elsewhere, @pxref{invocation}) and contains a set of @dfn{milter state handlers}, or subroutines to be executed in various @acronym{SMTP} states. Each interaction state can be supplied its own handling procedure. A missing procedure implies @code{continue} response code. @cindex milter state handler, described @cindex handler, described @cindex connect, handler @cindex helo, handler @cindex envfrom, handler @cindex envrcpt, handler @cindex header, handler @cindex eoh, handler @cindex body, handler @cindex eom, handler @cindex begin, special handler @cindex end, special handler @anchor{handler names} The filter script can define up to eight @dfn{milter state handlers}, called after the names of milter states: @samp{connect}, @samp{helo}, @samp{envfrom}, @samp{envrcpt}, @samp{header}, @samp{eoh}, @samp{body}, and @samp{eom}. Two special handlers are available for initialization and clean-up purposes: @samp{begin} is called before the processing starts, and @samp{end} is called after it is finished. The diagram below shows the control flow when processing an @acronym{SMTP} transaction. Lines marked with @code{C:} show @acronym{SMTP} commands issued by the remote machine (the @dfn{client}), those marked with @samp{@result{}} show called handlers with their arguments. An @samp{[R]} appearing at the start of a line indicates that this part of the transaction can be repeated any number of times: @float Figure, milter-control-flow @caption{Mailfromd Control Flow} @smallexample @group @result{} begin() @result{} connect(@var{hostname}, @var{family}, @var{port}, @samp{IP address}) C: HELO @var{domain} helo(@var{domain}) for each message transaction do C: MAIL FROM @var{sender} @result{} envfrom(@var{sender}) [R] C: RCPT TO @var{recipient} @result{} envrcpt(@var{recipient}) C: DATA [R] C: @var{header}: @var{value} @result{} header(@var{header}, @var{value}) C: @result{} eoh() [R] C: @var{body-line} @result{} /* @r{Collect lines into blocks @var{blk} of} @result{} * @r{at most @var{len} bytes and call:} @result{} */ @result{} body(@var{blk}, @var{len}) C: . @result{} eom() done @result{} end() @end group @end smallexample @end float This control flow is maintained for as long as each called handler returns @code{continue} (@pxref{Actions}). Otherwise, if any handler returns @code{accept} or @code{discard}, the message processing continues, but no other handler is called. In the case of @code{accept}, the @acronym{MTA} will accept the message for delivery, in the case of @code{discard} it will silently discard it. If any of the handlers returns @code{reject} or @code{tempfail}, the result depends on the handler. If this code is returned by @code{envrcpt} handler, it causes this particular recipient address to be rejected. When returned by any other handler, it causes the whole message will be rejected. The @code{reject} and @code{tempfail} actions executed by @code{helo} handler do not take effect immediately. Instead their action is deferred until the next @acronym{SMTP} command from the client, which is usually @code{MAIL FROM}. @node Simplest Configurations @section Simplest Configurations @cindex handler declaration @cindex milter state handler, declaring @cindex state handler, declaring @cindex declaring milter state handler The @command{mailfromd} script file contains a series of @dfn{declarations} of the handler procedures. Each declaration has the form: @smallexample @group prog @var{name} do @dots{} done @end group @end smallexample @noindent where @code{prog}, @code{do} and @code{done} are the @dfn{keywords}, and @var{name} is the state name for this handler. The dots in the above example represent the actual @dfn{code}, or a set of commands, instructing @command{mailfromd} how to process the message. For example, the declaration: @smallexample @group prog envfrom do accept done @end group @end smallexample @noindent installs a handler for @samp{envfrom} state, which always approves the message for delivery, without any further interaction with @command{mailfromd}. @cindex actions, introduced The word @code{accept} in the above example is an @dfn{action}. @dfn{Action} is a special language statement that causes the execution of the program to stop and to return a response code to the @command{Sendmail}. There are five actions, one for each response code: @code{continue}, @code{accept}, @code{reject}, @code{discard}, and @code{tempfail}. Among these, @code{reject} and @code{discard} can optionally take one to three arguments. The first argument is a three-digit @acronym{RFC} 2821 reply code. It must begin with @samp{5} for @code{reject} and with @samp{4} for @code{tempfail}. If two arguments are supplied, the second argument must be either an @dfn{extended reply code} (@acronym{RFC} 1893/2034) or a textual string to be returned along with the @acronym{SMTP} reply. Finally, if all three arguments are supplied, then the second one must be an extended reply code and the third one must supply the textual string. The following examples illustrate all possible ways of using the @code{reject} statement: @smallexample @group reject reject 503 reject 503 5.0.0 reject 503 "Need HELO command" reject 503 5.0.0 "Need HELO command" @end group @end smallexample @noindent Please note the quotes around the textual string. @node Conditional Execution @section Conditional Execution Programs consisting of a single action are rarely useful. In most cases you will want to do some checking and decide whether to process the message depending on its result. For example, if you do not want to accept messages from the address @samp{}, you could write the following program: @smallexample @group prog envfrom do if $f = "badguy@@some.net" reject else accept fi done @end group @end smallexample This example illustrates several important concepts. First or all, @code{$f} in the third line is a @dfn{Sendmail macro reference}. Sendmail macros are referenced the same way as in @file{sendmail.cf}, with the only difference that curly braces around macro names are optional, even if the name consists of several letters. The value of a macro reference is always a string. The equality operator (@samp{=}) compares its left and right arguments and evaluates to true if the two strings are exactly the same, or to false otherwise. Apart from equality, you can use the regular relational operators: @samp{!=}, @samp{>}, @samp{>=}, @samp{<} and @samp{<=}. Notice that string comparison in @command{mailfromd} is always case sensitive. To do case-insensitive comparison, translate both operands to upper or lower case (@xref{tolower}, and @pxref{toupper}). The @code{if} statement decides what actions to execute depending on the value its condition evaluates to. Its usual form is: @smallexample if @var{expression} @var{then-body} [else @var{else-body}] fi @end smallexample The @var{then-body} is executed if the @var{expression} evaluates to @code{true} (i.e. to any non-zero value). The optional @var{else-body} is executed if the @var{expression} yields @code{false} (i.e. zero). Both @var{then-body} and @var{else-body} can contain other @code{if} statements, their nesting depth is not limited. To facilitate writing complex conditional statements, the @code{elif} keyword can be used to introduce alternative conditions, for example: @smallexample @group prog envfrom do if $f = "badguy@@some.net" reject elif $f = "other@@domain.com" tempfail 470 "Please try again later" else accept fi done @end group @end smallexample @xref{switch}, for more elaborate forms of conditional branching. @node Functions and Modules @section Functions and Modules @cindex function, defined As any programming language, @acronym{MFL} supports a concept of @dfn{function}, i.e. a body of code that is assigned a unique name and can be invoked elsewhere as many times as needed. All functions have a @dfn{definition} that introduces types and names of the formal parameters and the result type, if the function is to return a meaningful value (function definitions in @acronym{MFL} are discussed in detail in @pxref{User-defined, User-Defined Functions}). @anchor{funcall} @cindex function calls A function is invoked using a special construct, @dfn{function call}: @smallexample @var{name} (@var{arg-list}) @end smallexample @noindent where @var{name} is the function name, and @var{arg-list} is a comma-separated list of expressions. Each expression in @var{arg-list} is evaluated, and its type is compared with that of the corresponding formal argument. If the types differ, the expression is converted to the formal argument type. Finally, a copy of its value is passed to the function as a corresponding argument. The order in which the expressions are evaluated is not defined. The compiler checks that the number of elements in @var{arg-list} matches the number of mandatory arguments for function @var{name}. For compatibility with previous versions, if @var{arg-list} consists of a single expression, the surrounding parentheses can be omitted, i.e. the following forms are equivalent: @smallexample hostname($client_addr) hostname $client_addr @end smallexample @noindent However, such syntax creates several ambiguities, so use it sparingly if at all. We recommend to always use parentheses when calling a function; @xref{Cautions}, for a detailed analysis of of this syntax. When a function does not deliver a result, it should only be called as a statement. Functions may be recursive, even mutually recursive. @cindex built-in and library functions, introduced @cindex library and built-in functions, introduced @cindex module, defined @cindex #require, introduced @command{Mailfromd} comes with a rich set of predefined functions for various purposes. There are two basic function classes: @dfn{built-in} functions, that are implemented by the @acronym{MFL} runtime environment in @command{mailfromd}, and @dfn{library} functions, that are implemented in @acronym{MFL}. The built-in functions are always available and no preparatory work is needed before calling them. In contrast, the library functions are defined in @dfn{modules}, special @acronym{MFL} source files that contain functions designed for a particular task. In order to access a library function, you must first @dfn{require} a module it is defined in. This is done using @code{#require} statement. For example, the function @code{hostname} looks up in the @acronym{DNS} the name corresponding to the @acronym{IP} address specified as its argument. This function is defined in module @file{dns.mf}, so before calling it you must require this module: @smallexample #require dns @end smallexample @noindent The @code{#require} statement takes a single argument: the name of the requested module (without the @samp{.mf} suffix). It looks up the module on disk and loads it if it is available. For more information about the module system @xref{Modules}. @node Domain Name System @section Domain Name System Site administrators often do not wish to accept mail from hosts that do not have a proper reverse delegation in the Domain Name System. In the previous section we introduced the library function @code{hostname}, that looks up in the @acronym{DNS} the name corresponding to the @acronym{IP} address specified as its argument. If there is no corresponding name, the function returns its argument unchanged. This can be used to test if the @acronym{IP} was resolved, as illustrated in the example below: @smallexample @group #require dns prog envfrom do if hostname($client_addr) = $client_addr reject fi done @end group @end smallexample The @code{#require dns} statement loads the module @file{dns.mf}, after which the definition of @code{hostname} becomes available. An orthogonal function, @code{resolve}, which resolves the symbolic name to the corresponding @acronym{IP} address is provided in the same @file{dns.mf} module. @node Checking Sender Address @section Checking Sender Address The main purpose of @command{mailfromd} is verification of the sender address, therefore a special construct is provided for this purpose: @smallexample @group on poll $f do when success: accept when not_found or failure: reject 550 5.1.0 "Sender validity not confirmed" when temp_failure: tempfail 450 4.1.0 "Try again later" done @end group @end smallexample The @code{on poll} construct runs standard verification (@pxref{standard verification}) for the email address specified as its argument (in the example above it is the value of the Sendmail macro @samp{$f}). The check can result in the following conditions: @table @code @item success The address exists. @item not_found The address does not exist. @item failure Some error of permanent nature occurred during the check. The existence of the address cannot be verified. @item temp_failure Some temporary failure occurred during the check. The existence of the address cannot be verified at the moment. @end table The @code{when} branches of the @code{on poll} statement introduce statements, that should be executed upon each of these conditions. If any condition occurs that is not handled within the @code{on} block, the run-time evaluator will signal an @dfn{exception}@footnote{For more information about exceptions and their handling, please refer to @ref{Exceptions}.} and return temporary failure, therefore it is advisable to always handle all four conditions. In fact, the condition handling shown in the above example is preferable for most normal configuration: the mail is accepted if the sender address is proved to exist and rejected otherwise. If a temporary failure occurs, the remote party is urged to retry the transaction some time later. The @code{poll} statement itself has a number of options that control the type of the verification. These are discussed in detail in @ref{poll}. It is worth noticing that there is one special email address which is always available on any host, it is the @dfn{null address} @samp{<>} used in error reporting. It is best to not verify this address: @smallexample @group prog envfrom do if $f == "" accept else on poll $f do when success: accept when not_found or failure: reject 550 5.1.0 "Sender validity not confirmed" when temp_failure: tempfail 450 4.1.0 "Try again later" done fi done @end group @end smallexample @node SMTP Timeouts @section @acronym{SMTP} Timeouts When using polling functions, it is important to take into account possible delay, which can occur in @acronym{SMTP} transactions. Most often such delays are due to low network bandwidth, but sometimes remote sites impose them willingly, as a spam-fighting measure@footnote{My private opinion is that such practice is completely lame.} @cindex timeouts, defined @command{Mailfromd} polling functions implement three distinct @dfn{timeout} values: @table @dfn @cindex connection timeout @cindex timeout, connection @item Connection timeout Maximum time for establishing the initial @acronym{TCP} connection to the remote host. If the connection is not established within this time interval, the polling returns @code{temp_failure}. @cindex initial response timeout @cindex timeout, initial response @item Initial response timeout Maximum time before receiving initial @acronym{SMTP} response from the remote host. @cindex I/O timeout @cindex timeout, I/O @cindex timeout, input/output @item I/O timeout Maximum amount of time for finishing an input/output operation with the remote @acronym{SMTP} server. @end table These three timeouts can be set using the following @dfn{pragmatic comments}@footnote{@xref{Pragmatic comments}, for a detailed description of pragmatic comments.} in the script file: @smallexample @group #pragma option connect-timeout @var{interval} #pragma option initial-response-timeout @var{interval} #pragma option io-timeout @var{interval} @end group @end smallexample Here, @var{interval} is the time interval, expressed in usual time units@footnote{@xref{time interval specification}, for its detailed description.}, for example: @smallexample #pragma option initial-response-timeout 1 minute 30 seconds @end smallexample The default values are: @smallexample @group #pragma option connect-timeout @value{CONNECT-TIMEOUT} #pragma option initial-response-timeout @value{INITIAL-RESPONSE-TIMEOUT} #pragma option io-timeout @value{IO-TIMEOUT} @end group @end smallexample @cindex CommuniGate Pro servers, lameness You will most certainly encounter some servers that deliberately delay issuing the initial @acronym{SMTP} reply (in particular, I have noted that most @samp{CommuniGate Pro} servers are guilty of this lame practice). The default @code{initial-response-timeout} value should be enough to cope with most of them. If you encounter some server that delays more than 30 seconds, you can raise the @code{initial-response-timeout} value. However, in this case, I'd rather recommend informing its admin that his server settings are not tolerable. @node Avoiding Verification Loops @section Avoiding Verification Loops An @code{envfrom} program consisting only of the @code{on poll} statement will work smoothly for incoming mails, but will create infinite loops for outgoing mails. This is because, upon sending an outgoing message @command{mailfromd} will start the verification procedure, which will initiate an @acronym{SMTP} transaction with the same mail server that runs it. This transaction will in turn trigger execution of @code{on poll} statement, etc. @i{ad infinitum}. To avoid this, any properly written filter script should not run the verification procedure on the email addresses in those domains that are relayed by the server it runs on. This can be achieved using @code{relayed} function. The function returns @code{true} if its argument is contained in one of the predefined @dfn{domain list} files. These files correspond to @command{Sendmail} plain text files used in @code{F} class definition forms (see @cite{Sendmail Installation and Operation Guide}, chapter 5.3), i.e. they contain one domain name per line, with empty lines and lines started with @samp{#} being ignored. The domain files consulted by @code{relayed} function are defined using the special @code{#pragma option relay} statement: @smallexample @group #pragma option relay "/etc/mail/local-host-names" #pragma option relay "/etc/mail/relay-domains" @end group @end smallexample The above example declares two domain list files, most commonly used in @command{Sendmail} installations to keep hostnames of the server @footnote{class @samp{w}, see @cite{Sendmail Installation and Operation Guide}, chapter 5.2.} and names of the domains, relayed by this server@footnote{class @samp{R}}. Given all this, we can improve our filter program: @smallexample @group #require dns #pragma option relay "/etc/mail/local-host-names" #pragma option relay "/etc/mail/relay-domains" prog envfrom do if $f == "" accept elif relayed(hostname($@{client_addr@})) accept else on poll $f do when success: accept when not_found or failure: reject 550 5.1.0 "Sender validity not confirmed" when temp_failure: tempfail 450 4.1.0 "Try again later" done fi done @end group @end smallexample If you feel that your Sendmail's relayed domains are not restrictive enough for @command{mailfromd} filters (for example you are relaying mails from some third-party servers), you can use a database of trusted mail server addresses. If the number of such servers is small enough, a single @samp{or} statement can be used, e.g.: @smallexample elif $@{client_addr@} = "10.10.10.1" or $@{client_addr@} = "192.168.11.7" accept @dots{} @end smallexample @noindent otherwise, if the servers' @acronym{IP} addresses fall within one or several @acronym{CIDR}s, you can use the @code{match_cidr} function (@pxref{Internet address manipulation functions}), e.g.: @smallexample elif match_cidr ($@{client_addr@}, "199.232.0.0/16") accept @dots{} @end smallexample @noindent or combine both methods. Finally, you can keep a @acronym{DBM} database of relayed addresses and use @code{dbmap} or @code{dbget} function for checking (@pxref{Database functions}). @smallexample elif dbmap(__statedir__ "/relay.db", $@{client_addr@}) accept @dots{} @end smallexample @node HELO Domain @section HELO Domain @cindex s, @command{Sendmail} macro Some of the mail filtering conditions may depend on the value of @dfn{helo domain} name, i.e. the argument to the @acronym{SMTP} @code{EHLO} (or @code{HELO}) command. If you ever need such conditions, take into account the following caveats. Firstly, although @command{Sendmail} passes the helo domain in @code{$s} macro, it does not do this consistently. In fact, the @code{$s} macro is available only to the @code{helo} handler, all other handlers won't see it, no matter what the value of the corresponding @code{Milter.macros.@var{handler}} statement. So, if you wish to access its value within an other handler, you will have to store it in a @dfn{variable} in the @code{helo} handler and then use this variable value in the other handler. This brings us to the concept of variables in @command{mailfromd} scripts. @cindex variables, introduced @cindex variable declaration A variable is declared using the following syntax: @smallexample @var{type} @var{name} @end smallexample @noindent where @var{variable} is the variable name and @var{type} is @samp{string}, if the variable is to hold a string value, and @samp{number}, if it is supposed to have a numeric value. @cindex variable assignment @cindex assignment to variable A variable is assigned a value using @code{set} statement, as shown below: @smallexample set @var{name} @var{expr} @end smallexample @noindent where @var{expr} is any valid @acronym{MFL} expression. To get the value of a variable, the following notation is used: @code{%@var{name}}. The @code{set} statement can occur within handler declarations as well as outside of them. There are two kinds of @command{Mailfromd} variables: @dfn{global variables}, that are visible to all handlers and functions, and @dfn{automatic variables}, that are available only within the handler or function where they are declared. For our purpose we need a global variable (@xref{Variables, Variable classes}, for detailed descriptions of both kinds of variables). The following example illustrates the approach that allows to use the @code{HELO} domain name in any handler: @smallexample @group # @r{Declare the helohost variable} string helohost prog helo do # @r{Save the host name for further use} set helohost $s done prog envfrom do # @r{Reject hosts claiming to be @i{localhost}} if %helohost = "localhost" reject 570 "Please specify real host name" fi done @end group @end smallexample Notice, that for this approach to work, the @command{Sendmail} statement @code{Milter.macros.helo} must contain @samp{s} (@pxref{Sendmail}). This requirement can be removed by using the @dfn{handler argument} of @code{helo}. Each @command{mailfromd} handler is given one or several arguments. The exact number of arguments and their meaning are handler-specific and are described in @ref{Handlers}, and @ref{milter-control-flow}. The arguments are referenced by their ordinal number, using the notation @code{$@var{n}}. The @code{helo} handler takes one argument, whose value is the helo domain. Using this information, the @code{helo} handler from the example above can be rewritten as follows: @smallexample @group prog helo do # @r{Save the host name for further use} set helohost $1 done @end group @end smallexample @node Controlling Number of Recipients @section Controlling Number of Recipients @cindex @code{MaxRecipientsPerMessage}, @command{sendmail} option The simplest way to control the number of recipients per message in @command{Sendmail} is using the option @code{MaxRecipientsPerMessage}@footnote{@cite{Sendmail (tm) Installation and Operation Guide}, chapter 5.6, @samp{O -- Set Option}.}. However, it has its limitations and is not flexible, so you are often better off using @command{mailfromd} for this purpose. @command{Mailfromd} keeps the number of recipients collected so far in variable @code{%rcpt_count}, which can be controlled in @code{envrcpt} handler as shown in the example below: @smallexample @group prog envrcpt do if %rcpt_count > 10 reject 550 5.7.1 "Too many recipients" fi done @end group @end smallexample This filter will accept no more than 10 recipients per message. You may achieve finer granularity by using additional conditions. For example, the following code will allow any number of recipients if the mail is coming from a domain relayed by the server, while limiting it to 10 for incoming mail from other domains: @smallexample @group prog envrcpt do if not relayed hostname $client_addr and %rcpt_count > 10 reject 550 5.7.1 "Too many recipients" fi done @end group @end smallexample There are three important features to notice in the above code. First of all, it introduces two @dfn{boolean} operators: @code{and}, which evaluates to @code{true} only if both left-side and right-side expressions are @code{true}, and @code{not}, which reverses the value of its argument. Secondly, the scope of an operation is determined by its @dfn{precedence}, or @dfn{binding strength}. @code{Not} binds more tightly than @code{and}, so its scope is limited by the next expression between it and @code{and}. Using parentheses to underline the operator scoping, the above @code{if} condition can be rewritten as follows: @smallexample if (not (relayed (hostname ($client_addr)))) and (%rcpt_count > 10) @end smallexample Finally, it is important to notice that all boolean expressions are computed using @dfn{shortcut evaluation}. To understand what it is, let's consider the following expression: @code{@var{x} and @var{y}}. Its value is @code{true} only if both @var{x} and @var{y} are @code{true}. Now suppose that we evaluate the expression from left to right and we find that @var{x} is false. This means that no matter what the value of @var{y} is, the resulting expression will be @code{false}, therefore there is no need to compute @var{y} at all. So, the boolean shortcut evaluation works as follows: @table @code @item @var{x} and @var{y} If @code{@var{x} @result{} @code{false}}, do not evaluate @var{y} and return @code{false}. @item @var{x} or @var{y} If @code{@var{x} @result{} @code{true}}, do not evaluate @var{y} and return @code{true}. @end table Thus, in the expression @code{not relayed hostname $client_addr and %rcpt_count > 10}, the value of the @code{rcpt_count} variable will be compared with @samp{10} only if the @code{relayed} function yielded @code{false}. To further enhance our sample filter, you may wish to make the @code{reject} output more informative, to let the sender know what the recipient limit is. To do so, you can use the fact that in @command{mailfromd} @emph{adjacent string expressions concatenate}, so the enhanced filter version could look like: @smallexample @group set max_rcpt 10 prog envrcpt do if not relayed hostname $client_addr and %rcpt_count > 10 reject 550 5.7.1 "Too many recipients, max=" %max_rcpt fi done @end group @end smallexample When evaluating the third argument to @code{reject}, @command{mailfromd} will first convert @code{%max_rcpt} to string and then concatenate both strings together, producing string @samp{Too many recipients, max=10}. @node Sending Rate @section Sending Rate We have introduced the notion of mail sending rate in @ref{Rate Limit}. @command{Mailfromd} keeps the computed rates in the special @code{rate} database (@pxref{Databases}). Each record in this database consists of a @code{key}, for which the rate is computed, and the rate value, in form of a double precision floating point number, representing the average number of messages per second sent by this @code{key} within the last sampling interval. In the simplest case, the sender email address can be used as a @code{key}, however we recommend to use a conjunction @var{email}-@var{sender_ip} instead, so the actual @var{email} owner won't be blocked by actions of some spammer abusing his/her address. Two functions are provided to control and update sending rates. The @code{rateok} function takes three mandatory arguments: @smallexample bool rateok(string @var{key}, number @var{interval}, number @var{threshold}) @end smallexample The @var{key} meaning is described above. The @var{interval} is the sampling interval, or the number of seconds to which the actual sending rate value is converted. Remember that it is stored internally as a floating point number, and thus cannot be directly used in @command{mailfromd} filters, which operate only on integer numbers. To use the rate value, it is first converted to messages per given interval, which is an integer number. For example, the rate @code{0.138888} brought to 1-hour interval gives @code{500} (messages per hour). Wherever the @code{rateok} function is called, it recomputes the rate record for the given @var{key}. If the new rate value converted to messages per given @var{interval} is less than @var{threshold}, the function updates the database and returns @code{True}. Otherwise it returns @code{False} and does not update the database. This function must be @dfn{required} prior to use, by placing the following statement somewhere at the beginning of your script: @smallexample #require rateok @end smallexample For example, the following code limits the mail sending rate for each @samp{email address}-@samp{@acronym{IP}} combination to 180 per hour. If the actual rate value exceeds this limit, the sender is returned a temporary failure response: @smallexample @group #require rateok prog envfrom do if not rateok($f "-" $@{client_addr@}, 3600, 180) tempfail 450 4.7.0 "Mail sending rate exceeded. Try again later" fi done @end group @end smallexample @noindent Notice argument concatenation, used to produce the key. It is often inconvenient to specify intervals in seconds, therefore a special @code{interval} function is provided. It converts its argument, which is a textual string representing time interval in English, to the corresponding number of seconds. Using this function, the function invocation would be: @smallexample rateok($f "-" $@{client_addr@}, interval("1 hour"), 180) @end smallexample The @code{interval} function is described in @ref{interval}, and time intervals are discussed in @ref{time interval specification}. The @code{rateok} function begins computing the rate as soon as it has collected enough data. By default, it needs at least four mails. Since this may lead to a big number of false positives (i.e. overestimated rates) at the beginning of sampling interval, there is a way to specify a minimum number of samples @code{rateok} must collect before starting to actually compute rates. This number of samples is given as the optional fourth argument to the function. For example, the following call will always return @code{True} for the first 10 mails, no matter what the actual rate: @smallexample rateok($f "-" $@{client_addr@}, interval("1 hour"), 180, 10) @end smallexample @anchor{TBF} The @code{tbf_rate} function allows to exercise more control over the mail rates. This function implements a @dfn{token bucket filter} (@acronym{TBF}) algorithm. The token bucket controls when the data can be transmitted based on the presence of abstract entities called @dfn{tokens} in a container called @dfn{bucket}. Each token represents some amount of data. The algorithm works as follows: @itemize @bullet @item A token is added to the bucket at a constant rate of 1 token per @var{t} microseconds. @item A bucket can hold at most @var{m} tokens. If a token arrives when the bucket is full, that token is discarded. @item When @var{n} items of data arrive (e.g. @var{n} mails), @var{n} tokens are removed from the bucket and the data are accepted. @item If fewer than @var{n} tokens are available, no tokens are removed from the bucket and the data are not accepted. @end itemize This algorithm allows to keep the data traffic at a constant rate @var{t} with bursts of up to @var{m} data items. Such bursts occur when no data was being arrived for @var{m}*@var{t} or more microseconds. @command{Mailfromd} keeps buckets in a database @samp{tbf}. Each bucket is identified by a unique @dfn{key}. The @code{tbf_rate} function is defined as follows: @smallexample bool tbf_rate(string @var{key}, number @var{n}, number @var{t}, number @var{m}) @end smallexample The @var{key} identifies the bucket to operate upon. The rest of arguments is described above. The @code{tbf_rate} function returns @samp{True} if the algorithm allows to accept the data and @samp{False} otherwise. Depending on how the actual arguments are selected the @code{tbf_rate} function can be used to control various types of flow rates. For example, to control mail sending rate, assign the arguments as follows: @var{n} to the number of mails and @var{t} to the control interval in microseconds: @smallexample @group prog envfrom do if not tbf_rate($f "-" $client_addr, 1, 10000000, 20) tempfail 450 4.7.0 "Mail sending rate exceeded. Try again later" fi done @end group @end smallexample The example above permits to send at most one mail each 10 seconds. The burst size is set to 20. Another use for the @code{tbf_rate} function is to limit the total delivered mail size per given interval of time. To do so, the function must be used in @code{prog eom} handler, because it is the only handler where the entire size of the message is known. The @var{n} argument must contain the number of bytes in the email (or email bytes * number of recipients), and the @var{t} must be set to the number of bytes per microsecond a given user is allowed to send. The @var{m} argument must be large enough to accommodate a couple of large emails. E.g.: @smallexample @group prog eom do if not tbf_rate($f "-" $client_addr, message_size(current_message()), 10240*1000000, # At most 10 kb/sec 10*1024*1024) tempfail 450 4.7.0 "Data sending rate exceeded. Try again later" fi done @end group @end smallexample @xref{Rate limiting functions}, for more information about @code{rateok} and @code{tbf_rate} functions. @node Greylisting @section Greylisting Greylisting is a simple method of defending against the spam proposed by Evan Harris. In few words, it consists in recording the @samp{sender @acronym{IP}}-@samp{sender email}-@samp{recipient email} triplet of mail transactions. Each time the unknown triplet is seen, the corresponding message is rejected with @code{tempfail} code. If the mail is legitimate, this will make the originating server retry the delivery later, at which time the destination will accept it. If, however, the mail is a spam, it will probably never be retried, so the users will not be bothered by it. Even if the spammer will retry the delivery, the @dfn{greylisting period} will give spam-detection systems, such as @acronym{DNSBL}s, enough time to detect and blacklist it, so by the time the destination host starts accepting emails from this triplet, it will already be blocked by other means. You will find the detailed description of the method in @uref{http://projects.puremagic.com/@/greylisting/@/whitepaper.html, The Next Step in the Spam Control War: Greylisting}, the original whitepaper by Evan Harris. The @command{mailfromd} implementation of greylisting is based on @code{greylist} function. The function takes two arguments: the @code{key}, identifying the greylisting triplet, and the @code{interval}. The function looks up the key in the @dfn{greylisting database}. If such a key is not found, a new entry is created for it and the function returns @code{true}. If the key is found, @code{greylist} returns @code{false}, if it was inserted to the database more than @code{interval} seconds ago, and @code{true} otherwise. In other words, from the point of view of the greylisting algorithm, the function returns @code{true} when the message delivery should be blocked. Thus, the simplest implementation of the algorithm would be: @smallexample @group prog envrcpt do if greylist($@{client_addr@} "-" $f "-" $@{rcpt_addr@}, interval("1 hour")) tempfail 451 4.7.1 "You are greylisted" fi done @end group @end smallexample @cindex greylist_seconds_left, global variable, introduced However, the message returned by this example, is not informative enough. In particular, it does not tell when the message will be accepted. To help you produce more informative messages, @code{greylist} function stores the number of seconds left to the end of the greylisting period in the global variable @code{greylist_seconds_left}, so the above example could be enhanced as follows: @smallexample @group prog envrcpt do set gltime interval("1 hour") if greylist($@{client_addr@} "-" $f "-" $@{rcpt_addr@}, %gltime) if %greylist_seconds_left = %gltime tempfail 451 4.7.1 "You are greylisted for " %gltime " seconds" else tempfail 451 4.7.1 "Still greylisted for " %greylist_seconds_left " seconds" fi fi done @end group @end smallexample In real life you will have to avoid greylisting some messages, in particular those coming from the @samp{<>} address and from the @acronym{IP} addresses in your relayed domain. It can easily be done using the techniques described in previous sections and is left as an exercise to the reader. @anchor{greylisting types} @cindex greylisting types @cindex greylisting, traditional @code{Mailfromd} provides two implementations of greylisting primitives, which differ in the information stored in the database. The one described above is called @dfn{traditional}. It keeps in the database the time when the greylisting was activated for the given key, so the @code{greylisting} function uses its second argument (@code{interval}) and the current timestamp to decide whether the key is still greylisted. @cindex greylisting, Con Tassios type @cindex Con Tassios greylisting type The second implementation is called by the name of its inventor @dfn{Con Tassios}. This implementation stores in the database the time when the greylisting period is set to expire, computed by the @code{greylist} when it is first called for the given key, using the formula @samp{current_timestamp + interval}. Subsequent calls to @code{greylist} compare the current timestamp with the one stored in the database and ignore their second argument. This implementation is enabled by one of the following pragmas: @smallexample #pragma greylist con-tassios @end smallexample @noindent or @smallexample #pragma greylist ct @end smallexample When Con Tassios implementation is used, yet another function becomes available. The function @code{is_greylisted} returns @samp{True} if its argument is greylisted and @samp{False} otherwise. It can be used to check for the greylisting status without actually updating the database: @smallexample if is_greylisted($@{client_addr@} "-" $f "-" $@{rcpt_addr@}) @dots{} fi @end smallexample @anchor{whitelisting} @cindex whitelisting One special case is @dfn{whitelisting}, which is often used together with greylisting. To implement it, @command{mailfromd} provides the function @code{dbmap}, which takes two mandatory arguments: @code{dbmap(@var{file}, @var{key})} (it also allows an optional third argument, see @ref{dbmap}, for more information on it). The first argument is the name of the @acronym{DBM} file where to search for the key, the second one is the key to be searched. Assuming you keep your whitelist database in file @file{/var/run/whitelist.db}, a more practical example will be: @smallexample @group prog envrcpt do set gltime interval("1 hour") if not ($f = "" or relayed hostname $@{client_addr@} or dbmap("/var/run/whitelist.db", $@{client_addr@})) if greylist($@{client_addr@} "-" $f "-" $@{rcpt_addr@}, %gltime) if %greylist_seconds_left = %gltime tempfail 451 4.7.1 "You are greylisted for " %gltime " seconds" else tempfail 451 4.7.1 "Still greylisted for " %greylist_seconds_left " seconds" fi fi fi done @end group @end smallexample @node Local Account Verification @section Local Account Verification In your filter script you may need to verify if the given user name is served by your mail server, in other words, to verify if it represents a @dfn{local account}. Notice that in this context, the word @dfn{local} does not necessarily mean that the account is local for the server running @command{mailfromd}, it simply means any account whose mailbox is served by the mail servers using @command{mailfromd}. The @code{validuser} function may be used for this purpose. It takes one argument, the user name, and returns @code{true} if this name corresponds to a local account. To verify this, the function relies on @command{libmuauth}, a powerful authentication library shipped with GNU @command{mailutils}. More precisely, it invokes a list of @dfn{authorization} functions. Each function is responsible for looking up the user name in a particular source of information, such as system @file{passwd} database, an @acronym{SQL} database, etc. The search is terminated when one of the functions finds the name in question or the list is exhausted. In the former case, the account is local, in the latter it is not. This concept is discussed in detail in @pxref{authentication, Authentication, Authorization and Authentication Principles, mailutils, GNU Mailutils Manual}). Here we will give only some practical advices for implementing it in @command{mailfromd} filters. The actual list of available authorization modules depends on your @command{mailutils} installation. Usually it includes, apart from traditional @acronym{UNIX} @file{passwd} database, the functions for verifying @acronym{PAM}, @acronym{RADIUS} and @acronym{SQL} database accounts. Each of the authorization methods is configured using special configuration file statements. For the description of the Mailutils configuration files, @xref{configuration, Mailutils Configuration File, Mailutils Configuration File, mailutils, GNU Mailutils Manual}. You can obtain the template for @command{mailfromd} configuration by running @command{mailfromd --config-help}. For example, the following @file{mailutils.rc} file: @smallexample @group program mailfromd @{ auth @{ authorization pam:system; @} pam @{ service mailfromd; @} @} @end group @end smallexample @noindent sets up the authorization using @acronym{PAM} and system @file{passwd} database. The name of @acronym{PAM} service to use is @samp{mailfromd}. @cindex aliases, looking up The function @code{validuser} is often used together with @code{dbmap}, as in the example below: @smallexample @group #pragma /etc/mail/aliases.db null if dbmap("/etc/mail/aliases.db", localpart($rcpt_addr)) and validuser localpart $rcpt_addr @dots{} fi @end group @end smallexample For more information about @code{dbmap} function, see @ref{dbmap}. For a description of @code{dbprop} pragma, see @ref{Database functions}. @node Examining mail contents @section Examining mail contents @cindex Examining mail contents @cindex mail contents, examining @WRITEME{} @node Databases @section Databases Some @command{mailfromd} functions use @acronym{DBM} databases to save their persistent state data. Each database has a unique @dfn{identifier}, and is assigned several pieces of information for its maintenance: the database @dfn{file name} and the @dfn{expiration period}, i.e. the time after which a record is considered expired. @xopindex{show-defaults, introduced} To obtain the list of available databases along with their preconfigured settings, run @kbd{mailfromd --show-defaults}. You will see an output similar to this: @smallexample @group version: @value{VERSION} script file: /etc/mailfromd.rc user: mail statedir: /var/run/mailfromd socket: unix:/var/run/mailfromd/mailfrom pidfile: /var/run/mailfromd/mailfromd.pid default syslog: blocking database format: Berkeley DB 2.x dns database: /var/run/mailfromd/dns.db dns negative expiration: 3600 cache database: /var/run/mailfromd/mailfromd.db cache expiration: 86400 cache negative expiration: 43200 greylist database: /var/run/mailfromd/greylist.db greylist expiration: 86400 rate database: /var/run/mailfromd/rates.db rate expiration: 86400 @end group @end smallexample The text below @samp{database format} line describes all available databases. Notice that the @samp{cache} database, in contrast to the rest of databases, has two expire periods associated with it. This is explained in the next subsection. @menu * Database Formats:: * Basic Database Operations:: * Database Maintenance:: @end menu @node Database Formats @subsection Database Formats @cindex database formats The version @value{VERSION} runs the following database types (or @dfn{formats}): @cindex databases used by @command{mailfromd} @table @samp @cindex dns database @item dns @dfn{DNS database} caches @acronym{DNS} lookups. The key consists of the lookup type and the actual lookup key, separated by a single space. The type can be one of @samp{A}, @samp{PTR}, @samp{MX}. The value is an @acronym{ASCII} string built up of one or more fields, separated by a single space. The first field is always the expiration date for this record in seconds since the Epoch (00:00:00 UTC, January 1, 1970). The meaning of the rest of the fields depends on the lookup type as described in the following table: @table @asis @item A Each field contains the next @acronym{IP} address corresponding to the lookup key. Notice, that currently (version @value{VERSION}) there can be at most one field here, but it may change in the future. @item PTR Each field contains a host name corresponding to the lookup key. Notice, that currently (version @value{VERSION}) there can be at most one field here, but it may change in the future. @item MX Each field contains a host name of an @samp{MX} record for the lookup key. @end table @xref{DNS Cache Management}, for more information of @acronym{DNS} cache database and its management. @cindex cache database @item cache @dfn{Cache database} keeps the information about external emails, obtained using sender verification functions (@pxref{Checking Sender Address}). The key entry to this database is an email address or @var{email}:@var{sender-ip} string, for addresses checked using strict verification. The data its stores for each key are: @enumerate 1 @item Address validity. This field can be either @code{success} or @code{not_found}, meaning the address is confirmed to exists or it is not. @item The time when the entry was entered into the database. It is used to check for expired entries. @end enumerate @anchor{cache expiration} @cindex positive expiration period, defined @cindex negative expiration period, defined The @samp{cache} database has two expiration periods: a @dfn{positive expiration} period, that is applied to entries with the first field set to @code{success}, and a @dfn{negative expiration} period, applied to entries marked as @code{not_found}. @cindex rate database @item rate The mail sending rate data, maintained by @code{rate} function (@pxref{Rate limiting functions}). A record consists of the following fields: @table @asis @item timestamp The time when the entry was entered into the database. @item interval Interval during which the rate was measured (seconds). @item count Number of mails sent during this interval. @end table @cindex tbf database @item tbf This database is maintained by @code{tbf_rate} function (@pxref{TBF}). Each record represents a single bucket and consists of the following keys: @table @asis @item timestamp Timestamp of most recent token, as a 64-bit unsigned integer (microseconds resolution). @item expirytime Estimated time when this bucket expires (seconds since epoch). @item tokens Number of tokens in the bucket (@code{size_t}). @end table @cindex greylist database @item greylist This database is maintained by @code{greylist} function (@pxref{Greylisting}). Each record holds only the timestamp. Its semantics depends on the greylisting implementation in use (@pxref{greylisting types}). In traditional implementation, it is the time when the entry was entered into the database. In Con Tassios implementation, it is the time when the greylisting period expires. @end table @node Basic Database Operations @subsection Basic Database Operations @cindex database, listing @cindex listing a database contents @xopindex{list, described} @anchor{--list option} To list the contents of a database, use @option{--list} option. When used without any arguments it will list the @samp{cache} database: @smallexample @group $ @kbd{mailfromd --list} abrakat@@mail.com success Thu Aug 24 15:28:58 2006 baccl@@EDnet.NS.CA not_found Fri Aug 25 10:04:18 2006 bhzxhnyl@@chello.pl not_found Fri Aug 25 10:11:57 2006 brqp@@aaanet.ru:24.1.173.165 not_found Fri Aug 25 14:16:06 2006 @end group @end smallexample You can also list data for any particular key or keys. To do so, give the keys as arguments to @command{mailfromd}: @smallexample @group $ @kbd{mailfromd --list abrakat@@mail.com brqp@@aaanet.ru:24.1.173.165} abrakat@@mail.com success Thu Aug 24 15:28:58 2006 brqp@@aaanet.ru:24.1.173.165 not_found Fri Aug 25 14:16:06 2006 @end group @end smallexample @xopindex{format, introduced} @xopindex{format, using with @option{--list}} To list another database, give its format identifier with the @option{--format} (@option{-H}) option. For example, to list the @samp{rate} database: @smallexample @group $ mailfromd --list --format=rate sam@@mail.net-62.12.4.3 Wed Sep 6 19:41:42 2006 139 3 0.0216 6.82e-06 axw@@rame.com-59.39.165.172 Wed Sep 6 20:26:24 2006 0 1 N/A N/A @end group @end smallexample The @option{--format} option can be used with any database management option, described below. @anchor{estimated time of sending} @cindex estimated time of sending, prediction of @xopindex{predict, introduced} Another useful operation you can do while listing @samp{rate} database is the prediction of @dfn{estimated time of sending}, i.e. the time when the user will be able to send mail if currently his mail sending rate has exceeded the limit. This is done using @option{--predict} option. The option takes an argument, specifying the mail sending rate limit, e.g. (the second line is split for readability): @smallexample @group $ @kbd{mailfromd --predict="180 per 1 minute"} ed@@fae.net-21.10.1.2 Wed Sep 13 03:53:40 2006 0 1 N/A N/A; free to send service@@19.netlay.com-69.44.129.19 Wed Sep 13 15:46:07 2006 7 2 0.286 0.0224; in 46 sec. on Wed Sep 13 15:49:00 2006 @end group @end smallexample @noindent Notice, that there is no need to use @option{--list --format=rate} along with this option, although doing so is not an error. @anchor{deleting from databases} @xopindex{delete, introduced} To delete an entry from the database, use @option{--delete} option, for example: @kbd{mailfromd --delete abrakat@@mail.com}. You can give any number of keys to delete in the command line. @node Database Maintenance @subsection Database Maintenance @cindex database maintenance @cindex maintenance, database There are two principal operations of database management: expiration and compaction. @dfn{Expiration} consists in removing expired entries from the database. In fact, it is rarely needed, since the expired entries are removed in the process of normal @command{mailfromd} work. Nevertheless, a special option is provided in case an explicit expiration is needed (for example, before dumping the database to another format, to avoid transferring useless information). @xopindex{expire, introduced} The command line option @option{--expire} instructs @command{mailfromd} to delete expired entries from the specified database. As usual, the database is specified using @option{--format} option. If it is not given explicitly, @samp{cache} is assumed. @cindex database compaction @cindex compaction, database While removing expired entries the space they occupied is marked as free, so it can be used by subsequent inserts. The database does not shrink after expiration is finished. To actually return the unused space to the file system you should @dfn{compact} your database. @anchor{compaction} @xopindex{compact, introduced} This is done by running @kbd{mailfromd --compact} (and, optionally, specifying the database to operate upon with @option{--format} option). Notice, that compacting a database needs roughly as much disk space on the partition where the database resides as is currently used by the database. Database compaction runs in three phases. First, the database is scanned and all non-expired records are stored in the memory. Secondly, a temporary database is created in the state directory and all the cached entries are flushed into it. This database is named after the @acronym{PID} of the running @command{mailfromd} process. Finally, the temporary database is renamed to the source database. @anchor{compact cronjob} @xopindex{all, introduced} Both @option{--compact} and @option{--expire} can be applied to all databases by combining them with @option{--all}. It is useful, for example, in @file{crontab} files. For example, I have the following monthly job in my @file{crontab}: @smallexample 0 1 1 * * /usr/local/sbin/mailfromd --compact --all @end smallexample @node Testing Filter Scripts @section Testing Filter Scripts It is important to check your filter script before actually starting to use it. There are several ways to do so. @cindex lint mode @cindex syntax check @cindex script file checking @xopindex{lint, introduced} @xopindex{syntax-check, introduced} To test the syntax of your filter script, use the @option{--lint} option. It will cause @command{mailfromd} to exit immediately after attempting to compile the script file. If the compilation succeeds, the program will exit with code 0. Otherwise, it will exit with error code 78 (@samp{configuration error}). In the latter case, @command{mailfromd} will also print a diagnostic message, describing the error along with the exact location where the error was diagnosed, for example: @smallexample @group mailfromd: /etc/mailfromd.rc:39: syntax error, unexpected ACT_REJECT, expecting OR or AND or ')' @end group @end smallexample @cindex cross-reference For complex scripts you may wish to obtain a listing of variables used in the script. This can be achieved using @option{--xref} command line option: The output it produces consists of four columns: @table @asis @item Variable name @item Data type Either @code{number} or @code{string}. @item Offset in data segment Measured in words. @item References A comma-separated list of locations where the variable was referenced. Each location is represented as @var{file}:@var{line}. If several locations pertain to the same @var{file}, the file name is listed only once. @end table @noindent Here is an example of the cross-reference output: @smallexample @group $ @kbd{mailfromd --xref} Cross-references: ----------------- cache_used number 5 /etc/mailfromd.rc:48 clamav_virus_name string 9 /etc/mailfromd.rc:240,240 db string 15 /etc/mailfromd.rc:135,194,215 dns_record_ttl number 16 /etc/mailfromd.rc:136,172,173 ehlo_domain string 11 gltime number 13 /etc/mailfromd.rc:37,219,220,222,223 greylist_seconds_left number 1 /etc/mailfromd.rc:220,226,227 last_poll_host string 2 @end group @end smallexample @anchor{test mode} @cindex filter script, debugging @cindex debugging the filter script @cindex filter script, running in test mode @xopindex{test, introduced} If the script passes syntax check, the next step is often to test if it works as you expect it to. This is done with @option{--test} (@option{-t}) command line option. This option runs the @code{envfrom} handler (or another one, see below) and prints the result of its execution. @cindex sendmail macros, setting from the command line When running your script in test mode, you will need to supply the values of @command{Sendmail} macros it needs. You do this by placing the necessary assignments in the command line. For example, this is how to supply initial values for @code{f} and @code{client_addr} macros: @smallexample $ @kbd{mailfromd --test f=gray@@gnu.org client_addr=127.0.0.1} @end smallexample @anchor{overriding initial values} @cindex overriding initial variable values @cindex variable values, setting from the command line @xopindex{variable, introduced} You may also need to alter initial values of some global variables your script uses. To do so, use @option{-v} (@option{--variable}) command line option. This option takes a single argument consisting of the variable name and its initial value, separated by an equals sign. For example, here is how to change the value of @code{ehlo_domain} global variable: @smallexample $ @kbd{mailfromd -v ehlo_domain=mydomain.org} @end smallexample The @option{--test} option is often useful in conjunction with options @option{--debug}, @option{--trace} and @option{--transcript} (@pxref{Logging and Debugging}. The following example shows what the author got while debugging the filter script described in @ref{Filter Script Example}: @smallexample @group $ @kbd{mailfromd --test --debug=50 f=gray@@gnu.org client_addr=127.0.0.1} MX 20 mx20.gnu.org MX 10 mx10.gnu.org MX 10 mx10.gnu.org MX 20 mx20.gnu.org getting cache info for gray@@gnu.org found status: success (0), time: Thu Sep 14 14:54:41 2006 getting rate info for gray@@gnu.org-127.0.0.1 found time: 1158245710, interval: 29, count: 5, rate: 0.172414 rate for gray@@gnu.org-127.0.0.1 is 0.162162 updating gray@@gnu.org-127.0.0.1 rates SET REPLY 450 4.7.0 Mail sending rate exceeded. Try again later State envfrom: tempfail @end group @end smallexample @xopindex{test, specifying handler name} To test any handler, other than @samp{envfrom}, give its name as the argument to @option{--test} option. Since this argument is optional, it is important that it be given immediately after the option, without any intervening white space, for example @kbd{mailfromd --test=helo}, or @kbd{mailfromd -thelo}. @cindex @command{mtasim}, introduced This method allows to test one handler at a time. To test the script as a whole, use @command{mtasim} utility. When started it enters interactive mode, similar to that of @command{sendmail -bs}, where it expects @acronym{SMTP} commands on its standard input and sends answers to the standard output. The @option{--port=auto} command line option instructs it to start @command{mailfromd} and to create a unique socket for communication with it. For the detailed description of the program and the ways to use it, @xref{mtasim}. @node Run Mode @section Run Mode @cindex run mode Mailfromd provides a special option that allows to run arbitrary @acronym{MFL} scripts. This is an experimental feature, intended for future use of @acronym{MFL} as a scripting language. @xopindex{run, described} @cindex main, MFL function When given the @option{--run} command line option, @command{mailfromd} loads the script given in its command line and executes a function called @samp{main}. The function main must be declared as: @smallexample func main(...) returns number @end smallexample Mailfromd passes all command line arguments that follow the script name as arguments to that function. When the function returns, its return value is used by @command{mailfromd} as exit code. As an example, suppose the file @file{script.mf} contains the following: @smallexample func main (...) returns number do loop for number i 1, while %i <= $#, set i %i + 1 do echo "arg %i=" $(%i) done done @end smallexample This function prints all its arguments (@xref{variadic functions}, for a detailed description of functions with variable number of aruments). Now running: @smallexample $ mailfromd --run script.mf 1 file dest @end smallexample @noindent displays the following: @smallexample @cartouche arg 1=1 arg 2=file arg 3=dest @end cartouche @end smallexample Note, that @acronym{MFL} does not have a direct equivalent of shell's @code{$0} argument. If your function needs to know the name of the script that is being executed, use @code{__file__} built-in constant instead (@pxref{Built-in constants, __file__}. You may name your start function with any name other than the default @samp{main}. In this case, give its name as an argument to the @option{--run} option. This argument is optional, therefore it must be separated from the option by an equals sign (with no whitespace from either side). For example, given the command line below, @command{mailfromd} will load file @file{script.mf} and execute the function named @samp{start}: @smallexample $ mailfromd --run=start script.mf @end smallexample @menu * getopt:: Parsing Command Line Arguments. @end menu @node getopt @subsection Parsing Command Line Arguments @cindex command line arguments, parsing in MFL @cindex scripting, parsing command line arguments @cindex parsing command line arguments A special function is provided to break (parse) options in command lines, and to check for legal options. It uses the GNU getopt routines (@pxref{Getopt, getopt, , libc, The GNU C Library Reference Manual}). @deftypefn {Built-in Function} string getopt (number @var{argc}, @ pointer @var{argv}, ...) The @command{getopt} function parses the command line arguments, as supplied by @var{argc} and @var{argv}. The @var{argc} argument is the argument count, and @var{argv} is an opaque data structure, representing the array of arguments@footnote{When @acronym{MFL} has array data type, the second argument will change to array of strings.}. The operator @code{vaptr} (@pxref{vaptr}) is provided to initialize this argument. An argument that starts with @samp{-} (and is not exactly @samp{-} or @samp{--}), is an option element. An argument that starts with a @samp{-} is called @dfn{short} or @dfn{traditional} option. The characters of this element, except for the initial @samp{-} are option characters. Each option character represents a separate option. An argument that starts with @samp{--} is called @dfn{long} or @dfn{GNU} option. The characters of this element, except for the initial @samp{--} form the @dfn{option name}. Options may have arguments. The argument to a short option is supplied immediately after the option character, or as the next word in command line. E.g., if option @option{-f} takes a mandatory argument, then it may be given either as @option{-farg} or as @option{-f arg}. The argument to a long option is either given immediately after it and separated from the option name by an equals sign (as @option{--file=arg}), or is given as the next word in the command line (e.g. @option{--file arg}). If the option argument is optional, i.e. it may not necessarily be given, then only the first form is allowed (i.e. either @option{-farg} or @option{--file=arg}. The @samp{--} command line argument ends the option list. Any arguments following it are not considered options, even if they begin with a dash. If @code{getopt} is called repeatedly, it returns successively each of the option characters from each of the option elements (for short options) and each option name (for long options). In this case, the actual arguments are supplied only to the first invocation. Subsequent calls must be given two nulls as arguments. Such invocation instructs @code{getopt} to use the values saved on the previous invocation. When the function finds another option, it returns its character or name updating the external variable @code{optind} (see below) so that the next call to @code{getopt} can resume the scan with the following option. When there are no more options left, or a @samp{--} argument is encountered, @code{getopt} returns an empty string. Then @code{optind} gives the index in @var{argv} of the first element that is not an option. The legitimate options and their characteristics are supplied in additional arguments to @code{getopt}. Each such argument is a string consisting of two parts, separated by a vertical bar (@samp{|}). Any one of these parts is optional, but at least one of them must be present. The first part specifies short option character. If it is followed by a colon, this character takes mandatory argument. If it is followed by two colons, this character takes an optional argument. If only the first part is present, the @samp{|} separator may be omitted. Examples: @table @asis @item "c" @itemx "c|" Short option @option{-c}. @item "f:" @itemx "f:|" Short option @option{-f}, taking a mandatory argument. @item "f::" @itemx "f::|" Short option @option{-f}, taking an optional argument. @end table If the verical bar is present and is followed by any characters, these characters specify the name of a long option, synonymous to the short one, specified by the first part. Any mandatory or optional arguments to the short option remain mandatory or optional for the corresponding long option. Examples: @table @asis @item "f:|file" Short option @option{-f}, or long option @option{--file}, requiring an argument. @item "f::|file" Short option @option{-f}, or long option @option{--file}, taking an optional argument. @end table In any of the above cases, if this option appears in the command line, @command{getopt} returns its short option character. To define a long option without a short equivalent, begin it with a bar, e.g.: @table @asis @item "|help" @end table If this option is to take an argument, this is specified using the mechanism described above, except that the short option character is replaced with a minus sign. For example: @table @asis @item "-:|output" Long option @option{--output}, which takes a mandatory argument. @item "-::|output" Long option @option{--output}, which takes an optional argument. @end table @vrindex optarg If an option is returned that has an argument in the command line, @code{getopt} stores this argument in the variable @code{optarg}. @vrindex optind After each invocation, @code{getopt} sets the variable @code{optind} to the index of the next @var{argv} element to be parsed. Thus, when the list of options is exhausted and the function returned an empty string, @code{optind} contains the index of the the first element that is not an option. @vrindex optopt When @code{getopt} encounters an option that is not described in its arguments or if it detects a missing option argument it prints an error message using @command{mailfromd} logging facilities, stores the offending option in the variable @code{optopt}, and returns @samp{?}. @vrindex opterr If printing error message is not desired (e.g. the application is going to take care of error messaging), it can be disabled by setting the variable @code{opterr} to @samp{0}. @cindex controlling argument, getopt The third argument to @code{getopt}, called @dfn{controlling argument}, may be used to control the behavior of the function. If it is a colon, it disables printing the error message for unrecognized options and missing option arguments (as setting @code{opterr} to @samp{0} does). In this case @code{getopt} returns @samp{:}, instead of @samp{?} to indicate missing option argument. If the controlling argument is a plus sign, or the environment variable @env{POSIXLY_CORRECT} is set, then option processing stops as soon as a non-option argument is encountered. By default, if options and non optional arguments are intermixed in @var{argv}, @code{getopt} permutes them so that the options go first, followed by non-optional arguments. If the controlling argument is @samp{-}, then each non-option element in @var{argv} is handled as if it were the argument of an option with character code 1 (@samp{"\001"}, in @acronym{MFL} notation. This can used by programs that are written to expect options and other @var{argv}-elements in any order and that care about the ordering of the two. Any other value of the controlling argument is handled as an option definiton. @end deftypefn @anchor{vaptr} @cindex vaptr A special language construct is provided to supply the second argument (@var{argv}) to @code{getopt} and similar functions: @smallexample vaptr(@var{arg}) @end smallexample @noindent where @var{argv} is a positional parameter, from which to start the array of @var{argv}. For example: @smallexample func main(...) returns number do set rc getopt($#, vaptr($1), "|help") ... @end smallexample Here, @code{vaptr($1)} constructs the @var{argv} array from all the arguments, supplied to the function @code{main}. To illustrate the use of @code{getopt} function, let's suppose you write a script that takes the following options: @table @option @item -f @var{file} @itemx --file=@var{file} @item --output[=@var{dir}] @item --help @end table Then, the corresponding @code{getopt} invocation will be: @smallexample func main(...) returns number do loop for string rc getopt($#, vaptr($1), "f:|file", "-::|output", "h|help"), while %rc != "", set rc getopt(0, 0) do switch %rc do case "f": set file %optarg case "output" set %output 1 set %output_dir %optarg case "h" help() default: return 1 done ... @end smallexample @node Logging and Debugging @section Logging and Debugging @cindex diagnostics channel @cindex standard error, using for diagnostics output @cindex syslog, using for diagnostics output Depending on its operation mode, @command{mailfromd} tries to guess whether it is appropriate to print its diagnostics and informational messages on standard error or to send them to syslog. By default standard error is used if the program is given one of the database management options (@pxref{Databases}, or @option{--test} option (@pxref{Testing Filter Scripts}. Otherwise, syslog is used. To alter these defaults, two command line options are provided: @option{--stderr} to print everything to standard error and @option{--syslog} to output all diagnostics to syslog. @cindex syslog, default implementation @cindex syslog, non-blocking @cindex syslog, asynchronous @cindex asynchronous syslog @cindex non-blocking syslog @xopindex{syslog-async, introduced} @xopindex{no-syslog-async, introduced} The data can be sent to syslog using two ways: the @code{syslog} function from the system @file{libc} library, which is a @dfn{blocking} implementation in most cases, and the internal, @dfn{asynchronous} syslog implementation. @xref{syslog-async, Using non-blocking syslog}, for more information on these implementations and for information on how to select the default one. Two options are provided to select the implementation to use at run time: the @option{--syslog-async} option instructs @command{mailfromd} to use asynchronous version, and the @option{--no-syslog-async} option instructs it to use the blocking version. @cindex syslog facility, selecting @cindex selecting syslog facility @cindex syslog facility, default @cindex default syslog facility The default syslog facility is @samp{mail}, and it can be changed by @option{--log-facility} option. Argument to this option is a valid syslog facility name, i.e. one of: @samp{user}, @samp{daemon}, @samp{auth}, @samp{authpriv}@footnote{As of mailutils 1.0, @samp{authpriv} is not supported}, @samp{mail}, and @samp{local0} through @samp{local7}. The argument can be given in upper, lower or mixed cases, and it can be prefixed with @samp{log_} @cindex syslog tag @xopindex{log-tag, introduced} Another syslog-related parameter that can be configured is the @dfn{tag} used to identify @command{mailfromd} messages. By default the program name is used. The @option{--log-tag} option can be used to change it. As all @acronym{UNIX} utilities, @command{mailfromd} is very quiet unless it has something important to communicate, for example an error condition or something similar. A set of command line options is provided for controlling the verbosity of its output. @xopindex{trace, introduced} The @option{--trace} option enables tracing the Sendmail actions executed during the message verification. When this option is given, any @code{accept}, @code{discard}, @code{continue}, etc. triggered during the execution of your filter program will leave their traces in the log file. Here is an example of how it looks like (syslog time stamp, tag and @acronym{PID} removed for readability): @smallexample @group k8DHxvO9030656: /etc/mailfromd.rc:45: reject 550 5.1.1 Sender validity not confirmed @end group @end smallexample @noindent This shows that while verifying the message with @acronym{ID} @samp{k8DHxvO9030656} the @code{reject} action was executed by filter script @file{/etc/mailfromd.rc} at line 45. @anchor{Message-ID} @cindex Message-ID, using in @command{mailfromd} logs @cindex Message-ID, exporting The appearance of the message @acronym{ID} in the log deserves a special notice. The program will always identify its log messages with the @samp{Message-Id}, when it is available. Your responsibility as an administrator is to make sure it is available by configuring @code{Sendmail} to export the macro @samp{i} to @command{mailfromd}. The rule of thumb is: make @samp{i} available to the very first handler @command{mailfromd} executes. It is not necessary to export it to the rest of the handlers, since @command{mailfromd} will cache it. For example, if your filter script contains @samp{envfrom} and @samp{envrcpt} handlers, export @samp{i} for @samp{envfrom}. @xref{Sendmail}, for instructions on how to ensure it. @xopindex{debug, introduced} @cindex debugging level @cindex verbosity level To push the log verbosity further, use @code{#pragma option debug} (@pxref{pragma debug}) or its command line equivalent, @option{--debug} (@option{-d}, @pxref{--debug}). It takes a numeric argument specifying the relative verbosity level in the range between 0 and 100. Zero means disabling verbose output, while 100 produces impractically verbose output, suitable only for the developers of @command{mailfromd}. @anchor{debugging level specification} @cindex source modules, setting debugging levels There is a more sophisticated form of the @option{--debug} option, that allows to set debugging levels individually for a set of @dfn{source modules}. In this form, the argument to the option consists of a comma-separated list of @dfn{debug specifications}, each of which has the following form: @code{@var{source}[=@var{level}]}. Here, @var{source} is the @command{mailfromd} source name, without the suffix, and optional @var{level} is the debugging level (an integer between 0 and 100), that you wish to assign to this module. The default level is 100. For example, the following invocation sets the global debugging level to 1, the level for functions from @file{prog.c} to 10, and for @file{engine.c} to 100: @smallexample $ mailfromd --debug=100,prog=10,engine @end smallexample You need to have sufficient knowledge about @command{mailfromd} internal structure to use this form of the @option{--debug} option. @xopindex{transcript, introduced} To control the execution of the sender verification functions (@pxref{Polling functions}), you may use @option{--transcript} (@option{-X}) command line option which enables the transcript of @acronym{SMTP} sessions in the logs. Here is an example of the output produced running @kbd{mailfromd --debug=1 --transcript}: @xopindex{transcript, output example} @smallexample @group k8DHxlCa001774: RECV: 220 spf-jail1.us4.outblaze.com ESMTP Postfix k8DHxlCa001774: SEND: HELO mail.gnu.org.ua k8DHxlCa001774: RECV: 250 spf-jail1.us4.outblaze.com k8DHxlCa001774: SEND: MAIL FROM: <> k8DHxlCa001774: RECV: 250 Ok k8DHxlCa001774: SEND: RCPT TO: k8DHxlCa001774: RECV: 550 <>: No thank you rejected: Account Unavailable: Possible Forgery k8DHxlCa001774: poll exited with status: not_found; sent "RCPT TO: ", got "550 <>: No thank you rejected: Account Unavailable: Possible Forgery" k8DHxlCa001774: SEND: QUIT @end group @end smallexample @node Runtime errors @section Runtime Errors @cindex runtime error A @dfn{runtime error} is a special condition encountered during execution of the filter program, that makes further execution of the program impossible. There are two kinds of runtime errors: fatal errors, and uncaught exceptions. Whenever a runtime error occurs, @command{mailfromd} writes into the log file the following message: @smallexample RUNTIME ERROR near @var{file}:@var{line}: @var{text} @end smallexample @noindent where @var{file}:@var{line} indicates approximate source file location where the error occurred and @var{text} gives the textual description of the error. @subheading Fatal runtime errors @cindex runtime errors, fatal @cindex fatal runtime errors Fatal runtime errors are caused by a condition that is impossible to fix at run time: @table @asis @cindex @samp{Not enough memory}, runtime error @item Not enough memory There is not enough memory for the execution of the program. Try to make more memory available for @command{mailfromd} or to reduce its memory requirements by rewriting your filter script. @cindex @samp{Out of stack space; increase #pragma stacksize}, runtime error @item Out of stack space; increase #pragma stacksize @cindex @samp{Heap overrun; increase #pragma stacksize}, runtime error @itemx Heap overrun; increase #pragma stacksize @cindex @samp{memory chunk too big to fit into heap}, runtime error @itemx memory chunk too big to fit into heap These errors are reported when there is not enough space left on stack to perform the requested operation, and the attempt to resize the stack has failed. Usually @command{mailfromd} expands the stack when the need arises (@pxref{automatic stack resizing}). This runtime error indicates that there were no more memory available for stack expansion. Try to make more memory available for @command{mailfromd} or to reduce its memory requirements by rewriting your filter script. @cindex @samp{Stack underflow}, runtime error @item Stack underflow Program attempted to pop a value off the stack but the stack was already empty. This indicates an internal error in the @acronym{MFL} compiler or @command{mailfromd} runtime engine. If you ever encounter this error, please report it to @email{bug-mailfromd@@gnu.org.ua}. Include the log fragment (about 10-15 lines before and after this log message) and your filter script. @xref{Reporting Bugs}, for more information about bug reporting. @cindex @samp{pc out of range}, runtime error @item pc out of range The @dfn{program counter} is out of allowed range. This is a severe error, indicating an internal inconsistency in @command{mailfromd} runtime engine. If you encounter it, please report it to @email{bug-mailfromd@@gnu.org.ua}. Include the log fragment (about 10-15 lines before and after this log message) and your filter script. @xref{Reporting Bugs}, for more information about how to report a bug. @end table @subheading Programmatic runtime errors These indicate a programmatic error in your filter script, which the @acronym{MFL} compiler was unable to discover at compilation stage: @table @asis @cindex @samp{Invalid exception number}, runtime error @item Invalid exception number: @var{n} The @code{throw} statement used a not existent exception number @var{n}. Fix the statement and restart @command{mailfromd}. @xref{throw}, for the information about @code{throw} statement and see @ref{Exceptions}, for the list of available exception codes. @cindex @samp{No previous regular expression}, runtime error @item No previous regular expression You have used a back-reference (@pxref{Back references}), where there is no previous regular expression to refer to. Fix this line in your code and restart the program. @cindex @samp{Invalid back-reference number}, runtime error @item Invalid back-reference number You have used a back-reference (@pxref{Back references}), with a number greater than the number of available groups in the previous regular expression. For example: @smallexample @group if $f matches "(.*)@@gnu.org" # @r{Wrong: there is only one group in the regexp above!} set x \2 @dots{} @end group @end smallexample Fix your code and restart the daemon. @end table @anchor{uncaught exceptions} @subheading Uncaught exceptions Another kind of runtime errors are @dfn{uncaught exceptions}, i.e. exceptional conditions for which no handler was installed (@xref{Exceptions}, for information on exceptions and on how to handle them). These errors mean that the programmer (i.e. you), made no provision for some specific conditions. For example, consider the following code: @smallexample @group prog envfrom do if $f mx matches "yahoo.com" foo() fi done @end group @end smallexample @noindent It is syntactically correct, but it overlooks the fact that @code{mx matches} generates @code{temp_failure} exception, if the underlying @acronym{DNS} query has timed out (@pxref{Special comparisons}). If this happens, @command{mailfromd} has no instructions on what to do next and reports an error. This can easily be fixed using a @code{catch} statement, e.g.: @smallexample prog envfrom do # @r{Catch @acronym{DNS} errors} catch temp_failure, failure do tempfail 451 4.1.1 "MX verification failed" done if $f mx matches "yahoo.com" foo() fi done @end smallexample Another common case are undefined Sendmail macros. In this case the @code{e_macroundef} exception is generated: @smallexample RUNTIME ERROR near foo.c:34: Macro not defined: @{client_adr@} @end smallexample @noindent These can be caused either by misspelling the macro name (as in the example message above) or by failing to export the required name in Sendmail milter configuration (@pxref{exporting macros}). This error should be fixed either in your source code or in @file{sendmail.cf} file, but if you wish to provide a special handling for it, you can use the following catch statement: @smallexample @group catch macroundef do @dots{} done @end group @end smallexample @anchor{tracing runtime errors} @cindex runtime errors, tracing Sometimes the location indicated with the runtime error message is not enough to trace the origin of the error. For example, an error can be generated explicitly with @code{throw} statement (@pxref{throw}): @smallexample RUNTIME ERROR near match_cidr.mf:30: invalid CIDR (text) @end smallexample If you look in module @file{match_cidr.mf}, you will see the following code (line numbers added for reference): @smallexample 23 func match_cidr(string ipstr, string cidr) returns number 24 do 25 number netmask 26 27 if %cidr matches '^(([0-9]@{1,3@}\.)@{3@}[0-9]@{1,3@})/([0-9][0-9]?)' 28 return inet_aton(%ipstr) & len_to_netmask(\3) = inet_aton(\1) 29 else 30 throw invcidr "invalid CIDR (%cidr)" 31 fi 32 return 0 33 done @end smallexample @xopindex{stack-trace, explained} Now, it is obvious that the value of @code{cidr} argument to @code{match_cidr} was wrong, but how to find the caller that passed the wrong value to it? The special command line option @option{--stack-trace} is provided for this. This option enables dumping @dfn{stack traces} when a fatal error occurs. The traces contain information about function calls. Continuing our example, using the @option{--stack-trace} option you will see the following diagnostics: @smallexample RUNTIME ERROR near match_cidr.mf:30: invalid CIDR (127%) mailfromd: Stack trace: mailfromd: 0077: match_cidr.mf:30: match_cidr mailfromd: 0096: test.mf:13: bar mailfromd: 0110: mailfromd.rc:18: foo mailfromd: Stack trace finishes mailfromd: Execution of the configuration program was not finished @end smallexample @cindex stack traces, reading Each trace line describes one stack frame. The lines appear in the order of most recently called to least recently called. Each frame consists of: @enumerate 1 @item Value of program counter at the time of its execution @item Source code location, if available @item Name of the function called @end enumerate Thus, the example above can be read as: @samp{the function @code{match_cidr} was called by function @code{bar} in file @file{test.mf} at line 13. This function was called from function @code{bar}, in file @file{test.mf} at line 13. In its turn, @code{bar} was called by function @code{foo}, in file @file{mailfromd.rc} at line 18}. Examining the caller functions will help you localize the source of the error and fix it. @cindex @code{stack_trace} function, introduced You can also request a stack trace any place in your code, by calling the @code{stack_trace} function. This can be useful for debugging, or in your @code{catch} statements. @node Cautions @section Warnings about some slippery places in @acronym{MFL} @quotation @i{It seemed like a good idea at the time.}@* Brian Kernighan @end quotation There are some features of @acronym{MFL} which, when used improperly, may lead to subtle, hard identifiable errors. These are: concatenation operation (@pxref{Concatenation}) and passing arguments to one-argument functions without parentheses (@pxref{funcall, Function call syntax}). Since there is no explicit operator for concatenation, it is often necessary to ensure that it happens at the right time by using parentheses to enclose the items to concatenate. Consider the following example: @smallexample echo toupper "some" "thing" @end smallexample Should it print @samp{SOMETHING} or just @samp{SOMEthing}? The correct answer is the former, but it is difficult to deduce unless you are well acquainted with the @acronym{MFL} precedence rules (@pxref{Precedence}). Therefore, the rule of thumb is: whenever in doubt, parenthesize: @smallexample echo toupper("some" "thing") @result{} "SOMETHING" echo toupper("some") "thing" @result{} "SOMEthing" @end smallexample Quoteless literals (@pxref{Literals}) are yet another dangerous feature. Just as the features mentioned above, it stems from the good old days when @acronym{MFL} was small and sweet and using literals without quotes indeed ``seemed a good idea at the time.'' It ceased to seem so after the introduction of user-defined functions, though. Consider the following @emph{entire} program text: @smallexample @group prog envfrom do if hostname($client_addr) = $client_addr reject fi done @end group @end smallexample The intent was obviously to reject any mail that came from an address without a proper @code{PTR} record (@pxref{hostname function}). There is a serious error, however: @code{hostname} is not a built-in function as it used to be in previous releases@footnote{Up to the version 1.3.91.}, and therefore it needs to be defined or required prior to using. Otherwise it is no more than a literal, and the whole construct @samp{hostname($client_addr)} is regarded by @acronym{MFL} compiler as a concatenation of the string @samp{hostname} and the value of @samp{client_addr} Sendmail variable. It is easy to see using the @option{--dump-tree} option: @smallexample $ @kbd{mailfromd --dump-tree test.mf} State handlers: --------------- envfrom: COND: EQ CONCAT: STRING: "hostname" SYMBOL: @{client_addr@} SYMBOL: @{client_addr@} IFTRUE reject IFFALSE @end smallexample In effect, the comparison is always false and @code{reject} is never called. That is why starting from version 3.0 @command{mailfromd} warns about any occurrence of an unquoted identifier. In fact, running @option{--lint} on the above program, gives: @smallexample $ @kbd{mailfromd --lint test.mf} mailfromd: test.mf:3: warning: unquoted identifier `hostname' @end smallexample Whenever you see such a message, be sure to inspect the source and to place quotes around the suspicious string, if it is intended to be used as a literal, or to require the corresponding module (@pxref{Modules}) (or include the source file directly, @pxref{include}), if it is indeed a function name. Another place to execute special caution are format strings used with @code{sprintf} (@pxref{String formatting}) and @code{strftime} (@pxref{strftime}) functions. They use @samp{%} as a character introducing conversion specifiers, while the same character is used to expand a @acronym{MFL} variable within a string. To prevent this misinterpretation, enclose format specification in @emph{single quotes} (@pxref{singe-vs-double}). To illustrate this, let's consider the following example: @smallexample echo sprintf ("Mail from %s", $f) @end smallexample If a variable @code{s} is not declared, this line will produce the @samp{Variable s is not defined} error message, which will allow you to identify and fix the bug. The situation is considerably worse if @code{s} is declared. In that case you will see no warning message, as the statement is perfectly valid, but at the run-time the variable @code{s} will be interpreted within the format string, and its value will replace @code{%s}. To prevent this from happening, single quotes must be used: @smallexample echo sprintf ('Mail from %s', $f) @end smallexample This does not limit the functionality, since there is no need to fall back to variable interpretation in format strings. @anchor{variable--constant clashes} Yet another dangerous feature of the language is the way to refer to variable and constant names within literal strings. To expand a variable or a constant the same notation is used: %@var{name} (@xref{Variables}, and @pxref{Constants}). Now, lets consider the following code: @smallexample const x 2 string x "X" prog envfrom do echo "X is %x" done @end smallexample Does @code{%x} in @code{echo} refers to the variable or to the constant? The correct answer is @samp{to the variable}. When executed this code will print @samp{X is X}. The reason for such a name clash is entirely artificial. Indeed, the following code does not produce any ambiguity: @smallexample const x 2 string x "X" prog envfrom do echo "X is " x done @end smallexample This is because @code{x} alone can refer only to constant. Problems begin when we need to expand a constant in a literal string. The only way to do so is by prefixing its name with a @samp{%}, just as if it were variable, and that produces the ambiguity. As of version @value{VERSION}, @command{mailfromd} will always print a diagnostic message whenever it stumbles upon a variable having the same name as a previously defined constant or vice versa. The resolution of such name clashes is described in detail in @xref{variable--constant shadowing}. Future versions of the program will provide a non-ambiguous way of referring to variables and constants from literal strings. @node MFL @chapter Mail Filtering Language @cindex MFL @cindex mail filtering language The @dfn{mail filtering language}, or @acronym{MFL}, is a special language designed for writing filter scripts. It has a simple syntax, similar to that of Bourne shell. In contrast to the most existing programming languages, @acronym{MFL} does not have any special terminating or separating characters (like, e.g. newlines and semicolons in shell). All syntactical entities are separated by any amount of white-space characters (i.e. spaces, tabulations or newlines). The following sections describe @acronym{MFL} syntax in detail. @menu * Comments:: Usual and pragmatic comments. * Data Types:: * Numbers:: * Literals:: * Here Documents:: * Sendmail Macros:: * Constants:: * Variables:: * Back references:: * Handlers:: * begin/end:: * Functions:: Functions. * Expressions:: Expressions. * Shadowing:: Variable and Constant Shadowing. * Statements:: * Conditionals:: Conditional Statements. * Loops:: Loop Statements. * Exceptions:: Exceptional Conditions and their Handling. * Polling:: Sender Verification Tests. * Modules:: Modules are Collections of Useful Functions. * Preprocessor:: Input Text Is Preprocessed. * Filter Script Example:: A Working Filter Script Explained. * Reserved Words:: A Reference List of Reserved Words. @end menu @node Comments @section Comments @cindex comments Two types of comments are allowed: @sc{c}-style, enclosed between @samp{/*} and @samp{*/}, and shell-style, starting with @samp{#} character and extending up to the end of line: @smallexample @group /* This is a comment. */ # And this too. @end group @end smallexample There are, however, several special cases, where the characters following @samp{#} are not ignored. @anchor{include} @cindex #include statement @cindex including files @kwindex #include If @samp{#} is followed by word @samp{include} (with optional whitespace between them), this statement requires inclusion of the specified file, as in @sc{c}. There are two forms of the @samp{#include} statement: @enumerate 1 @item @code{#include <@var{file}>} @item @code{#include "@var{file}"} @end enumerate The quotes around @var{file} in the second form quotes are optional. @anchor{include search path} @cindex include search path, introduced Both forms are equivalent if @var{file} is an absolute file name. Otherwise, the first form will look for @var{file} in the @dfn{include search path}. The second one will look for it in the current working directory first, and, if not found there, in the include search path. The default include search path is: @enumerate 1 @item @file{@var{prefix}/share/mailfromd/@value{VERSION}/include} @item @file{@var{prefix}/share/mailfromd/include} @item @file{/usr/share/mailfromd/include} @item @file{/usr/local/share/mailfromd/include} @noindent Where @var{prefix} is the installation prefix. @end enumerate New directories can be appended in front of it using @option{-I} (@option{--include}) command line option. For example, invoking @smallexample $ @kbd{mailfromd -I/var/mailfromd -I/com/mailfromd} @end smallexample @noindent creates the following include search path @enumerate 1 @item @file{/var/mailfromd} @item @file{/com/mailfromd} @item @file{@var{prefix}/share/mailfromd/@value{VERSION}/include} @item @file{@var{prefix}/share/mailfromd/include} @item @file{/usr/share/mailfromd/include} @item @file{/usr/local/share/mailfromd/include} @end enumerate @anchor{include_once} @cindex include_once Along with @code{#include}, there is also a special form @code{#include_once}, that has the same syntax: @smallexample #include_once <@var{file}> #include_once "@var{file}" @end smallexample This form works exactly as @code{#include}, except that, if the @var{file} has already been included, it will not be included again. As the name suggests, it will be included only once. This form should be used to prevent re-inclusions of a code, which can cause problems due to function redefinitions, variable reassignments etc. @anchor{require} @kwindex require @cindex #require statement Another special construct is @code{#require}. It instructs the compiler, that the code below requires functions from the @dfn{module} given as an argument to this statement: @smallexample #require @var{module} @end smallexample Modules are @acronym{MFL} source files that contain a collection of code and data serving a special purpose. They are named @file{@var{modname}.mf} and placed in one of the directories comprising the include path (@pxref{include search path}). The @code{#require} statement looks up the named module in the path and attempts to compile it. If the module does not exist, a syntax error is reported. It is not an error to require the same module several times. After the first successful load, subsequent @code{#require} statements with the same @var{modname} will be ignored. In this regard, this statement is similar to @code{#include_once}. You will find more information regarding @acronym{MFL} modules in @xref{Modules}. @anchor{line} @cindex line, @code{#line} statement @kwindex #line A line in the form @smallexample #line @var{number} "@var{identifier}" @end smallexample @noindent causes the @acronym{MFL} compiler to believe, for purposes of error diagnostics, that the line number of the next source line is given by @var{number} and the current input file is named by @var{identifier}. If the identifier is absent, the remembered file name does not change. @anchor{Pragmatic comments} @cindex pragmatic comments @cindex #pragma statement @kwindex #pragma If @samp{#} is immediately followed by word @samp{pragma} (with optional whitespace between them), such a construct introduces a @dfn{pragmatic comment}, i.e. an instruction that controls some configuration setting. Following types of pragmatic comments are currently implemented: @samp{#pragma option} changes a value of a run-time option, @samp{#pragma database} configures database settings, @samp{#pragma stacksize} sets the initial stack size, and @samp{#pragma regex} controls the compilation of regular expressions. These pragma types are described in the following subsections. @menu * option:: Pragma option. * database:: Pragma database. * stacksize:: Pragma stacksize. * regex:: Pragma regex. * dbprop:: Pragma dbprop. * greylist:: Pragma greylist. @end menu @node option @subsection Pragma option @cindex option, pragma @cindex #pragma option The syntax of @samp{#pragma option} is: @smallexample #pragma option @var{name} @var{value} @end smallexample @noindent where @var{name} is the name of the command line option (without leading dashes) to set, and @var{value} is its new value. The effect of this statement is the same as that of the command line option @samp{--@var{name}=@var{value}}. The @var{value} is specific for each particular option. The supported value types are: @table @asis @item number A decimal number. @item string A string of characters. It must be enclosed in a pair of quotes, if it contains whitespace characters (use either single or double quotes, at your option). @item boolean A boolean value: @code{yes}, @code{true} or @code{t} to indicate a true value, and @code{no}, @code{false} or @code{nil} to indicate a false value. @item address An @acronym{IP} address in ``dotted-quad'' notation or a fully-qualified host name. @item interval @cindex time Interval Specification @anchor{time interval specification} The @dfn{time interval specification} is a string that defines an interval, much the same way we do this in English: it consists of one or more pairs @samp{number}-@samp{time unit}. For example, the following are valid interval specifications: @smallexample @group 1 hour 2 hours 35 seconds 1 year 7 months 2 weeks 2 days 11 hours 12 seconds @end group @end smallexample @noindent The pairs can occur in any order, however unusual it may sound to a human ear, e.g. @samp{2 days 1 year}. If the @samp{time unit} is omitted, seconds are supposed. When used in a @samp{#pragma option} statement, interval values need not be quoted. @end table @noindent The following options control various database expiration intervals. The use of these options is deprecated, please use the corresponding @code{#pragma database} option. @deffn {pragma option} expire-interval interval @xprindex{expire-interval} Sets expiration interval for all databases. @end deffn @deffn {pragma option} positive-expire-interval interval @xprindex{positive-expire-interval} Sets expiration interval for positive cache entries. Use @code{#pragma database cache positive-expire-interval} instead. @end deffn @deffn {pragma option} negative-expire-interval interval @xprindex{negative-expire-interval} Sets expiration interval for negative cache entries. Use @code{#pragma database cache negative-expire-interval} instead. @end deffn @deffn {pragma option} rates-expire-interval interval @xprindex{rates-expire-interval} Sets expiration interval for entries in the rates database. Use @code{#pragma database rate expire-interval} instead. @end deffn @noindent The following options control @acronym{I/O} operations over @acronym{TCP}. @deffn {pragma option} source address @xprindex{source} Sets source address for @acronym{TCP} connections. @end deffn @deffn {pragma option} connect-timeout interval @xprindex{connect-timeout} Sets initial connection timeout. If the connection is not established within this time, the corresponding probing function returns temporary failure. The default value is @value{CONNECT-TIMEOUT}. @xref{SMTP Timeouts}, for a detailed description. @end deffn @deffn {pragma option} initial-response-timeout interval @xprindex{initial-response-timeout} Sets the time to wait for the initial @acronym{SMTP} response. Default is @value{INITIAL-RESPONSE-TIMEOUT}. @xref{SMTP Timeouts}, for the detailed description. @end deffn @deffn {pragma option} io-timeout interval @deffnx {pragma option} timeout interval @xprindex{io-timeout} @xprindex{timeout} Sets @acronym{I/O} operation timeout in seconds. @command{Mailfromd} will wait the given amount of time for the success of each @acronym{I/O} operation with the remote @acronym{MX}. Default timeout is @value{IO-TIMEOUT}. @xref{SMTP Timeouts}, for a detailed description. The form @code{timeout} is retained for backward compatibility and is considered deprecated. @end deffn @ignore ------------------------------------------------------------------------ -- This is to pacify make check-docs. -- These options are reserved for future use @opindex load @opindex load-dir ------------------------------------------------------------------------ @end ignore @noindent The following options provide the default settings for @code{poll} statement (@pxref{Polling}). @deffn {pragma option} mailfrom string @xprindex{mailfrom} Sets default email addresses used in @samp{MAIL FROM:} @acronym{SMTP} command when probing the remote host. This value can be overridden by @samp{as} parameter to @command{poll} command (@pxref{poll}). This pragma is deprecated (@pxref{31x-400}). Instead of it, use assignment to @code{mailfrom_address} variable: @smallexample set mailfrom_address @var{string} @end smallexample @xref{mailfrom_address}, for more information about it. @end deffn @deffn {pragma option} ehlo string @xprindex{ehlo} Sets default domain used in @samp{EHLO} (or @samp{HELO}) @acronym{SMTP} command when probing the remote host. This value can be overridden by @samp{from} parameter to @command{poll} command (@pxref{poll}). This pragma is deprecated (@pxref{31x-400}). Instead of it, use assignment to @code{ehlo_domain} variable: @smallexample set ehlo_domain @var{string} @end smallexample @xref{ehlo_domain}, for more information about it. @end deffn @noindent The following options control debugging and logging facilities: @deffn {pragma option} debug string @xprindex{debug} Sets debugging level. @var{String} is a decimal number in the range 0 -- 100. Level 0 effectively disables debugging, while level 100 enables the most verbose debugging output. You can also selectively set different debug levels for different source code modules. In this case @var{string} is a comma-separated list of debug specifications, each of which has the following syntax: @code{@var{module}[=@var{level}]}. @xref{Logging and Debugging}, for the detailed description of this. @end deffn @deffn {pragma option} source-info boolean @xprindex{source-info} When used together with @code{#pragma option debug}, this option includes source information into the debugging output. Use this for debugging @command{mailfromd}. @end deffn @deffn {pragma option} stack-trace boolean @xprindex{stack-trace} Enables dumping stack traces on runtime errors. This feature is useful for locating the source of an error, especially in complex scripts. @xref{tracing runtime errors}, for a detailed description. @end deffn @noindent These options control program privileges after startup: @deffn {pragma option} user string @xprindex{user} Switch to this user's privileges after startup. @xref{Starting and Stopping}, for a discussion of the privileges @command{mailfromd} runs under and the options that affect them. See also @code{group} below. @end deffn @deffn {pragma option} group string @xprindex{group} Retain the supplementary group @var{string} when switching to user privileges. By default @command{mailfromd} clears the list of supplementary groups when switching to user privileges, but this option allows to retain the given group. It can be specified multiple times to retain several groups. Use of this option can be necessary to maintain proper access rights for various files. @xref{Starting and Stopping}. @end deffn @noindent The following options control interaction with @command{Sendmail}: @deffn {pragma option} port string @xprindex{port} Sets the communication port data. Valid formats for @var{string} are: @anchor{milter port specification} @table @asis @item unix://@var{file} @itemx unix:@var{file} @itemx local://@var{file} @itemx local:@var{file} A named pipe (socket). @item inet://@var{address}:@var{port} @itemx inet:@var{port}@@@var{address} An @acronym{IP}v4 connection to host @var{address} at port @var{port}. Port must be specified either as a decimal number or a string representing the port name in @file{/etc/services}. @item inet6:@var{port}@@@var{address} An @acronym{IP}v6 connection to host @var{address} at port @var{port}. This port type is not yet supported. @end table @end deffn @deffn {pragma option} milter-timeout interval @xprindex{milter-timeout} Set the timeout value for connection between the filter and the @acronym{MTA}. Default value is @value{MILTER-TIMEOUT}. You normally do not need to change this value. @end deffn @noindent The following options are used to tune database file locking: @deffn {pragma option} lock-retry-count number @xprindex{lock-retry-count} Set maximum number of attempts to acquire the lock. The time between each two successive attempts is given by @code{lock-retry-timeout} pragma (see below). After the @var{number} of failed attempts, @command{mailfromd} gives up. @end deffn @deffn {pragma option} lock-retry-timeout interval @xprindex{lock-retry-timeout} Set the time span between the two locking attempts. @end deffn @noindent Other options: @deffn {pragma option} relay string @xprindex{relay} Specifies the file containing names of email domains, relayed by this machine. Multiple pragmas accumulate. The constructed list of domains is analyzed by @code{relayed} function (@pxref{relayed}). For example: @smallexample #pragma option relay "/etc/mail/sendmail.cw" #pragma option relay "/etc/mail/relay-domains" @end smallexample @end deffn @deffn {pragma option} state-directory string @xprindex{state-directory} Changes the file name of the program state directory. @smallexample #pragma option state-directory "/var/run/mailfromd" @end smallexample @end deffn @deffn {pragma option} pidfile string @xprindex{pidfile} Introduces the full name of a file where @command{mailfromd} will store its @acronym{PID} number. The file must be writable for the user @command{mailfromd} runs as (@pxref{pragma user}). @end deffn @node database @subsection Pragma database @cindex database, pragma @cindex #pragma database The @code{#pragma database} statement is used to control file names and expiration periods used for various @acronym{DBM} databases. Its syntax is: @table @code @item #pragma database @var{dbname} file @var{filename} Set the database file name for the database @var{dbname}. @item #pragma database @var{dbname} expire-interval @var{interval} Set the expiration interval for the database @var{dbname}. (@xref{time interval specification}, for more information on @var{interval} syntax). @end table The parameter @var{dbname} can be one of the following: @samp{cache}, @samp{dns}, @samp{rate} and @samp{greylist} for main cache, @acronym{DNS} lookup, sending rate and greylisting databases, correspondingly. The first two databases merit special attention. The cache database implements two different timeouts, therefore there are two special forms of this statement for @samp{cache} database: @table @code @item #pragma database cache positive-expire-interval @var{interval} Set expiration interval for positive (@samp{success}) cache entries. @item #pragma database cache negative-expire-interval @var{interval} Set expiration interval for negative (@samp{not_found}) cache entries. @end table The @acronym{DNS} lookup cache uses @acronym{DNS} @acronym{TTL} as expiration interval for records representing positive lookups. The only value that can be altered is negative expiration interval: @table @code @item #pragma database dns negative-expire-interval @var{interval} Set expiration interval for negative @acronym{DNS} cache entries. @end table @xref{DNS Cache Management}, for more information of @acronym{DNS} cache database and its management. @node stacksize @subsection Pragma stacksize @cindex stacksize, pragma @cindex #pragma stacksize @subheading Syntax @smallexample #pragma stacksize @var{size} #pragma stacksize @var{size} twice|@var{incr} #pragma stacksize @var{size} twice|@var{incr} @var{max} @end smallexample @subheading Description The @code{stacksize} pragma sets the initial size of the run-time stack size and may also define the policy of its growing, in case it becomes full. It takes one mandatory and two optional arguments. The first argument gives the desired initial stack size, in words. It defaults to @value{STACK-SIZE}. You may wish to increase this number if your configuration program uses recursive functions or does an excessive amount of string manipulations. For example: @smallexample #pragma stacksize 7168 @end smallexample You may use usual size suffixes: @multitable @columnfractions 0.3 0.6 @headitem Suffix @tab Meaning @item k @tab Kiloword, i.e. 1024 words @item m @tab Megawords, i.e. 1048576 words @item g @tab Gigawords, @item t @tab Terawords (ouch!) @end multitable File suffixes are case-insensitive: @smallexample @group #pragma stacksize 7m #pragma stacksize 7M @end group @end smallexample @anchor{automatic stack resizing} When the @acronym{MFL} engine notices that there is no more stack space available, it attempts to expand the stack. If this attempt succeeds, the operation continues. Otherwise, a runtime error is reported and the execution of the filter stops. @cindex stack growth policy @cindex growth policy, stack Optional second argument to @code{#pragma stacksize} defines growth policy for the stack. A positive number in its place is taken for the @dfn{expansion chunk} size. In this case, the stack will be grown in blocks that contain integer number of expansion chunks. The following example sets initial stack size to 10240, and expansion chunk size to 2048 words: @smallexample #pragma stacksize 10M 2M @end smallexample This @dfn{incremental growth policy} is the default. The default chunk size is @value{STACK-INCR}. The word @samp{twice} used as second argument enables @dfn{exponential stack growth} policy: @smallexample #pragma stacksize 10240 twice @end smallexample In this case, when the run-time evaluator hits the stack size limit, it expands the stack to twice the size it had before. So, in the example above, the stack will be sequentially expanded to the following sizes: 20480, 40960, 81920, 163840. Third argument to @code{#pragma stacksize} defines maximum size of the stack. If stack grows beyond this limit, the execution of the script will be aborted. If you are concerned about the execution time of your script, you may wish to avoid stack reallocations. To help you find out the optimal stack size, each time the stack is expanded, @command{mailfromd} issues a warning in its log file, which looks like this: @smallexample warning: stack segment expanded, new size=8192 @end smallexample You can use these messages to adjust your stack size configuration settings. @node regex @subsection Pragma regex @cindex regex, pragma @cindex #pragma regex @anchor{pragma regex} Another pragmatic comment, @samp{#pragma regex}, controls compilation of expressions. You can use any number of such pragma directives in your @file{mailfromd.rc}. The scope of @samp{#pragma regex} extends to the next occurrence of this directive or to the end of the script file, whichever occurs first. The syntax of this pragma is: @smallexample #pragma regex [push|pop] [@var{list-of-flags}] @end smallexample @noindent where @code{push} and @code{pop} are optional sub-commands discussed in detail below, and @var{list-of-flags} is a whitespace-separated list of @dfn{regex flags}. Each regex-flag is a word specifying some regex feature. It can be preceded by @samp{+} to enable this feature (this is the default), by @samp{-} to disable it or by @samp{=} to reset regex flags to its value. Valid regex-flags are: @table @samp @item extended Use @acronym{POSIX} Extended Regular Expression syntax when interpreting regex. If not set, @acronym{POSIX} Basic Regular Expression syntax is used. @item icase Do not differentiate case. Subsequent regex searches will be case insensitive. @item newline @dfn{Match-any-character} operators don't match a newline. A non-matching list (@samp{[^...]}) not containing a newline does not match a newline. @dfn{Match-beginning-of-line} operator (@samp{^}) matches the empty string immediately after a newline. @dfn{Match-end-of-line} operator (@samp{$}) matches the empty string immediately before a newline. @end table For example, the following pragma enables @acronym{POSIX} extended, case insensitive matching (a good thing to start your @file{mailfromd.rc} with): @smallexample #pragma regex +extended +icase @end smallexample Optional modifiers @code{push} and @code{pop} can be used to maintain a stack of regex flags. The statement @smallexample #pragma regex push [@var{flags}] @end smallexample @noindent saves current regex flags on stack and then optionally modifies them as requested by @var{flags}. The statement @smallexample #pragma regex pop [@var{flags}] @end smallexample @noindent does the opposite: restores the current regex flags from the top of stack and applies @var{flags} to it. This statement is useful in include files to avoid disturbing user regex settings. E.g.: @smallexample @group #pragma regex push +extended +icase . . . #pragma regex pop @end group @end smallexample @node dbprop @subsection Pragma dbprop @cindex dbprop, pragma @cindex #pragma dbprop @smallexample #pragma dbprop @var{pattern} @var{prop} [@var{prop}] @end smallexample This pragma configures properties for a @acronym{DBM} database. @xref{Database functions}, for its detailed description. @node greylist @subsection Pragma greylist @cindex greylist, pragma @cindex #pragma greylist @smallexample #pragma greylist @var{type} @end smallexample This pragma selects the greylisting implementation to use. Allowed values for @var{type} are: @table @asis @item traditional @itemx gray Use the traditional greylisting implementation. This is the default. @item con-tassios @itemx ct Use Con Tassios greylisting implementation. @end table @xref{greylisting types}, for a detailed description of available greylisting implementations. Notice, that this pragma can be used only once. Second use of this pragma constitutes an error, because you cannot use both greylisting implementations in the same program. @node Data Types @section Data Types The @command{mailfromd} filter script language operates on entities of two types: numeric and string. The @dfn{numeric} type is represented internally as a signed long integer. Depending on the machine architecture, its size can vary. For example, on machines with Intel-based @acronym{CPU}s it is 32 bits long. A @dfn{string} is a string of characters of arbitrary length. Strings can contain any characters except @acronym{ASCII} @sc{nul}. There is also a @dfn{generic pointer}, which is designed to facilitate certain operations. It appears only in @code{body} handler. @xref{body handler}, for more information about it. @node Numbers @section Numbers A @dfn{decimal number} is any sequence of decimal digits, not beginning with @samp{0}. An @dfn{octal number} is @samp{0} followed by any number of octal digits (@samp{0} through @samp{7}), for example: @code{0340}. A @dfn{hex number} is @samp{0x} or @samp{0X} followed by any number of hex digits (@samp{0} through @samp{9} and @samp{a} through @samp{f} or @samp{A} through @samp{F}), for example: @code{0x3ef1}. @node Literals @section Literals @cindex literals A literal is any sequence of alpha-numeric characters that is not a reserved word (@pxref{Reserved Words}), or any sequence of characters enclosed in double or single quotation marks. Literals consisting of only numeric characters represent integer numbers and were discussed in the previous section. Quoted literals and literals beginning with a letter or underscore represent strings. After @code{tempfail} and @code{reject} actions two special kinds of literals are recognized: three-digit numeric values represent @acronym{RFC} 2821 reply codes, and literals consisting of tree digit groups separated by dots represent an extended reply code as per @acronym{RFC} 1893/2034. For example: @smallexample @group 510 # @r{A reply code} 5.7.1 # @r{An extended reply code} @end group @end smallexample @anchor{Double-quoted strings} @subheading Double-quoted strings String literals enclosed in double quotation marks (@dfn{double-quoted strings}) are subject to @dfn{backslash interpretation}, @dfn{macro expansion}, @dfn{variable interpretation} and @dfn{back reference interpretation}. @cindex backslash interpretation @dfn{Backslash interpretation} is performed at compilation time. It consists in replacing the following @dfn{escape sequences} with the corresponding single characters: @float Table, backslash-interpretation @caption{Backslash escapes} @multitable @columnfractions 0.30 .5 @item Sequence @tab Replaced with @item \a @tab Audible bell character (@acronym{ASCII} 7) @item \b @tab Backspace character (@acronym{ASCII} 8) @item \f @tab Form-feed character (@acronym{ASCII} 12) @item \n @tab Newline character (@acronym{ASCII} 10) @item \r @tab Carriage return character (@acronym{ASCII} 13) @item \t @tab Horizontal tabulation character (@acronym{ASCII} 9) @item \v @tab Vertical tabulation character (@acronym{ASCII} 11) @end multitable @end float In addition, the sequence @samp{\@var{newline}} has the same effect as @samp{\n}, for example: @smallexample @group "a string with\ embedded newline" "a string with\n embedded newline" @end group @end smallexample Any escape sequence of the form @samp{\x@var{hh}}, where @var{h} denotes any hex digit is replaced with the character whose @acronym{ASCII} value is @var{hh}. For example: @smallexample "\x61nother" @result{} "another" @end smallexample Similarly, an escape sequence of the form @samp{\0@var{ooo}}, where @var{o} is an octal digit, is replaced with the character whose @acronym{ASCII} value is @var{ooo}. @cindex variable interpretation @cindex macro expansion Macro expansion and variable interpretation occur at run-time. During these phases all Sendmail macros (@pxref{Sendmail Macros}), @command{mailfromd} variables (@pxref{Variables}), and constants (@pxref{Constants}) referenced in the string are replaced by their actual values. For example, if the Sendmail macro @code{f} has the value @samp{postmaster@@gnu.org.ua} and the variable @code{last_ip} has the value @samp{127.0.0.1}, then the string@footnote{Implementation note: actually, the references are not interpreted within the string, instead, each such string is split at compilation time into a series of concatenated atoms. Thus, our sample string will actually be compiled as: @smallexample $f " last connected from " %last_ip ";" @end smallexample @xref{Concatenation}, for a description of this construct. You can easily see how various strings are interpreted by using @option{--dump-tree} option (@pxref{--dump-tree}). For our sample string it will produce: @smallexample CONCAT: CONCAT: CONCAT: SYMBOL: f CONSTANT: " last connected from " VARIABLE last_ip (13) CONSTANT: ";" @end smallexample } @smallexample "$f last connected from %last_ip;" @end smallexample @noindent will be expanded to @smallexample "postmaster@@gnu.org.ua last connected from 127.0.0.1;" @end smallexample @cindex back reference interpretation A @dfn{back reference} is a sequence @samp{\@var{d}}, where @var{d} is a decimal number. It refers to the @var{d}th parenthesized subexpression in the last @command{matches} statement@footnote{The subexpressions are numbered by the positions of their opening parentheses, left to right.}. Any back reference occurring within a double-quoted string is replaced by the value of the corresponding subexpression. @xref{Special comparisons}, for a detailed description of this process. Back reference interpretation is performed at run time. @anchor{singe-vs-double} @subheading Single-quoted strings The characters enclosed in single quotation marks are read unmodified. The following examples contain pairs of equivalent strings: @smallexample @group "a string" 'a string' "\\(.*\\):" '\(.*\):' @end group @end smallexample Notice the last example. Single quotes are particularly useful in writing regular expressions (@pxref{Special comparisons}). Notice also, that although unquoted literals are allowed, their use is not encouraged, since they create syntactic ambiguities that can make discovering real syntax errors difficult. @xref{Cautions}. Therefore @command{mailfromd} will always warn about such literals. @node Here Documents @section Here Documents @cindex here document @cindex multiline strings @dfn{Here-document} is a special form of a string literal is, allowing to specify multiline strings without having to use backslash escapes. The format of here-documents is: @smallexample @group <<[@var{flags}]@var{word} @dots{} @var{word} @end group @end smallexample The @code{<<@var{word}} construct instructs the parser to read all the following lines up to the line containing only @var{word}, with possible trailing blanks. The lines thus read are concatenated together into a single string. For example: @smallexample @group set str < has tried to send %count mails. Please see docs for more info. EOT @end group @end smallexample @noindent will be expanded to: @smallexample @group has tried to send 10 mails. Please see docs for more info. @end group @end smallexample If the @var{word} is quoted, either by enclosing it in single quote characters or by prepending it with a backslash, all interpretations and expansions within the document body are suppressed. For example: @smallexample @group set s <<'EOT' The following line is read verbatim: <$f> has tried to send %count mails. Please see docs for more info. EOT @end group @end smallexample Optional @var{flags} in the here-document construct control the way leading white space is handled. If @var{flags} is @code{-} (a dash), then all leading tab characters are stripped from input lines and the line containing @var{word}. Furthermore, if @code{-} is followed by a single space, all leading whitespace is stripped from them. This allows here-documents within configuration scripts to be indented in a natural fashion. Examples: @smallexample @group <<- TEXT <$f> has tried to send %count mails. Please see docs for more info. TEXT @end group @end smallexample Here-documents are particularly useful with @code{reject} actions (@pxref{reject}. @node Sendmail Macros @section Sendmail Macros @cindex macros, referencing @cindex Sendmail macros, referencing Sendmail macros are referenced exactly the same way they are in @file{sendmail.cf} configuration file, i.e. @samp{$@var{name}}, where @var{name} represents the macro name. Notice, that the notation is the same for both single-character and multi-character macro names. For consistency with the @command{Sendmail} configuration the @samp{$@{@var{name}@}} notation is also accepted. Another way to reference Sendmail macros is using function @code{getmacro} (@pxref{Macro access}). Sendmail macros evaluate to string values. Notice, that to reference a macro, you must properly export it in @file{sendmail.cf} using @code{Milter.macros} statement (@pxref{Sendmail}). Attempt to reference a not exported macro will result in raising a @code{e_macroundef} exception at the run time (@pxref{uncaught exceptions}). @node Constants @section Constants @cindex constants, defining @cindex const A @dfn{constant} is a symbolic name for an @acronym{MFL} value. Constants are defined using @code{const} statement: @smallexample const @var{name} @var{expr} @end smallexample @noindent where @var{name} is an identifier, and @var{expr} is any valid @acronym{MFL} expression evaluating immediately to a constant literal or numeric value. @cindex constants, using in program text After defining, any appearance of @var{name} in the program text is replaced by its value. For example: @smallexample const x 10/5 const text "X is " @end smallexample @noindent defines the numeric constant @samp{x} with the value @samp{5}, and the literal constant @samp{text} with the value @samp{X is }. @cindex constants, using in literals Constants can also be used in literals. To expand a constant within a literal string, prepend a percent sign to its name, e.g.: @smallexample echo "New %text %x" @result{} "New X is 2" @end smallexample This way of expanding constants creates an ambiguity if there happen to be a variable of the same name as the constant. @xref{variable--constant clashes}, for more information of this case and ways to handle it. @menu * Built-in constants:: @end menu @node Built-in constants @subsection Built-in constants @cindex built-in constants @cindex constants, built-in Several constants are built into the @acronym{MFL} compiler@footnote{In @command{mailfromd} versions prior to 1.3.91, they were called @dfn{macros}.}. To discern them from user-defined ones, their names start and end with two underscores (@samp{__}). The following constants are defined in @command{mailfromd} version @value{VERSION}: @deftypevr {Built-in constant} string __file__ Expands to the name of the current source file. @end deftypevr @deftypevr {Built-in constant} string __function__ Expands to the name of the current lexical context, i.e. the function or handler name. @end deftypevr @deftypevr {Built-in constant} number __line__ Expands to the current line number in the input source file. @end deftypevr @deftypevr {Built-in constant} number __major__ Expands to the major version number. The following example uses @code{__major__} constant to determine if some version-dependent feature can be used: @smallexample @group if __major__ > 2 # @r{Use some version-specific feature} fi @end group @end smallexample @end deftypevr @deftypevr {Built-in constant} number __minor__ Expands to the minor version number. @end deftypevr @deftypevr {Built-in constant} string __package__ Expands to the package name (@samp{mailfromd}) @end deftypevr @deftypevr {Built-in constant} number __patch__ For alpha versions and maintenance releases expands to the version patch level. For stable versions, expands to @samp{0}. @end deftypevr @deftypevr {Built-in constant} string __defpreproc__ Expands to the default external preprocessor command line, if the preprocessor is used, or to an empty string if it is not, e.g.: @smallexample __defpreproc__ @result{} "/usr/bin/m4 -s" @end smallexample @xref{Preprocessor}, for information on preprocessor and its features. @end deftypevr @deftypevr {Built-in constant} string __preproc__ Expands to the current external preprocessor command line, if the preprocessor is used, or to an empty string if it is not. Notice, that it equals @code{__defpreproc__}, unless the preprocessor was redefined using @option{--preprocessor} command line option (@pxref{Preprocessor, --preprocessor}). @end deftypevr @deftypevr {Built-in constant} string __version__ Expands to the textual representation of the program version (e.g. @samp{3.0.90}) @end deftypevr @deftypevr {Built-in constant} string __defstatedir__ Expands to the default state directory (@pxref{statedir}). @end deftypevr @deftypevr {Built-in constant} string __statedir__ Expands to the current value of the program state directory (@pxref{statedir}). Notice, that it is the same as @code{__defstatedir__} unless the state directory was redefined at run time. @end deftypevr Built-in constants can be used as variables, this allows to expand them within strings or here-documents. The following example illustrates the common practice used for debugging configuration scripts: @smallexample @group func foo(number x) do echo "%__file__:%__line__: foo called with arg %x" @dots{} done @end group @end smallexample If the function @code{foo} were called in line 28 of the script file @code{/etc/mailfromd.rc}, like this: @code{foo(10)}, you will see the following string in your logs: @smallexample /etc/mailfromd.rc:28: foo called with arg 10 @end smallexample @node Variables @section Variables @cindex variables, defined Variables represent regions of memory used to hold variable data. These memory regions are identified by @dfn{variable names}. A variable name must begin with a letter or underscore and must consist of letters, digits and underscores. Each variable is associated with its @dfn{lexical scope}, i.e. the part of source code where it can be used. Depending on the scope we discern two main classes of variables: global and automatic ones. @dfn{Global variables} have indefinite lexical scope, so they may be referred to anywhere in the program. @dfn{Automatic} or @dfn{local variables} are visible only within the given function or handler. The two variable classes occupy separate @dfn{namespaces}, so that an automatic variable can have the same name as an existing global one. In this case this variable is said to @dfn{shadow} its global counterpart. All references to such a name will refer to the automatic variable until the end of its scope is reached, where the global one becomes visible again. @cindex variables, declaring @cindex variable declarations A variable is @dfn{declared} using the following syntax: @smallexample @var{type} @var{name} @end smallexample @noindent where @var{name} is the variable name and @var{type} is the type of the data it is supposed to hold. It is @samp{string} for string variables and @samp{number} for numeric ones. If a variable declaration occurs within a function (@pxref{Functions,User-defined}) or handler (@pxref{Handlers}), it declares an automatic variable, local to this function or handler. Otherwise, it declares a global variable. @cindex variable, assigning a value @cindex variable assignment @kwindex set A variable is assigned a value using @code{set} statement: @smallexample set @var{name} @var{expr} @end smallexample @noindent where @var{name} is the variable name and @var{expr} is a @command{mailfromd} expression (@pxref{Expressions}). The effect of this statement is that the @var{expr} is evaluated and the value it yields is assigned to the variable @var{name}. If the @code{set} statement is located outside a function or handler definition, the @var{expr} must be a constant expression, i.e. the compiler should be able to evaluate it immediately. @FIXME-xref{optimizer} It is not an error to assign a value to a variable that is not declared. In this case the assignment first declares a global or automatic variable having the type of @var{expr} and then assigns a value to it. Automatic variable is created if the assignment occurs within a function or handler, global variable is declared if it occurs at topmost lexical level. This is called @dfn{implicit variable declaration}.@footnote{Notice, that this differs from the way variables were handled in versions up to 3.0.2, which declared all variables as global.} @cindex variables, referencing Variables are referenced using the notation @samp{%@var{name}}. The variable being referenced must have been declared earlier (either explicitly or implicitly). @menu * Predefined variables:: @end menu @node Predefined variables @subsection Predefined Variables @cindex predefined variables @cindex variables, predefined Several variables are predefined. In @command{mailfromd} version @value{VERSION} these are: @deftypevar {Predefined Variable} number cache_used This variable is set by @code{stdpoll} and @code{strictpoll} built-ins (and, consequently, by the @code{on poll} statement). Its value is @samp{1} if the function used the cached data instead of directly polling the host, and @samp{0} if the polling took place. @xref{Polling functions}. @anchor{cache_used example} @cindex @code{cache_used} variable, usage example @cindex reject messages, marking cached rejects You can use this variable to make your reject message more informative for the remote party. The common paradigm is to define a function, returning empty string if the result was obtained from polling, or some notice if cached data were used, and to use the function in the @code{reject} text, for example: @smallexample @group func cachestr() returns string do if %cache_used return "[CACHED] " else return "" fi done @end group @end smallexample @noindent Then, in @code{prog envfrom} one can use: @smallexample @group on poll $f do when not_found or failure: reject 550 5.1.0 cachestr() "Sender validity not confirmed" done @end group @end smallexample @end deftypevar @deftypevr {Predefined Variable} string clamav_virus_name Name of virus identified by @command{ClamAV}. Set by @code{clamav} function (@pxref{ClamAV}). @end deftypevr @deftypevr {Predefined Variable} number greylist_seconds_left Number of seconds left to the end of greylisting period. Set by @code{greylist} function (@pxref{Special test functions}). @end deftypevr @anchor{ehlo_domain} @deftypevr {Predefined Variable} string ehlo_domain Name of the domain used by polling functions in @acronym{SMTP} @code{EHLO} or @code{HELO} command. Default value is the fully qualified domain name of the host where @command{mailfromd} is run. @xref{Polling}. @end deftypevr @deftypevar {Predefined Variable} string last_poll_greeting Polling functions (@pxref{Polling functions}) set this variable before returning. It contains the initial SMTP reply from the last polled host. @end deftypevar @deftypevar {Predefined Variable} string last_poll_helo Polling functions (@pxref{Polling functions}) set this variable before returning. It contains the reply to the @code{HELO} (@code{EHLO}) command, received from the last polled host. @end deftypevar @deftypevar {Predefined Variable} string last_poll_host Polling functions (@pxref{Polling functions}) set this variable before returning. It contains the host name or @acronym{IP} address of the last polled host. @end deftypevar @deftypevar {Predefined Variable} string last_poll_recv Polling functions (@pxref{Polling functions}) set this variable before returning. It contains the last @acronym{SMTP} reply received from the remote host. In case of multi-line replies, only the first line is stored. If nothing was received the variable contains the string @samp{nothing}. @end deftypevar @deftypevar {Predefined Variable} string last_poll_send Polling functions (@pxref{Polling functions}) set this variable before returning. It contains the last @acronym{SMTP} command sent to the polled host. If nothing was sent, @code{last_poll_send} contains the string @samp{nothing}. @end deftypevar @anchor{mailfrom_address} @deftypevr {Predefined Variable} string mailfrom_address Email address used by polling functions in @acronym{SMTP} @code{MAIL FROM} command (@pxref{Polling}.). Default is @samp{<>}. Here is an example of how to change it: @smallexample set mailfrom_address "postmaster@@my.domain.com" @end smallexample @cindex multiple sender addresses You can set this value to a comma-separated list of email addresses, in which case the probing will try each address until either the remote party accepts it or the list of addresses is exhausted, whichever happens first. It is not necessary to enclose emails in angle brackets, as they will be added automatically where appropriate. The only exception is null return address, when used in a list of addresses. In this case, it should always be written as @samp{<>}. For example: @smallexample set mailfrom_address "postmaster@@my.domain.com, <>" @end smallexample @end deftypevr @deftypevr {Predefined Variable} number sa_code Spam score for the message, set by @code{sa} function (@pxref{sa}). @end deftypevr @deftypevr {Predefined Variable} number rcpt_count The variable @code{rcpt_count} keeps the number of recipients given so far by @code{RCPT TO} commands. It is defined only in @samp{envrcpt} handlers. @end deftypevr @deftypevr {Predefined Variable} number sa_threshold Spam threshold, set by @code{sa} function (@pxref{sa}). @end deftypevr @deftypevr {Predefined Variable} string sa_keywords Spam keywords for the message, set by @code{sa} function (@pxref{sa}). @end deftypevr @node Back references @section Back references @cindex back references, in program text A @dfn{back reference} is a sequence @samp{\@var{d}}, where @var{d} is a decimal number. It refers to the @var{d}th parenthesized subexpression in the last @command{matches} statement@footnote{The subexpressions are numbered by the positions of their opening parentheses, left to right.}. Any back reference occurring within a double-quoted string is replaced with the value of the corresponding subexpression. For example: @smallexample @group if $f matches '.*@@\(.*\)\.gnu\.org\.ua' set host \1 fi @end group @end smallexample If the value of @code{f} macro is @samp{smith@@unza.gnu.org.ua}, the above code will assign the string @samp{unza} to the variable @code{host}. Notice, that each occurrence of @code{matches} will reset the table of back references, so try to use them as early as possible. The following example illustrates a common error, when the back reference is used after the reference table has been reused by another matching: @smallexample @group # @r{Wrong!} if $f matches '.*@@\(.*\)\.gnu\.org\.ua' if $f matches 'some.*' set host \1 fi fi @end group @end smallexample This will produce the following run time error: @smallexample mailfromd: RUNTIME ERROR near file.rc:3: Invalid back-reference number @end smallexample @noindent because the inner match (@samp{some.*}) does not have any parenthesized subexpressions. @xref{Special comparisons}, for more information about @code{matches} operator. @node Handlers @section Handlers @cindex milter stage handler, defined @cindex stage handler, defined @cindex handler, defined @kwindex prog @dfn{Milter stage handler} (or @dfn{handler}, for short) is a subroutine responsible for processing a particular milter state. There are eight handlers available. Their order of invocation and arguments are described in @ref{milter-control-flow}. A handler is defined using the following construct: @smallexample @group prog @var{handler-name} do @var{handler-body} done @end group @end smallexample @noindent where @var{handler-name} is the name of the handler (@pxref{handler names}), @var{handler-body} is the list of filter statements composing the handler body. Some handlers take arguments, which can be accessed within the @var{handler-body} using the notation @var{$@var{n}}, where @var{n} is the ordinal number of the argument. Here we describe the available handlers and their arguments: @deffn {Handler} connect (string $1, number $2, number $3, string $4) @table @b @item Invocation: This handler is called once at the beginning of each @acronym{SMTP} connection. @item Arguments: @enumerate 1 @item @code{string}; The host name of the message sender, as reported by @acronym{MTA}. Usually it is determined by a reverse lookup on the host address. If the reverse lookup fails, @samp{$1} will contain the message sender's @acronym{IP} address enclosed in square brackets (e.g. @samp{[127.0.0.1]}). @item @code{number}; Socket address family. Include @file{status.mfh} to get symbolic definitions for the address families. Supported families are: @cindex FAMILY_STDIO @cindex FAMILY_UNIX @cindex FAMILY_INET @multitable @columnfractions 0.25 .10 0.45 @headitem Constant @tab Value @tab Meaning @item FAMILY_STDIO @tab 0 @tab Standard input/output (the @acronym{MTA} is run with @option{-bs} option) @item FAMILY_UNIX @tab 1 @tab @acronym{UNIX} socket @item FAMILY_INET @tab 2 @tab @acronym{IP}v4 protocol @end multitable @item @code{number}; Port number if @samp{$2} is @samp{FAMILY_INET}. @item @code{string}; Remote @acronym{IP} address if @samp{$2} is @samp{FAMILY_INET} or full file name of the socket if @samp{$2} is @samp{FAMILY_UNIX}. If @samp{$2} is @samp{FAMILY_STDIO}, @samp{$4} is an empty string. @end enumerate @end table @cindex actions, using in @code{connect} handler The actions (@pxref{Actions}) appearing in this handler are handled by Sendmail in a special way. First of all, any textual message is ignored. Secondly, the only action that immediately closes the connection is @code{tempfail 421}. Any other reply codes result in Sendmail switching to @dfn{nullserver} mode, where it accepts any commands, but answers with a failure to any of them, except for the following: @code{QUIT}, @code{HELO}, @code{NOOP}, which are processed as usual. The following table summarizes the Sendmail behavior depending on the action used: @table @code @item tempfail 421 @var{excode} @var{message} The caller is returned the following error message: @smallexample 421 4.7.0 @var{hostname} closing connection @end smallexample @noindent Both @var{excode} and @var{message} are ignored. @item tempfail 4@var{xx} @var{excode} @var{message} (where @var{xx} represents any digits, except @samp{21}) Both @var{excode} and @var{message} are ignored. Sendmail switches to nullserver mode. Any subsequent command, excepting the ones listed above, is answered with @smallexample 454 4.3.0 Please try again later @end smallexample @item reject 5@var{xx} @var{excode} @var{message} (where @var{xx} represents any digits). All arguments are ignored. Sendmail switches to nullserver mode. Any subsequent command, excepting ones listed above, is answered with @smallexample 550 5.0.0 Command rejected @end smallexample @end table Regarding reply codes, this behavior complies with @acronym{RFC} 2821 (section 3.9), which states: @quotation An @acronym{SMTP} server @emph{must not} intentionally close the connection except:@* [@dots{}]@* - After detecting the need to shut down the @acronym{SMTP} service and returning a 421 response code. This response code can be issued after the server receives any command or, if necessary, asynchronously from command receipt (on the assumption that the client will receive it after the next command is issued). @end quotation However, the @acronym{RFC} says nothing about textual messages and extended error codes, therefore Sendmail's ignoring of these is, in my opinion, absurd. My practice shows that it is often reasonable, and even necessary, to return a meaningful textual message if the initial connection is declined. The opinion of @command{mailfromd} users seems to support this view. Bearing this in mind, @command{mailfromd} is shipped with a patch for Sendmail 8.13.7 which makes it honor both extended return code and textual message given with the action. The patch is in the file @file{etc/@/sendmail-8.13.7.connect.diff}. It applies cleanly to versions of Sendmail up to 8.14. @end deffn @deffn {Handler} helo (string $1) @table @b @item Invocation: This handler is called whenever the @acronym{SMTP} client sends @code{HELO} or @code{EHLO} command. Depending on the actual @acronym{MTA} configuration, it can be called several times or even not at all. @item Arguments: @enumerate 1 @item @code{string}; Argument to @code{HELO} (@code{EHLO}) commands. @end enumerate @item Notes: According to @acronym{RFC} 28221, @code{$1} must be domain name of the sending host, or, in case this is not available, its @acronym{IP} address enclosed in square brackets. Be careful when taking decisions based on this value, because in practice many hosts send arbitrary strings. We recommend to use @code{heloarg_test} function (@pxref{heloarg_test}) if you wish to analyze this value. @end table @end deffn @deffn {Handler} envfrom (string $1, string $2) @table @b @item Invocation: Called when the @acronym{SMTP} client sends @code{MAIL FROM} command, i.e. once at the beginning of each message. @item Arguments: @enumerate 1 @item @code{string}; First argument to the @code{MAIL FROM} command, i.e. the email address of the sender. @item @code{string}; Rest of arguments to @code{MAIL FROM} separated by space character. This argument can be @samp{""}. @end enumerate @item Notes @enumerate 1 @item @code{$1} is not the same as @code{$f} Sendmail variable, because the latter contains the sender email after address rewriting and normalization, while @code{$1} contains exactly the value given by sending party. @item When the array type is implemented, @code{$2} will contain an array of arguments. @end enumerate @end table @end deffn @deffn {Handler} envrcpt (string $1, string $2) @table @b @item Invocation: Called once for each @code{RCPT TO} command, i.e. once for each recipient, immediately after @code{envfrom}. @item Arguments: @enumerate 1 @item @code{string}; First argument to the @code{RCPT TO} command, i.e. the email address of the recipient. @item @code{string}; Rest of arguments to @code{RCPT TO} separated by space character. This argument can be @samp{""}. @end enumerate @item Notes: When the array type is implemented, @code{$2} will contain an array of arguments. @end table @end deffn @deffn {Handler} header (string $1, string $2) @table @b @item Invocation: Called once for each header line received after @acronym{SMTP} @code{DATA} command. @item Arguments: @enumerate 1 @item @code{string}; Header field name. @item @code{string}; Header field value. The content of the header may include folded white space, i.e., multiple lines with following white space where lines are separated by @sc{lf} (@acronym{ASCII} 10). The trailing line terminator (@sc{cr/lf}) is removed. @end enumerate @end table @end deffn @deffn {Handler} eoh @table @b @item Invocation: This handler is called once per message, after all headers have been sent and processed. @item Arguments: None. @end table @end deffn @anchor{body handler} @deffn {Handler} body (pointer $1, number $2) @table @b @item Invocation: This header is called zero or more times, for each piece of the message body obtained from the remote host. @item Arguments: @enumerate 1 @item @code{pointer}; Piece of body text. See @samp{Notes} below. @item @code{number}; Length of data pointed to by @code{$1}, in bytes. @end enumerate @item Notes: The first argument points to the body chunk. Its size may be quite considerable and passing it as a string may be costly both in terms of memory and execution time. For this reason it is not passed as a string, but rather as a @dfn{generic pointer}, i.e. an object having the same size as @code{number}, which can be used to retrieve the actual contents of the body chunk if the need arises. A special function @code{body_string} is provided to convert this object to a regular @acronym{MFL} string (@pxref{Mail body functions}). Using it you can collect the entire body text into a single global variable, as illustrated by the following example: @smallexample string text prog body do set text %text body_string($1,$2) done @end smallexample @end table @end deffn The text collected this way can then be used in the @code{eom} handler (see below) to parse and analize it. If you wish to analyze both the headers and mail body, the following code fragment will do that for you: @smallexample string text # @r{Collect all headers.} prog header do set text %text $1 ": " $2 "\n" done # @r{Append terminating newline to the headers.} prog eoh do set text %text "\n" done # @r{Collect message body.} prog body do set text %text body_string($1, $2) done @end smallexample @deffn {Handler} eom @table @b @item Invocation: This handler is called once per message, when the terminating dot after @code{DATA} command has been received. @item Arguments: None @item Notes: This handler is useful for calling @dfn{message capturing} functions, such as @code{sa} or @code{clamav}. For more information about these, refer to @ref{Interfaces to Third-Party Programs}. @end table @end deffn For your reference, the following table shows each handler with its arguments: @cindex milter stage handler arguments @cindex stage handler arguments @cindex handler arguments @float Table, handler-arguments @caption{State Handler Arguments} @multitable @columnfractions 0.20 0.20 0.20 0.20 0.20 @headitem Handler @tab $1 @tab $2 @tab $3 @tab $4 @item connect @tab Hostname @tab Socket Family @tab Port @tab Remote address @item helo @tab @code{HELO} domain @tab @acronym{N/A} @tab @acronym{N/A} @tab @acronym{N/A} @item envfrom @tab Sender email address @tab Rest of arguments @tab @acronym{N/A} @tab @acronym{N/A} @item envrcpt @tab Recipient email address @tab Rest of arguments @tab @acronym{N/A} @tab @acronym{N/A} @item header @tab Header name @tab Header value @tab @acronym{N/A} @tab @acronym{N/A} @item eoh @tab @acronym{N/A} @tab @acronym{N/A} @tab @acronym{N/A} @tab @acronym{N/A} @item body @tab Body segment (pointer) @tab Length of the segment (numeric) @tab @acronym{N/A} @tab @acronym{N/A} @item eom @tab @acronym{N/A} @tab @acronym{N/A} @tab @acronym{N/A} @tab @acronym{N/A} @end multitable @end float @node begin/end @section The @samp{begin} and @samp{end} special handlers @cindex begin, special handler @cindex end, special handler @cindex startup handler @cindex handler, startup @cindex handler, initialization @cindex cleanup handler @cindex handler, cleanup Apart from the milter handlers described in the previous section, @acronym{MFL} defines two special handlers, called @samp{begin} and @samp{end}, which supply startup and cleanup instructions for the filter program. The @samp{begin} special handler is executed once for each @acronym{SMTP} session, after the connection has been established but before the first milter handler has been called. Similarly, an @samp{end} handler is executed exactly once, after the connection has been closed. Neither of them takes any arguments. @kwindex begin @kwindex end The two handlers are defined using the following syntax: @smallexample # @r{Begin handler} begin do @dots{} done # @r{End handler} end do @dots{} done @end smallexample @noindent where @samp{@dots{}} represent any @acronym{MFL} statements. An @acronym{MFL} program may have multiple @samp{begin} and @samp{end} definitions. They can be intermixed with other definitions. The compiler combines all @samp{begin} statements into a single one, in the order they appear in the sources. Similarly, all @samp{end} blocks are concatenated together. The resulting @samp{begin} is called once, at the beginning of each @acronym{SMTP} session, and @samp{end} is called once at its termination. Multiple @samp{begin} and @samp{end} handlers are a useful feature for writing modules (@pxref{Modules}), because each module can thus have its own initialization and cleanup blocks. Notice, however, that in this case the order in which subsequent @samp{begin} and @samp{end} blocks are executed is not defined. It is only warranted that all @samp{begin} blocks are executed at startup and all @samp{end} blocks are executed at shutdown. It is also warranted that all @samp{begin} and @samp{end} blocks defined within a compilation unit (i.e. a single abstract source file, with all @code{#include} and @code{#include_once} statements expanded in place) are executed in order of their appearance in the unit. @cindex @samp{begin}, handler restrictions @cindex @samp{end}, handler restrictions Due to their special nature, the startup and cleanup blocks impose certain restrictions on the statements that can be used within them: @enumerate 1 @cindex @code{return} in @samp{begin} @cindex @samp{begin} and @code{return} @cindex @code{return} in @samp{end} @cindex @samp{end} and @code{return} @item @code{return} cannot be used in @samp{begin} and @samp{end} handlers. @FIXME{It could be a useful feature, though.} @cindex @code{accept} in @samp{begin} @cindex @samp{begin} and @code{accept} @cindex @code{accept} in @samp{end} @cindex @samp{end} and @code{accept} @cindex @code{continue} in @samp{begin} @cindex @samp{begin} and @code{continue} @cindex @code{continue} in @samp{end} @cindex @samp{end} and @code{continue} @cindex @code{discard} in @samp{begin} @cindex @samp{begin} and @code{discard} @cindex @code{discard} in @samp{end} @cindex @samp{end} and @code{discard} @cindex @code{reject} in @samp{begin} @cindex @samp{begin} and @code{reject} @cindex @code{reject} in @samp{end} @cindex @samp{end} and @code{reject} @cindex @code{tempfail} in @samp{begin} @cindex @samp{begin} and @code{tempfail} @cindex @code{tempfail} in @samp{end} @cindex @samp{end} and @code{tempfail} @item The following Sendmail actions cannot be used in them: @code{accept}, @code{continue}, @code{discard}, @code{reject}, @code{tempfail}. They can, however, be used in @code{catch} statements, declared in @samp{begin} blocks (see example below). @cindex @code{add} in @samp{begin} @cindex @samp{begin} and @code{add} @cindex @code{add} in @samp{end} @cindex @samp{end} and @code{add} @cindex @code{replace} in @samp{begin} @cindex @samp{begin} and @code{replace} @cindex @code{replace} in @samp{end} @cindex @samp{end} and @code{replace} @cindex @code{delete} in @samp{begin} @cindex @samp{begin} and @code{delete} @cindex @code{delete} in @samp{end} @cindex @samp{end} and @code{delete} @item Header manipulation actions (@pxref{header manipulation}) cannot be used in @samp{end} handler. @end enumerate The @samp{begin} handlers are the usual place to put global initialization code to. For example, if you do not want to use @acronym{DNS} caching, you can do it this way: @smallexample @group begin do db_set_active("dns", 0) done @end group @end smallexample Additionally, you can set up global exception handling routines there. For example, the following @samp{begin} statement disables @acronym{DNS} cache and, for all exceptions not handled otherwise, installs a handler that logs the exception along with the stack trace and continues processing the message: @smallexample @group begin do db_set_active("dns", 0) catch * do echo "Caught exception $1: $2" stack_trace() continue done done @end group @end smallexample @node Functions @section Functions A @dfn{function} is a named @command{mailfromd} subroutine, which takes zero or more @dfn{parameters} and returns certain @dfn{value}. Depending on the return value, functions can be subdivided into @dfn{string functions} and @dfn{number functions}. The number of parameters is fixed for each function. When invoked, the function must be supplied exactly as many @dfn{actual arguments} as it has parameters. The function invocation syntax is: @smallexample @var{name} (@var{args}) @end smallexample @noindent where @var{name} is the function name and @var{args} is a comma-separated list of variables. Single-argument functions compose a special subclass: for convenience they can be invoked without parentheses around their argument. Summarizing, following are valid function calls: @smallexample @group # @r{Single-argument functions:} foo 10 interval "1 hour" interval("1 hour") # @r{Multi-argument functions:} greylist("/var/my.db", 180) @end group @end smallexample The number of parameters a function takes and their data types compose the @dfn{function signature}. When actual arguments are passed to the function, they are converted to types of corresponding formal parameters. There are two major groups of functions: @dfn{built-in} functions, that are implemented in the @command{mailfromd} binary, and @dfn{user-defined} functions, that are written in @acronym{MFL}. The invocation syntax is the same for both groups. @command{Mailfromd} is shipped with a rich set of @dfn{library functions}. In addition to these you can define your own functions. In subsequent sections we will discuss the library and built-in functions, and then we will explain how to write new functions. @menu * Built-in:: Built-in and Library Functions * User-defined:: Syntax for defining user functions @end menu @node Built-in @subsection Built-in and Library Functions This subsection describes built-in and library functions available in version @value{VERSION}. @menu * Macro access:: * String manipulation:: * String formatting:: * Character Type:: * Envelope modification functions:: * Header modification functions:: * Body Modification Functions:: * Mail header functions:: * Mail body functions:: * Mailbox functions:: * Message functions:: * Quarantine functions:: * Polling functions:: * Internet address manipulation functions:: * DNS functions:: * Database functions:: * I/O functions:: * System functions:: * Sieve Interface:: * Interfaces to Third-Party Programs:: * Rate limiting functions:: * Greylisting functions:: * Special test functions:: * Mail Sending Functions:: * NLS Functions:: * Debugging Functions:: * Blacklisting Functions:: * SPF Functions:: @end menu @node Macro access @subsubsection Sendmail Macro Access Functions @deftypefn {Built-in Function} string getmacro (string @var{macro}) Returns the value of Sendmail macro @var{macro}. If @var{macro} is not defined, raises the @code{e_macroundef} exception. Calling @code{getmacro(@var{name})} is completely equivalent to referencing @code{$@{@var{name}@}}, except that it allows to construct macro names programmatically, e.g.: @smallexample if getmacro("auth_" %var) = "foo" @dots{} fi @end smallexample @end deftypefn @deftypefn {Built-in Function} number macro_defined (string @var{name}) Return true if Sendmail macro @var{name} is defined. @end deftypefn @node String manipulation @subsubsection String Manipulation Functions @deftypefn {Built-in Function} string domainpart (string @var{str}) Returns the domain part of @var{str}, if it is a valid email address, otherwise returns @var{str} itself. @smallexample @group domainpart "gray" @result{} "gray" domainpart "gray@@gnu.org.ua" @result{} "gnu.org.ua" @end group @end smallexample @end deftypefn @anchor{index-built-in} @deftypefn {Built-in Function} number index (string @var{s}, string @var{t}) @deftypefnx {Built-in Function} number index (string @var{s}, string @var{t}, @ number @var{start}) Returns the index of the first occurrence of the string @var{t} in the string @var{s}, or -1 if @var{t} is not present. @smallexample index("string of rings", "ring") @result{} 2 @end smallexample Optional argument @var{start}, if supplied, indicates the position in string where to start searching. @smallexample index("string of rings", "ring", 3) @result{} 10 @end smallexample To find the last occurrence of a substring, use the function @var{rindex} (@pxref{rindex}). @end deftypefn @anchor{interval} @deftypefn {Built-in Function} number interval (string @var{str}) Converts @var{str}, which should be a valid time interval specification (@pxref{time interval specification}), to seconds. @end deftypefn @deftypefn {Built-in Function} number length (string @var{str}) Returns the length of the string @var{str} in bytes. @smallexample length "string" @result{} 6 @end smallexample @end deftypefn @deftypefn {Built-in Function} string localpart (string @var{str}) Returns the local part of @var{str} if it is a valid email address, otherwise returns @var{str} unchanged. @smallexample @group localpart "gray" @result{} "gray" localpart "gray@@gnu.org.ua" @result{} "gray" @end group @end smallexample @end deftypefn @deftypefn {Built-in Function} string replstr (string @var{s}, number @var{n}) Replicate a string, i.e. return a string, consisting of @var{s} repeated @var{n} times: @smallexample replstr("12", 3) @result{} "121212" @end smallexample @end deftypefn @deftypefn {Built-in Function} string revstr (string @var{s}) Returns the string composed of the characters from @var{s} in reversed order: @smallexample revstr("foobar") @result{} "raboof" @end smallexample @end deftypefn @anchor{rindex} @deftypefn {Built-in Function} number rindex (string @var{s}, string @var{t}) @deftypefnx {Built-in Function} number rindex (string @var{s}, string @var{t}, @ number @var{start}) Returns the index of the last occurrence of the string @var{t} in the string @var{s}, or -1 if @var{t} is not present. @smallexample rindex("string of rings", "ring") @result{} 10 @end smallexample Optional argument @var{start}, if supplied, indicates the position in string where to start searching. E.g.: @smallexample rindex("string of rings", "ring", 10) @result{} 2 @end smallexample See also @ref{index-built-in, @code{index} built-in function, String manipulation}. @end deftypefn @anchor{substr} @deftypefn {Built-in Function} string substr (string @var{str}, @ number @var{start}) @deftypefnx {Built-in Function} string substr (string @var{str}, @ number @var{start}, number @var{length}) Returns the at most @var{length}-character substring of @var{str} starting at @var{start}. If @var{length} is omitted, the rest of @var{str} is used. If @var{length} is greater than the actual length of the string, the @code{e_range} exception is signalled. @smallexample substr("mailfrom", 4) @result{} "from" substr("mailfrom", 4, 2) @result{} "fr" @end smallexample @end deftypefn @anchor{substring} @deftypefn {Built-in Function} string substring (string @var{str}, @ number @var{start}, number @var{end}) Returns a substring of @var{str} between offsets @var{start} and @var{end}, inclusive. Negative @var{end} means offset from the end of the string. In other words, yo obtain a substring from @var{start} to the end of the string, use @code{substring(@var{str}, @var{start}, -1)}: @smallexample substring("mailfrom", 0, 3) @result{} "mail" substring("mailfrom", 2, 5) @result{} "ilfr" substring("mailfrom", 4, -1) @result{} "from" substring("mailfrom", 4, length("mailfrom") - 1) @result{} "from" substring("mailfrom", 4, -2) @result{} "fro" @end smallexample This function signals @code{e_range} exception if either @var{start} or @var{end} are outside the string length. @end deftypefn @anchor{tolower} @deftypefn {Built-in Function} string tolower (string @var{str}) Returns a copy of the string @var{str}, with all the upper-case characters translated to their corresponding lower-case counterparts. Non-alphabetic characters are left unchanged. @smallexample tolower "MAIL" @result{} "mail" @end smallexample @end deftypefn @anchor{toupper} @deftypefn {Built-in Function} string toupper (string @var{str}) Returns a copy of the string @var{str}, with all the lower-case characters translated to their corresponding upper-case counterparts. Non-alphabetic characters are left unchanged. @smallexample toupper "mail" @result{} "MAIL" @end smallexample @end deftypefn @deftypefn {Library Function} string sa_format_score (number @var{code}, @ number @var{prec}) Format @var{code} as a floating-point number with @var{prec} decimal digits: @smallexample sa_format_score(5000, 3) @result{} "5.000" @end smallexample @flindex sa.mf This function is convenient for formatting SpamAssassin scores for use in message headers and textual reports. It is defined in module @file{sa.mf}. @xref{sa, SpamAssassin}, for examples of its use. @end deftypefn @deftypefn {Library Function} string sa_format_report_header (string @var{text}) Format a SpamAssassin report text in order to include it in a RFC 822 header. This function selects the score listing from @var{%text}, and prefixes each line with @samp{* }. Its result looks like: @smallexample * 0.2 NO_REAL_NAME From: does not include a real name * 0.1 HTML_MESSAGE BODY: HTML included in message @end smallexample @xref{sa, SpamAssassin}, for examples of its use. @end deftypefn @anchor{strip_domain_part} @deftypefn {Library Function} string strip_domain_part (string @var{domain}, @ number @var{n}) Returns at most @var{n} last components of the domain name @var{domain}. If @var{n} is 0 the function is equivalent to @code{domainpart}. @flindex strip_domain_part.mf This function is defined in @file{strip_domain_part.mf} module (@pxref{Modules}). Examples: @smallexample #require strip_domain_part strip_domain_part("puszcza.gnu.org.ua", 2) @result{} "org.ua" strip_domain_part("puszcza.gnu.org.ua", 0) @result{} "gnu.org.ua" @end smallexample @end deftypefn @deftypefn {Library Function} boolean is_ip (string @var{str}) @flindex is_ip.mf Returns @samp{true} if @var{str} is a valid @acronym{IP}v4 address. This function is defined in @file{is_ip.mf} module (@pxref{Modules}). For example: @smallexample #require is_ip is_ip("1.2.3.4") @result{} 1 is_ip("1.2.3.x") @result{} 0 is_ip("blah") @result{} 0 is_ip("255.255.255.255") @result{} 1 is_ip("0.0.0.0") @result{} 1 @end smallexample @end deftypefn @anchor{revip} @deftypefn {Library Function} string revip (string @var{ip}) Reverses octets in @var{ip}, which must be a valid string representation of an @acronym{IP}v4 address. Example: @code{revip("127.0.0.1") @result{} "1.0.0.127"} @end deftypefn @deftypefn {Library Function} string verp_extract_user (string @var{email}, @ string @var{domain}) If @var{email} is a valid @acronym{VERP}-style email address for @var{domain}, this function returns the user name, corresponding to that email. Otherwise, it returns empty string. @smallexample verp_extract_user("gray=gnu.org.ua@@tuhs.org", 'gnu\..*') @result{} "gray" @end smallexample @end deftypefn @node String formatting @subsubsection String formatting @deftypefn {Built-in Function} string sprintf (string @var{format}, @dots{}) The function @code{sprintf} formats its argument according to @var{format} (see below) and returns the resulting string. It takes varying number of parameters, the only mandatory one being @var{format}. @end deftypefn @subsubheading Format of the format string The format string is a simplified version of the format argument to @acronym{C} @code{printf}-family functions. The format string is composed of zero or more @dfn{directives}: ordinary characters (not @samp{%}), which are copied unchanged to the output stream; and @dfn{conversion specifications}, each of which results in fetching zero or more subsequent arguments. Each conversion specification is introduced by the character @samp{%}, and ends with a conversion specifier. In between there may be (in this order) zero or more @dfn{flags}, an optional @dfn{minimum field width}, and an optional @dfn{precision}. Notice, that in practice that means that you should use single quotes with the @var{format} arguments, to protect conversion specifications from being recognized as variable references (@pxref{singe-vs-double}). No type conversion is done on arguments, so it is important that the supplied arguments match their corresponding conversion specifiers. By default, the arguments are used in the order given, where each @samp{*} and each conversion specifier asks for the next argument. If insufficiently many arguments are given, @code{sprintf} raises @samp{e_range} exception. One can also specify explicitly which argument is taken, at each place where an argument is required, by writing @samp{%@var{m}$}, instead of @samp{%} and @samp{*@var{m}$} instead of @samp{*}, where the decimal integer @var{m} denotes the position in the argument list of the desired argument, indexed starting from 1. Thus, @smallexample sprintf('%*d', %width, %num); @end smallexample @noindent and @smallexample sprintf('%2$*1$d', width, num); @end smallexample @noindent are equivalent. The second style allows repeated references to the same argument. @subsubheading The flag characters The character @samp{%} is followed by zero or more of the following @dfn{flags}: @table @samp @item # The value should be converted to an @dfn{alternate form}. For @samp{o} conversions, the first character of the output string is made zero (by prefixing a @samp{0} if it was not zero already). For @samp{x} and @samp{X} conversions, a non-zero result has the string @samp{0x} (or @samp{0X} for @samp{X} conversions) prepended to it. Other conversions are not affected by this flag. @item 0 The value should be zero padded. For @samp{d}, @samp{i}, @samp{o}, @samp{u}, @samp{x}, and @samp{X} conversions, the converted value is padded on the left with zeros rather than blanks. If the @samp{0} and @samp{-} flags both appear, the @samp{0} flag is ignored. If a precision is given, the @samp{0} flag is ignored. Other conversions are not affected by this flag. @item - The converted value is to be left adjusted on the field boundary. (The default is right justification.) The converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A @samp{-} overrides a @samp{0} if both are given. @item ' ' (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. @item + A sign (@samp{+} or @samp{-}) always be placed before a number produced by a signed conversion. By default a sign is used only for negative numbers. A @samp{+} overrides a space if both are used. @end table @subsubheading The field width An optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). Instead of a decimal digit string one may write @samp{*} or @samp{*@var{m}$} (for some decimal integer @var{m}) to specify that the field width is given in the next argument, or in the @var{m}-th argument, respectively, which must be of numeric type. A negative field width is taken as a @samp{-} flag followed by a positive field width. In no case does a non-existent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result. @subsubheading The precision An optional precision, in the form of a period (@samp{.}) followed by an optional decimal digit string. Instead of a decimal digit string one may write @samp{*} or @samp{*@var{m}$} (for some decimal integer @var{m}) to specify that the precision is given in the next argument, or in the @var{m}-th argument, respectively, which must be of numeric type. If the precision is given as just @samp{.}, or the precision is negative, the precision is taken to be zero. This gives the minimum number of digits to appear for @samp{d}, @samp{i}, @samp{o}, @samp{u}, @samp{x}, and @samp{X} conversions, or the maximum number of characters to be printed from a string for the @samp{s} conversion. @subsubheading The conversion specifier A character that specifies the type of conversion to be applied. The conversion specifiers and their meanings are: @table @asis @item d @itemx i The numeric argument is converted to signed decimal notation. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. The default precision is @samp{1}. When @samp{0} is printed with an explicit precision @samp{0}, the output is empty. @item o @itemx u @itemx x @itemx X The numeric argument is converted to unsigned octal (@samp{o}), unsigned decimal (@samp{u}), or unsigned hexadecimal (@samp{x} and @samp{X}) notation. The letters @samp{abcdef} are used for @samp{x} conversions; the letters @samp{ABCDEF} are used for @samp{X} conversions. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. The default precision is @samp{1}. When @samp{0} is printed with an explicit precision 0, the output is empty. @item s The string argument is written to the output. If a precision is specified, no more than the number specified of characters are written. @item % A @samp{%} is written. No argument is converted. The complete conversion specification is @samp{%%}. @end table @node Character Type @subsubsection Character Type @cindex ctype_mismatch, global variable These functions check whether all characters of @var{str} fall into a certain character class according to the @samp{C} (@samp{POSIX}) locale@footnote{Support for other locales is planned for future versions.}. @samp{True} (1) is returned if they do, @samp{false} (0) is returned otherwise. In the latter case, global variable @code{ctype_mismatch} is set to the index of the first character that is outside of the character class (characters are indexed from 0). @deftypefn {Built-in Function} number isalnum (string @var{str}) Checks for alphanumeric characters: @smallexample isalnum("a123") @result{} 1 isalnum("a.123") @result{} 0 (ctype_mismatch = 1) @end smallexample @end deftypefn @deftypefn {Built-in Function} number isalpha (string @var{str}) Checks for an alphabetic character: @smallexample isalnum("abc") @result{} 1 isalnum("a123") @result{} 0 @end smallexample @end deftypefn @deftypefn {Built-in Function} number isascii (string @var{str}) Checks whether all characters in @var{str} are 7-bit ones, thatt fit into the @acronym{ASCII} character set. @smallexample isascii("abc") @result{} 1 isascii("ab\0200") @result{} 0 @end smallexample @end deftypefn @deftypefn {Built-in Function} number isblank (string @var{str}) Checks if @var{str} contains only blank characters; that is, spaces or tabs. @end deftypefn @deftypefn {Built-in Function} number iscntrl (string @var{str}) Checks for control characters. @end deftypefn @deftypefn {Built-in Function} number isdigit (string @var{str}) Checks for digits (0 through 9). @end deftypefn @deftypefn {Built-in Function} number isgraph (string @var{str}) Checks for any printable characters except spaces. @end deftypefn @deftypefn {Built-in Function} number islower (string @var{str}) Checks for lower-case characters. @end deftypefn @deftypefn {Built-in Function} number isprint (string @var{str}) Checks for printable characters including space. @end deftypefn @deftypefn {Built-in Function} number ispunct (string @var{str}) Checks for any printable characters which are not a spaces or alphanumeric characters. @end deftypefn @deftypefn {Built-in Function} number isspace (string @var{str}) Checks for white-space characters, i.e.: space, form-feed (@samp{\f}), newline (@samp{\n}), carriage return (@samp{\r}), horizontal tab (@samp{\t}), and vertical tab (@samp{\v}). @end deftypefn @deftypefn {Built-in Function} number isupper (string @var{str}) Checks for uppercase letters. @end deftypefn @deftypefn {Built-in Function} number isxdigit (string @var{str}) Checks for hexadecimal digits, i.e. one of @samp{0}, @samp{1}, @samp{2}, @samp{3}, @samp{4}, @samp{5}, @samp{6}, @samp{7}, @samp{8}, @samp{9}, @samp{a}, @samp{b}, @samp{c}, @samp{d}, @samp{e}, @samp{f}, @samp{A}, @samp{B}, @samp{C}, @samp{D}, @samp{E}, @samp{F}. @end deftypefn @node Envelope modification functions @subsubsection Envelope Modification Functions Envelope modification functions add or delete recipient addresses from the message envelope. This allows @acronym{MFL} scripts to redirect messages to another addresses. @deftypefn {Built-in Function} void rcpt_add (string @var{address}) Add the e-mail @var{address} to the envelope. @end deftypefn @deftypefn {Built-in Function} void rcpt_delete (string @var{address}) Remove @var{address} from the envelope. @end deftypefn The following example code implements a simple alias-like capability: @smallexample prog envrcpt do string alias dbget(%aliasdb, $1, "NULL", 1) if %alias != "NULL" rcpt_delete($1) rcpt_add(%alias) fi done @end smallexample @node Header modification functions @subsubsection Header Modification Functions @cindex header modification There are two ways to modify message headers in a @acronym{MFL} script. First is to use header actions, described in @ref{Actions}, and the second way is to use message modification functions. Compared with the actions, the functions offer a series of advantages. For example, using functions you can construct the name of the header to operate upon (e.g. by concatenating several arguments), something which is impossible when using actions. Moreover, apart from three basic operations (add, modify and remove), as supported by header actions, header functions allow to insert a new header into a particular place. @deftypefn {Built-in Function} void header_add (string @var{name}, @ string @var{value} [, number @var{idx}]) Adds a header @samp{@var{name}: @var{value}} to the message. If @var{idx} is given, it specifies a 0-based index in the header list where to insert this header. If @var{idx} is not supplied, the header is appended to the end of the header list. In contrast to @code{add} action, this function allows to construct the header name using arbitrary @acronym{MFL} expressions. @end deftypefn @deftypefn {Built-in Function} void header_insert (string @var{name}, @ string @var{value}, number @var{idx}) This function is equivalent to @code{header_add} with three arguments, i.e. it inserts a header @samp{@var{name}: @samp{value}} at @var{idx}th header position in the message. @end deftypefn @deftypefn {Built-in Function} void header_delete (string @var{name} @ [, number @var{index}]) Delete header @var{name} from the envelope. If @var{index} is given, delete @var{index}th instance of the header @var{name}. Notice the differences between this function and the @code{delete} action: @enumerate 1 @item It allows to construct the header name, whereas @code{delete} requires it to be a literal string. @item Optional @var{index} argument allows to select a particular header instance to delete. @end enumerate @end deftypefn @deftypefn {Built-in Function} void header_replace (string @var{name}, @ string @var{value} [, number @var{index}]) Replace the value of the header @var{name} with @var{value}. If @var{index} is given, replace @var{index}th instance of header @var{name}. Notice the differences between this function and the @code{replace} action: @enumerate 1 @item It allows to construct the header name, whereas @code{replace} requires it to be a literal string. @item Optional @var{index} argument allows to select a particular header instance to replace. @end enumerate @end deftypefn @node Body Modification Functions @subsubsection Body Modification Functions Body modification is an experimental feature of @acronym{MFL}. Version @value{VERSION} provides only one function for that purpose. @deftypefn {Built-in Function} void replbody (string @var{text}) Replace the body of the message with @var{text}. Notice, that @var{text} must not contain RFC 822 headers. See previous section if you want to manipulate message headers. Example: @smallexample replbody("Body of this message has been removed by the mail filter.") @end smallexample No restrictions are imposed on the format of @var{text}. @end deftypefn @node Mail header functions @subsubsection Mail Header Functions @deftypefn {Built-in Function} string message_header_encode @ (string @var{text}, [string @var{enc}, string @var{charset}]) Encode @var{text} in accordance with @acronym{RFC} 2047. Optional arguments: @table @var @item enc Encoding to use. Valid values are @samp{quoted-printable}, or @samp{Q} (the default) and @samp{base64}, or @samp{B}. @item charset Character set. By default @samp{UTF-8}. @end table If the function is unable to encode the string, it raises the exception @code{e_failure}. For example: @smallexample @group set string "Keld J@o{}rn Simonsen " message_header_encode(%string, "ISO-8859-1") @result{} "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= " @end group @end smallexample @end deftypefn @deftypefn {Built-in Function} string message_header_decode @ (string @var{text}, [string @var{charset}]) @var{text} must be a header value encoded in accordance with @acronym{RFC} 2047. The function returns the decoded string. If the decoding fails, it raises @code{e_failure} exception. The optional argument @var{charset} specifies the character set to use (default -- @samp{UTF-8}). @smallexample @group set string "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= " message_header_decode(%string) @result{} "Keld J@o{}rn Simonsen " @end group @end smallexample @end deftypefn @deftypefn {Built-in Function} string unfold (string @var{text}) If @var{text} is a ``folded'' multi-line @acronym{RFC} 2822 header value, unfold it. If @var{text} is a single-line string, return its unchanged copy. For example, suppose that the message being processed contained the following header: @smallexample @group List-Id: Sent bugreports to @end group @end smallexample Then, applying @code{unfold} to its value@footnote{For example: @smallexample prog header do echo unfold($2) done @end smallexample } will produce: @smallexample Sent bugreports to @end smallexample @end deftypefn @node Mail body functions @subsubsection Mail Body Functions @deftypefn {Built-in Function} string body_string (pointer @var{text}, @ number @var{count}) Convert first @var{count} bytes from the memory location pointed to by @var{text} into a regular string. This function is intended to convert the @code{$1} argument passed to a @code{body} handler to a regular @acronym{MFL} string. For more information about its use, see @ref{body handler}. @end deftypefn @anchor{current_message} @deftypefn {Built-in Function} number current_message () This function can be used in @code{eom} handlers only. It returns a message descriptor referring to the current message. @xref{Message functions}, for a description of functions for accessing messages. @end deftypefn @node Mailbox functions @subsubsection Mailbox Functions @cindex mailbox functions A set of functions is provided for accessing mailboxes and messages within them. In this subsection we describe the functions for accessing mailboxes. A mailbox is opened using @code{mailbox_open} function: @deftypefn {Built-in Function} number mailbox_open (string @var{url} @ [, string @var{mode}, string @var{perms}]) Open a mailbox identified by @var{url}. Return a @dfn{mailbox descriptor}: a unique numeric identifier that can subsequently be used to access this mailbox. The optional @var{mode} argument specifies the access mode for which the mailbox should be opened. Its valid values are: @multitable @columnfractions 0.2 0.7 @headitem Value @tab Meaning @item r @tab Open mailbox for reading. This is the default. @item w @tab Open mailbox for writing. If the mailbox does not exist, it is created. @item rw @tab Open mailbox for reading and writing. If the mailbox does not exist, it is created. @item wr @tab Same as @samp{rw}. @item w+ @tab Open mailbox for reading and writing. If the mailbox does not exist, it is created. @item a @tab Open mailbox for appending messages to it. If the mailbox does not exist, an exception is signalled. @item a+ @tab Open mailbox for appending messages to it. If the mailbox does not exist, it is created. @end multitable @end deftypefn @deftypefn {Built-in Function} number mailbox_messages_count (number @var{nmbx}) Return the number of messages in mailbox. The argument @var{nmbx} is a valid mailbox descriptor as returned by a previous call to @code{mailbox_open}. @end deftypefn @deftypefn {Built-in Function} number mailbox_get_message (number @var{mbx}, @ number @var{n}) Retrieve @var{n}th message from the mailbox identified by descriptor @var{mbx}. On success, the function returns a @dfn{message descriptor}, an integer number that can subsequently be used to access that message (@pxref{Message functions}). On error, an exception is raised. Messages in a mailbox are numbered starting from 1. @end deftypefn @deftypefn {Built-in Function} void mailbox_close (number @var{nmbx}) Close a mailbox previously opened by @code{mailbox_open}. @end deftypefn @deftypefn {Built-in Function} void mailbox_append_message (number @var{nmbx}, @ number @var{nmsg}) Append message @var{nmsg} to mailbox @var{nmbx}. The message descriptior @var{nsmg} must be obtained from a previous call to @code{mailbox_get_message} or @code{current_message} (@pxref{current_message}). @end deftypefn @node Message functions @subsubsection Message Functions @cindex message functions The functions described below retrieve information from RFC822 messages. The message to operate upon is identified by its @dfn{descriptor}, an integer number returned by the previous call to @code{mailbox_get_message} (@pxref{Mailbox functions, mailbox_get_message}) or @code{current_message} (@pxref{current_message}) function. @deftypefn {Built-in Function} number message_size (number @var{nmsg}) Return the size of the message @var{nmsg}, in bytes. @emph{Notice}, that if @var{nmsg} refers to current message (@pxref{current_message}), the returned value is less than the size seen by the @acronym{MTA}, because @command{mailfromd} recodes @acronym{CR-LF} sequences to @acronym{LF}, i.e. removes carriage returns (@acronym{ASCII} 13) ocurring before line feeds (@acronym{ASCII} 10. To obtain actual message length as seen by the @acronym{MTA}, add the number of lines in the message: @smallexample set actual_length message_size(%nmsg) + message_lines(%nmsg) @end smallexample @end deftypefn @deftypefn {Built-in Function} number message_body_size (number @var{nmsg}) Return the size, in bytes, of the body of message @var{nmsg}. See the note to the @code{message_size}, above. @end deftypefn @deftypefn {Built-in Function} number message_header_size (number @var{nmsg}) Return the size, in bytes of the headers of message @var{nmsg}. See the note to the @code{message_size}, above. @end deftypefn @deftypefn {Built-in Function} number message_body_lines (number @var{nmsg}) Return number of lines in the body of message referred to by descriptor @var{nmsg}. @end deftypefn @deftypefn {Built-in Function} void message_body_rewind (number @var{nmsg}) Rewind stream associated with the body of message referred to by descriptor @var{nmsg}. A call to @code{message_body_read_line} (see below) after calling this function will return the first line from the message body. @end deftypefn @deftypefn {Built-in Function} void message_close (number @var{nmsg}) Close the message identified by descriptor @var{nmsg}. @end deftypefn @deftypefn {Built-in Function} number message_count_parts (number @var{nmsg}) Return number of parts in message @var{nmsg}, if it is a multipart (@acronym{MIME}) message. If it is not, return @samp{1}. Use @code{message_is_multipart} to check whether message is a multipart one. @end deftypefn @deftypefn {Built-in Function} string message_find_header (number @var{nmsg}, string @var{name} [, number @var{idx}]) Return value of header @var{name} from the message @var{nmsg}. If the message contains several headers with the same name, optional parameter @var{idx} may be used to select one of them. Headers are numbered from @samp{1}. If no matching header is not found, the @code{not_found} exception is raised. If another error occures, the @code{failure} exception is raised. The returned string is a verbatim copy of the message contents (except for eventual @acronym{CR-LF} -> @acronym{LF} translation, see above). You might need to apply the @code{unfold} function to it (@pxref{Mail header functions, unfold}). @end deftypefn @deftypefn {Built-in Function} number message_get_part (number nmsg, @ number @var{n}) Extract @var{n}th part from multipart message @var{nmsg}. Parts are named from @samp{1}. Return message descriptor referring to the extracted part. Message parts are regarded as messages, so any message functions can be applied to them. @end deftypefn @deftypefn {Built-in Function} boolean message_has_header (number @var{nmsg},@ string @var{name} [, number @var{idx}]) Return @code{true} if message @var{nmsg} contains header with the given @var{name}. If there are several headers with the same name, optional parameter @var{idx} may be used to select one of them. @end deftypefn @deftypefn {Built-in Function} number message_header_count (number @var{nmsg}) Return number of headers in message @var{nmsg}. @end deftypefn @deftypefn {Built-in Function} number message_header_lines (number @var{nmsg}) Return number of lines occupied by headers in message @var{nmsg}. @end deftypefn @deftypefn {Built-in Function} boolean message_is_multipart (number @var{nmsg}) Return @code{true} if message @var{nmsg} is a multipart (@acronym{MIME}) message. @end deftypefn @deftypefn {Built-in Function} number message_lines (number @var{nmsg}) Return total number of lines in message @var{nmsg}. The following relation holds true: @smallexample message_lines(@var{x}) = message_body_lines(@var{x}) + message_header_lines(@var{x}) + 1 @end smallexample @end deftypefn @deftypefn {Built-in Function} string message_read_body_line (number @var{nmsg}) Read and return next line from the body of message @var{nmsg}. If there are no more lines to read, raise the @code{not_found} exception. @FIXME{Probably a special exception type is needed for that.} Use @code{message_body_rewind} (see above) to rewind the body stream and read its contents again. @end deftypefn @deftypefn {Built-in Function} string message_read_line (number @var{nmsg}) Read and return next line from message @var{nmsg}. If there are no more lines to read, raise the @code{not_found} exception. Use @code{message_rewind} to rewind the message stream and read its contents again. @end deftypefn @deftypefn {Built-in Function} void message_rewind (number @var{nmsg}) Rewind stream associated with message referred to by descriptor @var{nmsg}. @end deftypefn @node Quarantine functions @subsubsection Quarantine Functions @deftypefn {Built-in Function} void quarantine (string @var{text}) Place the message to the quarantine queue, using @var{text} as explanatory reason. @end deftypefn @node Polling functions @subsubsection Polling Functions We have described the base notions about sender address verification (or @dfn{polling}, for short) in @ref{Checking Sender Address}. Here we will describe the functions @command{mailfromd} offers for this purpose. @deftypefn {Built-in Function} number _pollhost @ (string @var{ip}, string @var{email}, string @var{domain}, @ string @var{mailfrom}) Poll @acronym{SMTP} host @var{ip} for email address @var{email}, using @var{domain} as @code{EHLO} domain and @var{mailfrom} as @code{MAIL FROM}. Returns 0 or 1 depending on the result of the test. In contrast to @code{strictpoll} function, this function does not use cache database and does not fall back to polling @acronym{MX} servers if the main poll tempfails. The function can throw one of the following exceptions: @code{e_failure}, @code{e_temp_failure}. @end deftypefn @deftypefn {Built-in Function} number _pollmx @ (string @var{ip}, string @var{email}, string @var{domain}, @ string @var{mailfrom}) Poll @acronym{MX}s of the @var{domain} for email address @var{email}, using @var{domain} as @code{EHLO} domain and @var{mailfrom} as @code{MAIL FROM} address. Returns 0 or 1 depending on the result of the test. In contrast to @code{stdpoll} function, @code{_pollmx} does not use cache database and does not fall back to polling the @var{ip} if the poll fails. The function can throw one of the following exceptions: @code{e_failure}, @code{e_temp_failure}. @end deftypefn @deftypefn {Built-in Function} number stdpoll @ (string @var{email}, string @var{domain}, string @var{mailfrom}) Performs standard poll for @var{email}, using @var{domain} as @code{EHLO} domain and @var{mailfrom} as @code{MAIL FROM} address. Returns 0 or 1 depending on the result of the test. Can raise one of the following exceptions: @code{e_failure}, @code{e_temp_failure}. In @code{on} statement context, it is synonymous to @code{poll} without explicit @var{host}. @FIXME{more details and references} @end deftypefn @deftypefn {Built-in Function} number strictpoll @ (string @var{host}, string @var{email}, @ string @var{domain}, string @var{mailfrom}) Performs strict poll for @var{email} on host @var{host}. See the description of @code{stdpoll} for the detailed information. In @code{on} context, it is synonymous to @code{poll host @var{host}}. @end deftypefn @cindex multiple sender addresses, using with polling commands. @cindex trying several sender addresses The @var{mailfrom} argument can be a comma-separated list of email addresses, which can be useful for servers that are unusually picky about sender addresses. It is advised, however, that this list always contain the @samp{<>} address. For example: @smallexample _pollhost($client_addr, $f, "domain", "postmaster@@my.net,<>") @end smallexample See also @ref{pragma mailfrom}. Before returning, all described functions set the following built-in variables: @float Table, poll-variables-table @caption{Variables set by polling functions} @multitable @columnfractions 0.30 0.70 @headitem Variable @tab Contains @cindex last_poll_host, global variable, introduced @item last_poll_host @tab Host name or @acronym{IP} address of the last polled host. @cindex last_poll_send, global variable, introduced @item last_poll_send @tab Last @acronym{SMTP} command, sent to this host. If nothing was sent, it contains literal string @samp{nothing}. @cindex last_poll_recv, global variable, introduced @item last_poll_recv @tab Last @acronym{SMTP} reply received from this host. In case of multi-line replies, only the first line is stored. If nothing was received the variable contains the string @samp{nothing}. @cindex cache_used, global variable, introduced @item cache_used @tab @code{1} if cached data were used instead of polling, @code{0} otherwise. This variable is set by @code{stdpoll} and @code{strictpoll}. If it equals @code{1}, none of the above variables are modified. @xref{cache_used example}, for an example. @end multitable @end float @node Internet address manipulation functions @subsubsection Internet address manipulation functions Following functions operate on @acronym{IP}v4 addresses and @acronym{CIDR}s. @deftypefn {Built-in Function} number ntohl (number @var{n}) Converts the number @var{n}, from host to network byte order. The argument @var{n} is treated as an unsigned 32-bit number. @end deftypefn @deftypefn {Built-in Function} number htonl (number @var{n}) Converts the number @var{n}, from network to host byte order. The argument @var{n} is treated as an unsigned 32-bit number. @end deftypefn @deftypefn {Built-in Function} number ntohs (number @var{n}) The argument @var{n} is treated as an unsigned 16-bit number. The function converts this number from network to host order. @end deftypefn @deftypefn {Built-in Function} number htons (number @var{n}) The argument @var{n} is treated as an unsigned 16-bit number. The function converts this number from host to network order. @end deftypefn @deftypefn {Built-in Function} number inet_aton (string @var{s}) Converts the Internet host address @var{s} from the standard numbers-and-dots notation into the equivalent integer in host byte order. @smallexample inet_aton("127.0.0.1") @result{} 2130706433 @end smallexample @emph{The numeric data type in @acronym{MFL} is signed, therefore on machines with 32 bit integers, this conversion can result in a negative number:} @smallexample inet_aton("255.255.255.255") @result{} -1 @end smallexample @emph{However, this does not affect arithmetical operations on @acronym{IP} addresses.} @end deftypefn @deftypefn {Built-in Function} string inet_ntoa (number @var{n}) Converts the Internet host address @var{n}, given in host byte order to string in standard numbers-and-dots notation: @smallexample inet_ntoa(2130706433) @result{} "127.0.0.1" @end smallexample @end deftypefn @deftypefn {Built-in Function} number len_to_netmask (number @var{n}) Convert number of masked bits @var{n} to @acronym{IP}v4 netmask: @smallexample inet_ntoa(len_to_netmask(24)) @result{} 255.255.255.0 inet_ntoa(len_to_netmask(7)) @result{} 254.0.0.0 @end smallexample If @var{n} is greater than 32 the function raises @code{e_range} exception. @end deftypefn @deftypefn {Built-in Function} number netmask_to_len (number @var{mask}) Convert @acronym{IP}v4 netmask @var{mask} into netmask length (number of bits preserved by the mask): @smallexample netmask_to_len(inet_aton("255.255.255.0")) @result{} 24 netmask_to_len(inet_aton("254.0.0.0")) @result{} 7 @end smallexample @end deftypefn @deftypefn {Library Function} boolean match_cidr (string @var{ip}, @ string @var{cidr}) @flindex match_cidr.mf This function is defined in @file{match_cidr.mf} module (@pxref{Modules}). It returns @code{true} if the @acronym{IP} address @var{ip} pertains to the @acronym{IP} range @var{cidr}. The first argument, @var{ip}, is a string representation of an @acronym{IP} address. The second argument, @var{cidr}, is a string representation of a @acronym{IP} range in @acronym{CIDR} notation, i.e. @code{"@var{A.B.C.D}/@var{N}"}, where @var{A.B.C.D} is an @acronym{IP}v4 address and @var{N} specifies the @dfn{prefix length} -- the number of shared initial bits, counting from the left side of the address. The following example will reject the mail if the @acronym{IP} address of the sending machine does not belong to the block @code{10.10.1.0/19}: @smallexample @group if not match_cidr($@{client_addr@}, "10.10.1.0/19") reject fi @end group @end smallexample @end deftypefn @node DNS functions @subsubsection DNS Functions Most @acronym{DNS}-related functions cache their results in the database @samp{dns}, so no matter how many times you use a particular function in your startup program, it will result in at most one actual @acronym{DNS} lookup. See below (@pxref{DNS Cache Management}) for the description of the database and its management. The functions are implemented in two layers: @dfn{primitive} built-in functions which raise exceptions if the lookup fails, and library calls that are warranted to always return meaningful value without throwing exceptions. @flindex dns.mf The built-in layer is always available. The library calls become available after requesting @file{dns.mf} module (@pxref{Modules}): @smallexample #require dns @end smallexample @deftypefn {Built-in Function} string dns_getaddr (string @var{domain}) Returns a whitespace-separated list of @acronym{IP} addresses (@code{A} records) for @var{domain}. At most 64 addresses are returned. @FIXME{This limit should be configurable.} This function does not use the @acronym{DNS} cache. @end deftypefn @deftypefn {Built-in Function} string dns_getname (string @var{ipstr}) Returns a whitespace-separated list of domain names (@code{PTR} records) for the @acronym{IP}v4 address @var{ipstr}. At most 64 names are returned. @FIXME{This limit should be configurable.} This function does not use the @acronym{DNS} cache. @end deftypefn @deftypefn {Built-in Function} string getmx (string @var{domain} @ [, number @var{resolve}]) Returns a whitespace-separated list of @samp{MX} names (if @var{resolve} is not given or if it is @code{0}) or @samp{MX} @acronym{IP} addresses (if @code{@var{resolve}!=0})) for @var{domain}. Within the returned strings, items are sorted lexicographically. If @var{domain} has no @samp{MX} records, an empty string is returned. If the @acronym{DNS} query fails, @code{getmx} raises an appropriate exception. Examples: @smallexample getmx("mafra.cz") @result{} "smtp1.mafra.cz smtp2.mafra.cz relay.iol.cz" getmx("idnes.cz") @result{} "smtp1.mafra.cz smtp2.mafra.cz relay.iol.cz" getmx("gnu.org") @result{} "mx10.gnu.org mx20.gnu.org" getmx("org.pl") @result{} "" @end smallexample @emph{Notes}: @enumerate 1 @item The @code{getmx} function returns at most 32 @acronym{MX} names or @acronym{IP} addresses. @FIXME{This limit should probably be configurable.} @item The number of items returned by @code{getmx(@var{domain})} can differ from that obtained from @code{getmx(@var{domain}, 1)}, e.g.: @smallexample @group getmx("aol.com") @result{} mailin-01.mx.aol.com mailin-02.mx.aol.com mailin-03.mx.aol.com mailin-04.mx.aol.com getmx("aol.com", 1) @result{} 64.12.137.89 64.12.137.168 64.12.137.184 64.12.137.249 64.12.138.57 64.12.138.88 64.12.138.120 64.12.138.185 205.188.155.89 205.188.156.185 205.188.156.249 205.188.157.25 205.188.157.217 205.188.158.121 205.188.159.57 205.188.159.217 @end group @end smallexample @item This interface will change in future releases, when array data types are implemented. @end enumerate @end deftypefn @anchor{primitive_hasmx} @deftypefn {Built-in Function} boolean primitive_hasmx (string @var{domain}) Returns @code{true} if the domain name given by its argument has any @samp{MX} records. If the @acronym{DNS} query fails, this function throws @code{failure} or @code{temp_failure}. @end deftypefn @anchor{hasmx} @deftypefn {Library Function} boolean hasmx (string @var{domain}) Returns @code{true} if the domain name given by its argument has any @samp{MX} records. Otherwise, if @var{domain} has no @samp{MX}s or if the @acronym{DNS} query fails, @code{hasmx} returns @code{false}. @end deftypefn @deftypefn {Built-in Function} string primitive_hostname (string @var{ip}) The @var{ip} argument should be a string representing an @acronym{IP} address in @dfn{dotted-quad} notation. The function returns the canonical name of the host with this @acronym{IP} address obtained from @acronym{DNS} lookup. For example @smallexample primitive_hostname ($@{client_addr@}) @end smallexample @noindent returns the fully qualified domain name of the host represented by Sendmail variable @samp{client_addr}. If there is no @samp{PTR} record for @var{ip}, @code{primitive_hostname} raises the exception @code{e_not_found}. If @acronym{DNS} query fails, the function raises @code{failure} or @code{temp_failure}, depending on the character of the failure. @end deftypefn @anchor{hostname function} @deftypefn {Library Function} string hostname (string @var{ip}) The @var{ip} argument should be a string representing an @acronym{IP} address in @dfn{dotted-quad} notation. The function returns the canonical name of the host with this @acronym{IP} address obtained from @acronym{DNS} lookup. If there is no @samp{PTR} record for @var{ip}, or if the lookup fails, the function returns @var{ip} unchanged. The previous @command{mailfromd} versions used the following paradigm to check if an @acronym{IP} address resolves: @smallexample if hostname(%ip) != %ip ... @end smallexample @end deftypefn @anchor{primitive_ismx} @deftypefn {Built-in Function} boolean primitive_ismx (string @var{domain}, @ string @var{host}) The @var{domain} argument is any valid domain name, the @var{host} is a host name or @acronym{IP} address. The function returns @code{true} if @var{host} is one of the @samp{MX} records for the @var{domain}. If @var{domain} has no @samp{MX} records, @code{primitive_ismx} raises exception @code{e_not_found}. If @acronym{DNS} query fails, the function raises @code{failure} or @code{temp_failure}, depending on the character of the failure. @end deftypefn @anchor{ismx} @deftypefn {Library Function} boolean ismx (string @var{domain}, @ string @var{host}) The @var{domain} argument is any valid domain name, the @var{host} is a host name or @acronym{IP} address. The function returns @code{true} if @var{host} is one of the @samp{MX} records for the @var{domain}. Otherwise it returns @code{false}. If @var{domain} has no @samp{MX} records, or if the @acronym{DNS} query fails, the function returns @code{false}. @end deftypefn @deftypefn {Built-in Function} string primitive_resolve (string @var{host}, @ [string @var{domain}]) Reverse of @code{primitive_hostname}. The @code{primitive_resolve} function returns the @acronym{IP} address for the host name specified by @var{host} argument. If @var{host} has no A records, the function raises the exception @code{e_not_found}. If @acronym{DNS} lookup fails, the function raises @code{failure} or @code{temp_failure}, depending on the character of the failure. If the optional @var{domain} argument is given, it will be appended to @var{host} (with an intermediate dot), before querying the @acronym{DNS}. For example, the following two expressions will return the same value: @smallexample primitive_resolve("puszcza.gnu.org.ua") primitive_resolve("puszcza", "gnu.org.ua") @end smallexample There is a considerable internal difference between one-argument and two-argument forms of @code{primitive_resolve}: the former queries @acronym{DNS} for an @samp{A} record, whereas the latter queries it for any record matching @var{host} in the domain @var{domain} and then selects the most appropriate one. For example, the following two calls are equivalent: @smallexample primitive_hostname("213.130.0.22") primitive_resolve("22.0.130.213", "in-addr.arpa") @end smallexample This makes it possible to use @code{primitive_resolve} for querying @acronym{DNS} black listing domains. @xref{match_dnsbl}, for a working example of this approach. See also @ref{match_rhsbl}, for another practical example of the use of the two-argument form. @end deftypefn @deftypefn {Library Function} string resolve (string @var{host}, @ [string @var{domain}]) Reverse of @code{hostname}. The @code{resolve} function returns @acronym{IP} address for the host name specified by @var{host} argument. If the host name cannot be resolved, or a @acronym{DNS} failure occurs, the function returns @samp{"0"}. This function is entirely equivalent to @code{primitive_resolve} (see above), except that it never raises exceptions. @end deftypefn @anchor{DNS Cache Management} @cindex @acronym{DNS} cache management @cindex @acronym{DNS} cache database All the functions above use @dfn{DNS cache database} for caching @acronym{DNS} answers. The database is normally named @file{@var{statedir}/dns.db} (@xref{statedir,Local state directory}, for the description of @var{statedir}), but its actual name and location can be set at the run time using @code{#pragma database dns file} statement (@pxref{database}). Each record in the database consists of @dfn{expiration time} in seconds since the Epoch and the actual answer, which depends on the type of the query (see below). @cindex @acronym{DNS} cache database, lookup key When called, any @acronym{DNS} function first looks if the corresponding query is in the @samp{dns} database. It does so by building a @dfn{lookup key}, which consists of @dfn{query type} and @dfn{query argument} separated by a single whitespace. The @dfn{query type is}: @multitable @columnfractions 0.2 0.7 @item @samp{A} @tab for @code{resolve} @item @samp{PTR} @tab for @code{hostname} @item @samp{MX} @tab for @code{hasmx} and @code{ismx} @end multitable If the lookup key is present in the database and its expiration time is not yet reached, the corresponding answer from the database is returned. Otherwise, the function performs actual @acronym{DNS} lookup, stores the obtained data in the database and returns it. @cindex @acronym{DNS} cache database, expiration times @cindex expiration time, @acronym{DNS} cache database The expiration date for each new record is obtained by increasing the current system timestamp by the value of @acronym{TTL} obtained from the @acronym{DNS} reply. If the latter carried several @acronym{TTL}s (e.g. if it was an @samp{MX} request), the smallest of them is used. @cindex @acronym{DNS} cache database, negative caching @cindex negative caching, @acronym{DNS} cache database @cindex @acronym{DNS} cache database, negative expiration interval If the @acronym{DNS} lookup failed, the result is stored in the database as well. In this case, the value part of the record consists only of the expiration time (@dfn{negative caching}). It is computed by adding to the current timestamp the @dfn{negative expiration period}, which defaults to 3600 seconds. The negative expiration period can be configured using @code{#pragma database dns negative-expire-interval} statement. Thus, there are two statements in the startup file that control the settings of the @acronym{DNS} databases. The following example illustrates them: @smallexample @group #pragma database dns file "/var/run/mailfromd/dns.db" #pragma database dns negative-expire-interval 7200 @end group @end smallexample @cindex @acronym{DNS} cache database, listing @cindex listing @acronym{DNS} cache database The contents of the @acronym{DNS} database can be listed using the following command: @smallexample $ @kbd{mailfromd --list --format=dns} # @r{or:} $ @kbd{mailfromd --list -Hdns} @end smallexample You can look up a particular entry as well. For example: @smallexample @group $ @kbd{mailfromd --list -Hdns "A mx10.gnu.org"} A mx10.gnu.org: Sun Dec 3 10:56:12 2006 199.232.76.166 @end group @end smallexample The above example shows that the @acronym{IP} address of @samp{mx10.gnu.org} and that it expires on Sunday, December 3d, at 10:56:12. Of course, the rest of database management options are also valid for @acronym{DNS} database. @xref{Database Maintenance}, for more information on these. @node Database functions @subsubsection Database Functions The functions described below provide a user interface to @acronym{DBM} databases. Each @acronym{DBM} database is a separate disk file that keeps @dfn{key/value pairs}. The interface allows to retrieve the value corresponding to a given key. Both @samp{key} and @samp{value} are null-terminated character strings. To lookup a key, it is important to know whether its length includes the terminating null byte. By default, it is assumed that it does not. Another important database property is the @dfn{file mode} of the database file. The default file mode is @samp{640} (i.e. @samp{rw-r----}, in symbolic notation). Both properties can be configured using the @code{dbprop} pragma: @kwindex dbprop, @cindex dbprop, pragma @cindex #pragma dbprop @smallexample #pragma dbprop @var{pattern} @var{prop} [@var{prop}] @end smallexample The @var{pattern} is the database name or shell-style globbing pattern. Properties defined by that pragma apply to each database whose name matches this pattern. If several @code{dbprop} pragmas match the database name, the one that matches exactly is preferred. The rest of arguments define properties for that database. The valid values for @var{prop} are: @enumerate 1 @item The word @samp{null}, meaning that the terminating null byte is included in the key length. Setting @samp{null} property is necessary, for databases created with @command{makemap -N hash} command. @item File mode for the disk file. It can be either an octal number, or a symbolic mode specification in ls-like format. E.g., the following two formats are equivalent: @smallexample @group 640 rw-r---- @end group @end smallexample @end enumerate For example, consider the following pragmas: @smallexample #pragma dbprop /etc/mail/*.db null 600 #pragma dbprop /etc/mail/whitelist.db 640 #pragma dbprop /etc/mail/blacklist.db 640 @end smallexample The first of them tells that each database in @file{/etc/mail} directory must have the mode @samp{600} and include the null terminator in the key length. The remaining two pragmas define two exceptions: the databases @file{whitelist.db} and @file{blacklist.db} have privileges @samp{640} and do not include null in the key length. Additionally, for compatibility with previous versions (up to 5.0), the terminating null property can be requested via an optional argument to the database functions (in description below, marked as @var{null}). @anchor{dbmap} @deftypefn {Built-in Function} boolean dbmap (string @var{db}, @ string @var{key}, [number @var{null}]) Looks up @var{key} in the @acronym{DBM} file @var{db} and returns @code{true} if it is found. See above for the meaning of @var{null}. @xref{whitelisting}, for an example of using this function. @end deftypefn @deftypefn {Built-in Function} string dbget (string @var{db}, @ string @var{key} [, string @var{default}, number @var{null}]) Looks up @var{key} in the database @var{db} and returns the value associated with it. If the key is not found returns @var{default}, if specified, or empty string otherwise. See above for the meaning of @var{null}. @end deftypefn @deftypefn {Library Function} string safedbget (string @var{db}, @ string @var{key} [, string @var{default}, number @var{null}]) This is an exception-safe interface to @code{dbget}. If some database error occurs while attempting to retrieve the record, @code{safedbget} returns empty string. @flindex safedb.mf To use this function, request the @file{safedb.mf} module: @smallexample #require safedb @end smallexample @noindent @xref{Modules}, for a description of @acronym{MFL} module system. @end deftypefn @deftypefn {Built-in Function} void dbput (string @var{db}, @ string @var{key}, string @var{value} [, @ number @var{null}, number @var{mode} ]) Inserts in the database a record with the given @var{key} and @var{value}. If a record with the given @var{key} already exists, its value is replaced with the supplied one. See above for the meaning of @var{null}. Optional @var{mode} allows to explicitly specify the file mode for this database. See also @code{#pragma dbprop}, described above. @end deftypefn @deftypefn {Library Function} void safedbput (string @var{db}, @ string @var{key}, string @var{value} [, number @var{null}]) This is an exception-safe interface to @code{dbput}. If a database error occurs while attempting to retrieve the record, the function returns without reporting an error. @flindex safedb.mf To use this function, request the @file{safedb.mf} module: @smallexample #require safedb @end smallexample @noindent @xref{Modules}, for a description of @acronym{MFL} module system. @FIXME{safedbput should probably take an optional mode argument, as dbput does.} @end deftypefn @deftypefn {Built-in Function} void dbdel (string @var{db}, @ string @var{key} [, number @var{null}, number @var{mode}]) Delete from the database the record with the given @var{key}. If there are no such record, return without signalling error. If the optional @var{null} argument is given and is not zero, the terminating null character will be included in @var{key} length. Optional @var{mode} allows to explicitly specify the file mode for this database. See also @code{#pragma dbprop}, described above. @end deftypefn @anchor{dbm-seq} The following functions provide a sequential access to the contents of a @acronym{DBM} database: @deftypefn {Built-in Function} number dbfirst (string @var{name}) Start sequential access to the database @var{name}. The return value is an opaque identifier, which is used by the remaining sequential access functions. This number is @samp{0} if the database is empty. @end deftypefn @deftypefn {Built-in Function} number dbnext (number @var{dn}) Select next record form the database. The argument @var{dn} is the access identifier, returned by a previous call to @code{dbfirst} or @code{dbnext}. Returns new access identifier. This number is @samp{0} if all records in the database have been visited. @end deftypefn The usual approach for iterating over all records in a database @var{dbname} is: @smallexample loop for number dbn dbfirst(@var{dbname}) do @dots{} done while dbnext(%dbn) @end smallexample The following two functions can be used to access values of the currently selected database record. Their argument, @var{dn}, is the access identifier, returned by a previous call to @code{dbfirst} or @code{dbnext}. @deftypefn {Built-in Function} string dbkey (number @var{dn}) Return the key from the selected database record. @end deftypefn @deftypefn {Built-in Function} string dbvalue (number @var{dn}) Return the value from the selected database record. @end deftypefn @deftypefn {Built-in Function} number db_expire_interval (string @var{fmt}) The @var{fmt} argument is a database format identifier (@pxref{Database Formats}). If it is valid, the function returns the expiration interval for that format. @FIXME{How to obtain negative expiration??} Otherwise, @code{db_expire_interval} raises the @code{e_not_found} exception. @end deftypefn @deftypefn {Built-in Function} string db_name (string @var{fmtid}) The @var{fmt} argument is a database format identifier (@pxref{Database Formats}). The function returns the file name for that format. If @var{fmtid} does not match any known format, @code{db_name} raises the @code{e_not_found} exception. @end deftypefn @cindex getting cache status @cindex cache, getting status @deftypefn {Built-in Function} number db_get_active (string @var{fmtid}) Returns the flag indicating whether the cache database @var{fmtid} is currently enabled. If @var{fmtid} does not match any known format, @code{db_name} raises the @code{e_not_found} exception. @end deftypefn @cindex disabling cache @cindex cache, disabling @deftypefn {Built-in Function} void db_set_active (string @var{fmtid}, number @var{enable}) Enables the cache database @var{fmtid} if @var{enable} is not null, or disables it otherwise. For example, to disable @acronym{DNS} caching, do: @smallexample db_set_active("dns", 0) @end smallexample @end deftypefn @deftypefn {Built-in Function} boolean relayed (string @var{domain}) @anchor{relayed} Returns @code{true} if the string @var{domain} is found in one of relayed domain files (@xref{pragma relay}, and @pxref{option relay}). The usual construct is: @smallexample relayed hostname $@{client_addr@} @end smallexample @noindent which yields @code{true} if the @acronym{IP} address from @command{Sendmail} variable @samp{client_addr} is relayed by the local machine. @end deftypefn @node I/O functions @subsubsection I/O functions @acronym{MFL} provides a set of functions for writing to disk files or pipes and reading from them. The idea behind them is the same as in most other programming languages: first you open the resource with a call to @code{open} which returns a @dfn{descriptor} i.e. an integer number uniquely identifying the resource. Then you can write or read from it using this descriptor. Finally, when the resource is no longer needed, you can close it with a call to @code{close}. @deftypefn {Built-in Function} number open (string @var{name}) The @var{name} argument specifies the name of a resource to open and the access rights you need to have on it. The function returns a descriptor of the opened stream, which can subsequently be used as an argument to other @acronym{I/O} operations. First symbols of @var{name} determine the type of the resource to be opened and the access mode: @table @samp @item > The rest of @var{name} is a name of a file. Open the file for read-write access. If the file exists, truncate it to zero length, otherwise create the file. @item >> The rest of @var{name} is a name of a file. Open the file for appending (writing at end of file). The file is created if it does not exist. @item | Treat the rest of @var{name} as the command name and its arguments. Run this command and open its standard input for writing. @item |& Treat the rest of @var{name} as the command name and its arguments. Run this command and set up for two-way communication with it, i.e writes to the descriptor returned by @code{open} will send data to the program's standard input, reads from the descriptor will get data from the program's standard output. @end table If none of these prefixes is used, @var{name} is treated as a name of an existing file and @code{open} will attempt to open this file for reading. The @code{open} function will signal exception @code{e_failure} if it is unable to open the resource or get the required access to it. @end deftypefn @deftypefn {Built-in Function} void close (number @var{rd}) The argument @var{rd} is a resource descriptor returned by a previous call to @code{open}. The function @code{close} closes the resource and deallocates any memory associated with it. @code{close} will signal @code{e_range} exception if @var{rd} lies outside of allowed range of resource descriptors. @FIXME{More info on it} @end deftypefn Notice that you are not required to close resources opened by @code{open}. Any unclosed resource will be closed automatically upon the termination of the filtering program. The following functions provide basic read/write capabilities. @deftypefn {Built-in Function} void write (number @var{rd}, string @var{str} @ [, number @var{size}]) Writes the string @var{str} to the resource descriptor @var{rd}. If the @var{size} argument is given, writes this number of bytes. The function will signal @code{e_range} exception if @var{rd} lies outside of allowed range of resource descriptors, and @code{e_io} exception if an @acronym{I/O} error occurs. @end deftypefn @deftypefn {Built-in Function} string getline (number @var{rd}) Read and return the next newline-terminated string from the resource descriptor @var{rd}. The terminating newline character will be removed from the return value. The function will signal @code{e_range} exception if @var{rd} lies outside of allowed range of resource descriptors, and @code{e_io} exception if an @acronym{I/O} error occurs. @end deftypefn The following example shows how @command{mailfromd} @acronym{I/O} functions can be used to automatically add @acronym{IP} addresses to an @acronym{RBL} zone: @smallexample @group set nsupdate_cmd "/usr/bin/nsupdate -k /etc/bind/Kmail.+157+14657.private" func block_address(string addr) do number fd string domain set fd open "|%nsupdate_cmd" set domain revip(%addr) ".rbl.myzone.come" write(%fd, "prereq nxrrset %domain A\n" "update add %domain 86400 A %addr\n\n" done @end group @end smallexample @noindent The function @code{revip} is defined in @ref{revip}. @node System functions @subsubsection System functions @deftypefn {Built-in Function} number time () Return the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. @end deftypefn @anchor{strftime} @deftypefn {Built-in Function} string strftime (string @var{fmt}, @ number @var{timestamp}) @deftypefnx {Built-in Function} string strftime (string @var{fmt}, @ number @var{timestamp}, boolean @var{gmt}) Formats the time @var{timestamp} (seconds since the Epoch) according to the format specification @var{format}. Ordinary characters placed in the format string are copied to the output without conversion. Conversion specifiers are introduced by a @samp{%} character. @xref{Time and Date Formats}, for a detailed description of the conversion specifiers. We recommend using single quotes around @var{fmt} to prevent @samp{%} specifiers from being interpreted as @code{Mailfromd} variables (@xref{Literals}, for a discussion of quoted literals and variable interpretation within them). The @var{timestamp} argument can be a return value of @code{time} function (see above). For example: @smallexample @group strftime('%Y-%m-%d %H:%M:%S %Z', 1164477564) @result{} 2006-11-25 19:59:24 EET strftime('%Y-%m-%d %H:%M:%S %Z', 1164477564, 1) @result{} 2006-11-25 17:59:24 GMT @end group @end smallexample @end deftypefn @deftypefn {Built-in Function} number system (string @var{str}) The function @code{system} executes a command specified in @var{str} by calling @command{/bin/sh -c string}, and returns -1 on error or the return status of the command otherwise. @end deftypefn @deftypefn {Built-in Function} void sleep (number @var{seconds}) Sleep for @var{seconds}. This function is intended for debugging and experimental purposes. @end deftypefn @deftypefn {Built-in Function} number umask (number @var{mask}) Set the umask to @var{mask} & 0777. Return the previous value of the mask. @end deftypefn @node Sieve Interface @subsubsection Sieve Interface @cindex Sieve @samp{Sieve} is a powerful mail filtering language, defined in @acronym{RFC} 3028. @command{Mailfromd} supports an extended form of this language. For a description of the language and available extensions, @xref{Sieve Language, Sieve Language, Sieve Language, mailutils, GNU Mailutils Manual}. @deftypefn {Built-in Function} boolean sieve (string @var{script} @ [, number @var{flags}]) Compile the Sieve source file @var{script} and execute it over the collected message. This function can be used only in @code{eom} handler. @findex sieve.mfh Optional @var{flags} define additional debugging and verbosity settings. It is a bit-mask field, consisting of a bitwise @code{or} of one or more of the following flags, defined in @file{sieve.mfh}: @table @code @item MF_SIEVE_LOG Log every executed @samp{Sieve} action. @item MF_SIEVE_DEBUG_TRACE Trace execution of @samp{Sieve} tests. @item MF_SIEVE_DEBUG_INSTR Log every instruction, executed in the compiled @samp{Sieve} code. This produces huge amounts of output and is rarely useful, unless you suspect some bug in @samp{Sieve} implementation and wish to trace it. @item MF_SIEVE_DEBUG_MAILUTILS Log debugging information about the underlying Mailutils calls. @item MF_SIEVE_DEBUG_PROT Trace networking protocols. @end table For example, @code{MF_SIEVE_LOG|MF_SIEVE_DEBUG_TRACE} enables logging @samp{Sieve} actions and tests. The @code{sieve} function returns @code{true} if the message was accepted by the @var{script} program, and @code{false} otherwise. Here, the word @dfn{accepted} means that some form of @samp{KEEP} action (@pxref{Actions, keep, Actions, mailutils, GNU Mailutils Manual}) was executed over the message. @end deftypefn The following example discards each message not accepted by the @samp{Sieve} program @file{/etc/mail/filter.siv}: @smallexample #include_once group eom do if not sieve("/etc/mail/filter.siv", MF_SIEVE_LOG) discard fi done @end smallexample The example below illustrates how one can adjust logging flags depending on the current debugging level: @smallexample #include_once prog eom do number flags 0 number level debug_level("bi_sieve") if %level >= 1 set flags %flags | MF_SIEVE_LOG fi if %level >= 2 set flags %flags | MF_SIEVE_DEBUG_TRACE fi if %level > 9 set flags %flags | MF_SIEVE_DEBUG_INSTR fi if %level > 19 set flags %flags | MF_SIEVE_DEBUG_MAILUTILS fi if %level > 20 set flags %flags | MF_SIEVE_DEBUG_PROT fi if not sieve("/etc/mail/filter.siv", %flags) discard fi done @end smallexample @node Interfaces to Third-Party Programs @subsubsection Interfaces to Third-Party Programs A set of functions is defined for interfacing with other filters via @acronym{TCP}. Currently implemented are interfaces with @command{SpamAssassin} @command{spamd} daemon and with @command{ClamAV} antivirus. These functions can be used only in @code{eom} handler. Both interfaces work much the same way: the remote filter is connected and the message is passed to it. If the remote filter confirms that the message matches its requirements, the function returns @code{true}. Notice that in practice that means that such a message @emph{should be rejected or deferred}. The address of the remote filter is supplied as the first argument in the form of a standard @acronym{URL}: @smallexample @var{proto}://@var{path}[:@var{port}] @end smallexample @noindent The @var{proto} part specifies the @dfn{connection protocol}. It should be @samp{tcp} for the @acronym{TCP} connection and @samp{file} or @samp{socket} for the connection via @acronym{UNIX} socket. In the latter case the @var{proto} part can be omitted. When using @acronym{TCP} connection, the @var{path} part gives the remote host name or @acronym{IP} address and the optional @var{port} specifies the port number or service name to use. For example: @smallexample # @r{connect to @samp{remote.filter.net} on port 3314}: tcp://remote.filter.net:3314 # @r{the same, using symbolic service name (must be defined in # @file{/etc/services}):} tcp://remote.filter.net:spamd # @r{Connect via a local @acronym{UNIX} socket (equivalent forms):} /var/run/filter.sock file:///var/run/filter.sock socket:///var/run/filter.sock @end smallexample The description of the interface functions follows. @anchor{sa} @cindex SpamAssassin @cindex spamd @deftypefn {Built-in Function} boolean sa (string @var{url}, number @var{prec}) @deftypefnx {Built-in Function} boolean sa (string @var{url}, @ number @var{prec}, number @var{report}) Pass the message to the SpamAssassin daemon (@code{spamd}) at @var{url}. Return @code{true} if SpamAssassin considers it a spam, @code{false} otherwise. The second arguments, @var{prec}, gives the precision, in decimal digits, to be used when converting SpamAssassin diagnostic data and storing them into @command{mailfromd} variables. The floating point SpamAssassin data are converted to the integer @command{mailfromd} variables using the following relation: @smallexample @var{var} = int(@var{sa-var} * @var{prec}) @end smallexample @noindent where @var{sa-var} stands for the SpamAssassin value and @var{var} stands for the corresponding @command{mailfromd} one. @code{int()} means taking the integer part. Optional third argument, @var{report}, controls what kind of data is returned in the @code{sa_keywords} variable. See below for its description. The function returns additional information via the following variables: @table @code @cindex sa_score, global variable @item sa_score The spam score, converted to integer as described above. To convert it to a floating-point representation, use @code{sa_format_score} function (@pxref{String manipulation, sa_format_score}). See also the example below. @cindex sa_threshold, global variable @item sa_threshold The threshold, converted to integer form. @cindex sa_keywords, global variable @item sa_keywords If @var{report} is not supplied or is null, this variable contains a string of comma-separated SpamAssassin keywords identifying this message, e.g.: @smallexample ADVANCE_FEE_1,AWL,BAYES_99 @end smallexample Otherwise, if @var{report} is not null, the value of this variable is a @dfn{spam report} message. It is a multi-line textual message, containing detailed description of spam scores in a tabular form. It consists of the following parts: @enumerate @item A preamble. @item Content preview. The words @samp{Content preview}, followed by a colon and an excerpt of the message body. @item Content analysis details. It has the following form: @smallexample Content analysis details: (@var{score} points, @var{max} required) @end smallexample @noindent where @var{score} and @var{max} are spam score and threshold in floating point. @item Score table. The score table is formatted in three columns: @table @asis @item pts The score, as a floating point number with one decimal digit. @item rule name SpamAssassin rule name that contributed this score. @item description Textual description of the rule @end table The score table can be extracted from @code{sa_keywords} using @code{sa_format_report_header} function (@pxref{String manipulation, sa_format_report_header}), as illustrated in the example below. @end enumerate @end table The @code{sa} function can signal the following exceptions: @code{e_failure} if the connection fails, @code{e_url} if the supplied @acronym{URL} is invalid and @code{e_range} if the supplied port number is out of the range 1--65535. The simplest way to use the function is: @smallexample @group prog eom do if sa("tcp://192.168.10.1:3333", 3) reject 550 5.7.0 "Spam detected, score %sa_score with threshold %sa_threshold" fi done @end group @end smallexample Here is a more advanced example: @smallexample prog eom do set prec 3 if sa("tcp://192.168.10.1:3333", %prec, 1) add "X-Spamd-Status" "SPAM" else add "X-Spamd-Status" "OK" fi add "X-Spamd-Score" sa_format_score(%sa_score, %prec) add "X-Spamd-Threshold" sa_format_score(%sa_threshold, %prec) add "X-Spamd-Keywords" sa_format_report_header(%sa_keywords) done @end smallexample @end deftypefn @anchor{ClamAV} @cindex ClamAV @deftypefn {Built-in Function} boolean clamav (string @var{url}) @cindex clamav_virus_name, global variable Pass the message to the ClamAV daemon at @var{url}. Return @code{true} if it detects a virus in it. Return virus name in @code{clamav_virus_name} global variable. The @code{clamav} function can signal the following exceptions: @code{e_failure} if connection failed, @code{e_url} if the supplied @acronym{URL} is invalid and @code{e_range} if the supplied port number is out of the range 1--65535. An example usage: @smallexample @group prog eom do if clamav("tcp://192.168.10.1:6300") reject 550 5.7.0 "Infected with %clamav_virus_name" fi done @end group @end smallexample @end deftypefn @node Rate limiting functions @subsubsection Rate limiting functions @deftypefn {Built-in Function} number rate (string @var{key}, @ number @var{sample-interval}, @ [number @var{min-samples}, number @var{threshold}]) Returns the mail sending rate for @var{key} per @var{sample-interval}. Optional @var{min-samples}, if supplied, specifies the minimal number of mails needed to obtain the statistics. The default is 2. Optional @var{threshold} controls rate database updates. If the observed rate (per @var{sample-interval} seconds) is higher than the @var{threshold}, the hit counters for that key are not incremented and the database is not updated. Althouth the @var{threshold} argument is optional@footnote{It is made optional in order to provide backward compatibility with the releases of mailfromd prior to 5.0.93.}, its use is strongly encouraged. Normally, the value of @var{threshold} equals the value compared with the return from @var{rate}, as in: @smallexample @group if rate($f "-" $client_addr, %rate_interval, 4, %maxrate) > %maxrate tempfail 450 4.7.0 "Mail sending rate exceeded. Try again later" fi @end group @end smallexample This function is a low-level interface. Instead of using it directly, we advise to use the @code{rateok} function, described below. @end deftypefn @deftypefn {Library Function} boolean rateok (string @var{key}, @ number @var{sample-interval}, @ number @var{threshold}, [number @var{min-samples}]) @flindex rateok.mf To use this function, require @file{rateok.mf} module (@pxref{Modules}), e.g.: @code{#require rateok}. The @code{rateok} function returns @samp{True} if the mail sending rate for @var{key}, computed for the interval of @var{sample-interval} seconds is less than the @var{threshold}. Optional @var{min-samples} parameter supplies the minimal number of mails needed to obtain the statistics. It defaults to 4. @end deftypefn @xref{Sending Rate}, for a detailed description of the @code{rateok} and its use. The @code{interval} function (@pxref{interval}) is often used in the second argument to @code{rateok} or @code{rate}. @deftypefn {Built-in Function} boolean tbf_rate (string @var{key}, @ number @var{cost}, number @var{sample-interval}, number @var{burst-size}) This function implements a classical token bucket filter algorithm. Tokens are added to the bucket identified by the @var{key} at constant rate of 1 token per @var{sample-interval} microseconds, to a maximum of @var{burst-size} tokens. If no bucket is found for the specified key, a new bucket is created and initialized to contain @var{burst-size} tokens. If the bucket contains @var{cost} or more tokens, @var{cost} tokens are removed from it and @code{tbf_rate} returns @samp{True}. Otherwise, the function returns @samp{False}. For a detailed description of the Token Bucket Algorithm and its use to limit mail rates, see @ref{TBF}. @end deftypefn @node Greylisting functions @subsubsection Greylisting functions @deftypefn {Built-in Function} boolean greylist @ (string @var{key}, number @var{interval}) @cindex greylist_seconds_left, global variable Returns @samp{True} if the @var{key} is found in the greylist database (controlled by @code{#pragma database greylist} pragma, @pxref{database}). The argument @var{interval} gives the greylisting interval in seconds. The function stores the number of seconds left to the end of greylisting period in the internal variable @code{greylist_seconds_left}. @xref{Greylisting}, for a detailed explanation. The function @code{greylist} can signal @code{e_dbfailure} exception. @end deftypefn @deftypefn {Built-in Function} boolean is_greylisted (string @var{key} Returns @samp{True} if the @var{key} is still greylisted. This function is available only if Con Tassios implementation of greylisting is used. @xref{greylisting types}, for a discussion of available greylisting implementations. @xref{greylist}, for a way to switch to Con Tassios implementation. @end deftypefn @node Special test functions @subsubsection Special Test Functions @deftypefn {Built-in Function} boolean listens (string @var{host}, [number @var{port}]) Returns @code{true} if the @acronym{IP} address or host name given by @var{host} argument listens on the port number @var{port} (default 25). @end deftypefn @deftypefn {Built-in Function} boolean validuser (string @var{name}) Returns @code{true} if authenticity of the user @var{name} is confirmed using mailutils authentication system. @xref{Local Account Verification}, for more details. @end deftypefn @anchor{valid_domain} @deftypefn {Library Function} boolean valid_domain (string @var{domain}) Returns @code{true} if the domain name @var{domain} has a corresponding A record or if it has any @samp{MX} records, i.e. if it is possible to send mail to it. @flindex valid_domain.mf To use this function, require @file{valid_domain.mf} module (@pxref{Modules}): @smallexample #require valid_domain @end smallexample @end deftypefn @anchor{heloarg_test} @deftypefn {Library Function} number heloarg_test (string @var{arg}, @ string @var{remote_ip}, string @var{local_ip}) @flindex heloarg_test.mf Verify if an argument of @samp{HELO} (@samp{EHLO}) command is valid. To use this function, load @file{heloarg_test.mf} module (@pxref{Modules}). Arguments: @table @var @item arg @samp{HELO} (@samp{EHLO}) argument. Typically, the value of @code{$s} Sendmail macro; @item remote_ip @acronym{IP} address of the remote client. Typically, the value of @code{$client_addr} Sendmail macro; @item local_ip @acronym{IP} address of this @acronym{SMTP} server; @end table The function returns a number describing the result of the test, as described in the following table. @multitable @columnfractions 0.4 0.6 @headitem Code @tab Meaning @item HELO_SUCCESS @tab @var{arg} successfully passes all tests. @item HELO_MYIP @tab @var{arg} is our @acronym{IP} address. @item HELO_IPNOMATCH @tab @var{arg} is an @acronym{IP}, but it does not match the remote party @acronym{IP} address. @item HELO_ARGNORESOLVE @tab @var{arg} is an @acronym{IP}, but it does not resolve. @item HELO_ARGNOIP @tab @var{arg} is in square brackets, but it is not an @acronym{IP} address. @item HELO_ARGINVALID @tab @var{arg} is not an @acronym{IP} address and does not resolve to one. @item HELO_MYSERVERIP @tab @var{arg} resolves to our server @acronym{IP}. @item HELO_IPMISMATCH @tab @var{arg} does not resolve to the remote client @acronym{IP} address. @end multitable @end deftypefn @node Mail Sending Functions @subsubsection Mail Sending Functions The mail sending functions are new interfaces, introduced in version 3.1. The underlying mechanism for sending mail, called @dfn{mailer}, is specified by @option{--mailer} command line option. This global setting can be overridden using the last optional argument to a particular function. In any case, the mailer is specified in the form of a @acronym{URL}. @cindex @acronym{URL}, mailer @cindex mailer @acronym{URL} @anchor{mailer url} @dfn{Mailer @acronym{URL}} begins with a protocol specification. Two protocol specifications are currently supported: @samp{sendmail} and @samp{smtp}. The former means to use a @command{sendmail}-compatible program to send mails. Such a program must be able to read mail from its standard input and must support the following options: @table @option @item -oi Do not treat '.' as message terminator. @item -f @var{addr} Use @var{addr} as the address of the sender. @item -t Get recipient addresses from the message. @end table These conditions are met by most existing @acronym{MTA} programs, such as @command{exim} or @command{postfix} (to say nothing of @command{sendmail} itself). Following the protocol specification is the @dfn{mailer location}, which is separated from it with a colon. For the @samp{sendmail} protocol, the mailer location sets the full file name of the sendmail-compatible @acronym{MTA} binary, for example: @smallexample sendmail:/usr/sbin/sendmail @end smallexample A special form of a sendmail @acronym{URL}, consisting of protocol specification only (@samp{sendmail:}) is also allowed. It means ``use the sendmail binary from the @code{_PATH_SENDMAIL} macro in your @file{/usr/include/paths.h} file''. This is the default mailer. The @samp{smtp} protocol means to use an @acronym{SMTP} server directly. In this case the mailer location consists of two slashes, followed by the @acronym{IP} address or host name of the @acronym{SMTP} server, and, optionally, the port number. If the port number is present, it is separated from the rest of @acronym{URL} by a colon. For example: @smallexample @group smtp://remote.server.net smtp://remote.server.net:24 @end group @end smallexample @deftypefn {Built-in Function} void send_mail (string @var{msg}, @ string @var{to} [, string @var{from}, string @var{mailer}]) Sends message @var{msg} to the email address @var{to}. The value of @var{msg} must be a valid @acronym{RFC} 2822 message, consisting of headers and body. The @var{to} argument can contain several email addresses. In this case the message will be sent to each recipient specified in @var{to}. Optional arguments are: @table @var @item from Sets the sender address. By default @samp{<>} is used. @item mailer The @acronym{URL} of the mailer to use @end table Sample usage: @smallexample @group set message <<- EOT Subject: Test message To: Postmaster From: Mailfromd X-Agent: %__package__ (%__version__) Dear postmaster, This is to notify you that our /etc/mailfromd.rc needs a revision. -- Mailfromd filter administrator EOT send_mail(%message, "postmaster@@gnu.org.ua") @end group @end smallexample @end deftypefn @deftypefn {Built-in Function} void send_text (string @var{text}, @ string @var{headers}, string @var{to} @ [, string @var{from}, string @var{mailer}]) A more complex interface to mail sending functions. Mandatory arguments: @table @var @item text Text of the message to be sent. @item headers Headers for the message. @item to Recipient email address. @end table Optional arguments: @table @var @item from Sender email address. @item mailer @acronym{URL} of the mailer to use. @end table The above example can be rewritten using @code{send_text} as follows: @smallexample @group set headers << -EOT Subject: Test message To: Postmaster From: Mailfromd X-Agent: %__package__ (%__version__) EOT set text <<- EOT Dear postmaster, This is to notify you that our /etc/mailfromd.rc needs a revision. -- Mailfromd filter administrator EOT send_text(%text, %headers, "postmaster@@gnu.org.ua") @end group @end smallexample @end deftypefn @deftypefn {Built-in Function} void send_dsn (string @var{to}, @ string @var{sender}, string @var{rcpt}, string @var{text} @ [, string @var{headers}, string @var{from}, string @var{mailer}]) This is an experimental interface which will change in the future versions. It sends a message disposition notification (@acronym{RFC} 2298, @acronym{RFC} 1894), of type @samp{deleted} to the email address @var{to}. Arguments are: @table @var @item to Recipient email address. @item sender Original sender email address. @item rcpt Original recipient email address. @item text Notification text. @end table Optional arguments: @table @var @item headers Message headers @item from Sender address. @item mailer @acronym{URL} of the mailer to use. @end table @end deftypefn @node Blacklisting Functions @subsubsection Blacklisting Functions The functions described in this subsection allow to check whether the given @acronym{IP} address is listed in certain @dfn{black list} @acronym{DNS} zone. @anchor{match_dnsbl} @deftypefn {Library Function} boolean match_dnsbl (string @var{address}, @ string @var{zone}, string @var{range}) This function looks up @var{address} in the @acronym{DNS} blacklist zone @var{zone} and checks if the return falls into the given @var{range} of @acronym{IP} addresses. It is intended as a replacement for the Sendmail macros @samp{dnsbl} and @samp{enhdnsbl}. @flindex match_dnsbl.mf To use @code{match_dnsbl}, require @file{match_dnsbl.mf} module (@pxref{Modules}). Arguments: @table @var @item address @acronym{IP} address of the @acronym{SMTP} server to be tested. @item zone @acronym{FQDN} of the @acronym{DNS}bl zone to test against. @item range The range of @acronym{IP} addresses in @acronym{CIDR} notation or the word @samp{ANY}, which stands for @samp{127.0.0.0/8}. @end table The function returns @code{true} if dns lookup for @var{address} in the zone @var{dnsbl} yields an @acronym{IP} that falls within the range, specified by @var{cidr}. Otherwise, it returns @code{false}. This function raises the following exceptions: @code{e_invip} if @var{address} is invalid and @code{e_invcidr} if @var{cidr} is invalid. @end deftypefn @anchor{match_rhsbl} @deftypefn {Library Function} boolean match_rhsbl (string @var{email}, @ string @var{zone}, string @var{range}) This function checks if the @acronym{IP} address, corresponding to the domain part of @var{email} is listed in the @acronym{RHS DNS} blacklist zone @var{zone}, and if so, whether its record falls into the given range of @acronym{IP} addresses @var{range}. It is intended as a replacement for the Sendmail macro @samp{rhsbl} by Derek J. Balling. @flindex match_rhsbl.mf To use this function, require @file{match_rhsbl.mf} module (@pxref{Modules}). Arguments: @table @var @item email E-mail address, whose domain name should be tested (usually, it is @code{$f}) @item zone Domain name of the @acronym{RHS DNS} blacklist zone. @item range The range of @acronym{IP} addresses in @acronym{CIDR} notation. @end table @end deftypefn @node SPF Functions @subsubsection SPF Functions @cindex @acronym{SPF}, defined @cindex Sender Policy Framework, defined @dfn{Sender Policy Framework}, or @acronym{SPF} for short, is an extension to @acronym{SMTP} protocol that allows to identify forged identities supplied with the @code{MAIL FROM} and @code{HELO} commands. The framework is explained in detail in @acronym{RFC} 4408 (@uref{http://tools.ietf.org/html/rfc4408}) and on the @uref{http://www.openspf.org/, SPF Project Site}. The following description is a short introduction only, and the users are encouraged to refer to the original specification for the detailed description of the framework. The domain holder publishes an @dfn{SPF record} -- a special @acronym{DNS} resource record that contains a set of rules declaring which hosts are, and are not, authorized to use a domain name for @code{HELO} and @code{MAIL FROM} identities. This resource record is usually of type @code{TXT}.@footnote{Although @acronym{RFC} 4408 introduces a special @code{SPF} record type for this purpose, it is not yet widely used. As of version @value{VERSION}, @acronym{MFL} does not support @code{SPF} @acronym{DNS} records.} @cindex @acronym{SPF}, checking host record @cindex checking @acronym{SPF} host records @cindex @code{check_host} function, introduced The @acronym{MFL} script can verify if the identity matches the published @acronym{SPF} record by calling @code{check_host} function and analyzing its return code. The function can be called either in @code{helo} or in @code{envfrom} handler. Its arguments are: @table @var @item ip The @acronym{IP} address of the @acronym{SMTP} client that is emitting the mail. Usually it is @code{$client_addr}. @item domain The domain that provides the sought-after authorization information; Normally it is the domain portion of the @code{MAIL FROM} or @code{HELO} identity. @item sender The @code{MAIL FROM} identity. @item helo_domain The @code{HELO} identity. @item my_domain The @acronym{SMTP} domain served by the local server. @end table The function returns a numeric result code. For convenience, all possible return values are defined as macros in module @file{spf.mf}. The table below describes each value along with the recommended actions for it: @table @code @cindex None, SPF result code @item None A result of @code{None} means that no records were published by the domain or that no checkable sender domain could be determined from the given identity. The checking software cannot ascertain whether or not the client host is authorized. Such a message can be subject to further checks that will decide about its fate. @cindex Neutral, SPF result code @item Neutral The domain owner has explicitly stated that he cannot or does not want to assert whether or not the @acronym{IP} address is authorized. This result must be treated exactly like @code{None}; the distinction between them exists only for informational purposes @cindex Pass, SPF result code @item Pass The client is authorized to send mail with the given identity. The message can be subject to further policy checks with confidence in the legitimate use of the identity or it can be accepted in the absence of such checks. @cindex Fail, SPF result code @item Fail The client is not authorized to use the domain in the given identity. The proper action in this case can be to mark the message with a header explicitly stating it is spam, or to reject it outright. If you choose to reject such mails, we suggest to use @code{reject 550 5.7.1}, as recommended by @acronym{RFC} 4408. The reject can return either a default explanation string, or the one supplied by the domain that published the SPF records, as in the example below: @smallexample reject 550 5.7.1 "SPF check failed:\n%spf_explanation" @end smallexample @noindent (see below for the description of @code{spf_explanation} variable.) @cindex SoftFail, SPF result code @item SoftFail The domain believes the host is not authorized but is not willing to make that strong of a statement. This result code should be treated as somewhere in between a @code{Fail} and a @code{Neutral}. It is not recommended to reject the message based solely on this result. @item TempError A transient error occurred while performing @acronym{SPF} check. The proper action in this case is to accept or temporarily reject the message. If you choose the latter, we suggest to use @acronym{SMTP} reply code of @samp{451} and DSN code @samp{4.4.3}, for example: @smallexample tempfail 451 4.4.3 "Transient error while performing SPF verification" @end smallexample @item PermError This result means that the domain's published records could not be correctly interpreted. This signals an error condition that requires manual intervention to be resolved, as opposed to the @code{TempError} result. @end table The following example illustrates the use of @acronym{SPF} verification in @code{envfrom} handler: @smallexample #include_once #require spf prog envfrom do switch check_host($client_addr, domainpart($f), $f, $s) do case Fail: string text "" if %spf_explanation != "" set text %text "\n" %spf_explanation fi reject 550 5.7.1 "SPF MAIL FROM check failed" %text case Pass: accept case TempError: tempfail 451 4.4.3 "Transient error while performing SPF verification" default: on poll $f do when success: accept when not_found or failure: reject 550 5.1.0 "Sender validity not confirmed" when temp_failure: tempfail 450 4.7.0 "Temporary failure during sender verification" done done done @end smallexample The @acronym{SPF} support is implemented in @acronym{MFL} in two layers: a built-in layer that provides basic support, and a library layer that implements result caching. @flindex spf.mf The library layer is implemented in @file{spf.mf} module (@pxref{Modules}). The rest of this node describes available @acronym{SPF} functions and variables. @deftypefn {Built-in Function} number spf_check_host (string @var{ip}, @ string @var{domain}, string @var{sender}, string @var{helo_domain}, @ string @var{my_domain}) This function is the basic implementation of the @code{check_host} function, defined in @acronym{RFC} 4408, chapter 4. It fetches @acronym{SPF} records, parses them, and evaluates them to determine whether a particular host (@var{ip}) is or is not permitted to send mail from a given email address (@var{sender}). The function returns an @dfn{SPF result code}. Arguments are: @table @var @item ip The @acronym{IP} address of the @acronym{SMTP} client that is emitting the mail. Usually it is @code{$client_addr}. @item domain The domain that provides the sought-after authorization information; Normally it is the domain portion of the @code{MAIL FROM} or @code{HELO} identity. @item sender The @code{MAIL FROM} identity. @item helo_domain The @code{HELO} identity. @item my_domain The @acronym{SMTP} domain served by the local server. @end table @anchor{spf-globals} Before returning the @code{spf_check_host} function stores additional information in global variables: @table @code @item spf_explanation If the result code is not @code{Pass}, this variable contains the explanation string as returned by the publishing domain, prefixed with the value of the global variable @code{spf_explanation_prefix}. For example, if @code{spf_explanation_prefix} contains @samp{The domain %@{o@} explains: }, and the publishing domain @samp{example.com} returns the explanation string @samp{Please see http://www.example.com/mailpolicy.html}, than the value of @code{spf_explanation} will be: @smallexample @group The domain example.com explains: Please see http://www.example.com/mailpolicy.html @end group @end smallexample (see @uref{http://tools.ietf.org/html/rfc4408, @acronym{RFC} 4408}, chapter 8, for the description of @acronym{SPF} macro facility). @item spf_mechanism Set to the name of a @acronym{SPF} mechanism that decided about the result code of the @acronym{SPF} record. @item spf_ttl Set to the minimum interval of time, in seconds, during which it is safe to cache the result value. This value is used by @code{check_host} function. @end table @end deftypefn @deftypefn {Built-in Function} number spf_test_record (string @var{record}, @ string @var{ip}, string @var{domain}, string @var{sender}, @ string @var{helo_domain}, string @var{my_domain}) Evaluate @acronym{SPF} record @var{record} as if it were published by @var{domain}. The rest of arguments are the same as for @code{spf_check_host} above. This function is designed primarily for testing and debugging purposes. You would hardly need to use it. The @code{spf_test_record} function sets the same global variables as @code{spf_check_host}. @end deftypefn @deftypefn {Library Function} number check_host (string @var{ip}, @ string @var{domain}, string @var{sender}, string @var{helo}) This function implements the @code{check_host} function, defined in @acronym{RFC} 4408, chapter 4. It fetches @acronym{SPF} records, parses them, and evaluates them to determine whether a particular host (@var{ip}) is or is not permitted to send mail from a given email address (@var{sender}). The function returns an @dfn{SPF result code}. This function differs from the built-in @code{spf_check_host} in that it implements caching of the results, thereby reducing network traffic. The arguments are: @table @var @item ip The @acronym{IP} address of the @acronym{SMTP} client that is emitting the mail. Usually it is the same as the value of @code{$client_addr}. @item domain The domain that provides the sought-after authorization information; Normally it is the domain portion of the @code{MAIL FROM} or @code{HELO} identity. @item sender The @code{MAIL FROM} identity. @item helo The @code{HELO} identity. @end table Before returning, the @code{check_host} function stores additional information in the same global variables, as @code{spf_check_host}. @xref{spf-globals, the list}, for details. In addition, it sets the variable @code{spf_cached} to @samp{1} if cached data were used, or to @samp{0} otherwise. @end deftypefn @deftypefn {Library Function} string spf_status_string (number @var{code}) Converts numeric @acronym{SPF} result @var{code} to its string representation. @end deftypefn @deftypevar {Built-in variable} string spf_explanation If the result code of @code{check_host} (or @code{spf_check_host} or @code{spf_test_record} function is not @code{Pass}, this variable contains the explanation string as returned by the publishing domain, prefixed with the value of the global variable @code{spf_explanation_prefix}. For example, if @code{spf_explanation_prefix} contains @samp{The domain %@{o@} explains: }, and the publishing domain @samp{example.com} returns the explanation string @samp{Please see http://www.example.com/mailpolicy.html}, than the value of @code{spf_explanation} will be: @smallexample @group The domain example.com explains: Please see http://www.example.com/mailpolicy.html @end group @end smallexample @end deftypevar @deftypevar {Built-in variable} string spf_mechanism Set to the name of a @acronym{SPF} mechanism that decided about the result code of the @acronym{SPF} record. @end deftypevar @deftypevar {Built-in variable} number spf_ttl Set to the minimum interval of time, in seconds, during which it is safe to cache the result value. This value is used by @code{check_host} function. @end deftypevar @deftypevar {Built-in variable} string spf_explanation_prefix The prefix to be appended to the explanation string before storing it in the @code{spf_explanation} variable. This string can contain valid @acronym{SPF} macros (see @uref{http://tools.ietf.org/html/rfc4408, @acronym{RFC} 4408}, chapter 8), for example: @smallexample set spf_explanation_prefix "%@{o@} explains: " @end smallexample The default value is @samp{""} (an empty string). @end deftypevar @deftypevar {Library variable} string spf_database Sets the full name of @acronym{DBM} file used to cache the results of the @acronym{SPF} functions. By default is is @file{@code{%__statedir__/spf.db}}. @end deftypevar @deftypevar {Library variable} number spf_negative_ttl Sets the interval of time during which negative replies (result code @code{None}) will be stored in the database. By default it is 1 day. @end deftypevar @deftypevar {Library variable} number spf_cached Set by @code{check_host} function to @samp{1} if the function made the decision based on the cached data, or to @samp{0} otherwise. @end deftypevar @node NLS Functions @subsubsection National Language Support Functions @cindex @acronym{NLS} @cindex National Language Support The @dfn{National Language Support} functions allow you to write your scripts in such a way, that any textual messages they display are automatically translated to your native language, or, more precisely, to the language required by your current locale. @cindex internationalization @cindex i18n @cindex localization @cindex l10n This section assumes the reader is familiar with the concepts of program @dfn{internationalization} and @dfn{localization}. If not, please refer to @ref{Why, The Purpose of GNU @command{gettext}, The Purpose of GNU @command{gettext}, gettext, GNU gettext manual}, before reading further. @flindex nls.mf In general, internationalization of any @acronym{MFL} script follows the same rules as described in the @cite{GNU gettext manual}. First of all, you select the program @dfn{message domain}, i.e. the identifier of a set of translatable messages your script contain. This identifier is then used to select appropriate translation. The message domain is set using @code{textdomain} function. For the purposes of this section, let's suppose the domain name is @samp{myfilter}. All @acronym{NLS} functions are provided by @file{nls.mf} module, so you must require this module prior to using any of them. To find translations of textual message to the current locale, the underlying @command{gettext} mechanism will look for file @file{@var{dirname}/@var{locale}/LC_MESSAGES/@var{domainname}.mo}, where @var{dirname} is the message catalog hierarchy name, @var{locale} is the locale name, and @var{domainname} is the name of the message domain. By default @var{dirname} is @file{/usr/local/share/locale}, but you may change it using @code{bindtextdomain} function. The right place for this initial @acronym{NLS} setup is in the @samp{begin} block (@pxref{begin/end}). To summarize all the above, the usual @acronym{NLS} setup will look like: @smallexample #require nls begin do textdomain("myfilter") bindtextdomain("myfilter", "/usr/share/locale"); done @end smallexample For example, given the settings above, and supposing the environment variable @env{LC_ALL} is set to @samp{pl}, translations will be looked in file @file{/usr/share/locale/pl/LC_MESSAGES/myfilter.mo}. Once this preparatory work is done, you can request each message to be translated by using @code{gettext} function, or @code{_} (underscore) macro. For example, the following statement will produce translated textual description for @samp{450} response: @smallexample tempfail 450 4.1.0 _("Try again later") @end smallexample Of course it assumes that the appropriate @file{myfile.mo} file already exists. If it does not, nothing bad happens: in this case the macro @command{_} (as well as @code{gettext} function) will simply return its argument unchanged, so that the remote party will get the textual message in English. The @samp{mo} files are binary files created from @samp{po} source files using @command{msgfmt} utility, as described in @ref{Binaries, Producing Binary MO Files, Producing Binary MO Files, gettext, GNU gettext manual}. In turn, the format of @samp{po} files is described in @ref{PO Files, The Format of PO Files, The Format of PO Files, gettext, GNU gettext manual}. @deftypefn {Built-in Function} string bindtextdomain (string @var{domain}, @ string @var{dirname}) This function sets the base directory of the hierarchy containing message catalogs for a given message domain. @var{domain} is a string identifying the textual domain. If it is not empty, the base directory for message catalogs belonging to domain @var{domain} is set to @var{dirname}. It is important that @var{dirname} be an absolute pathname; otherwise it cannot be guaranteed that the message catalogs will be found. If @var{domain} is @samp{""}, @code{bindtextdomain} returns the previously set base directory for domain @var{domain}. @end deftypefn The rest of this section describes the @acronym{NLS} functions supplied by the @file{nls.mf} module. @deftypefn {Built-in Function} string dgettext (string @var{domain}, @ string @var{msgid}) @code{dgettext} attempts to translate the string @var{msgid} into the currently active locale, according to the settings of the textual domain @var{domain}. If there is no translation available, @code{dgettext} returns @var{msgid} unchanged. @end deftypefn @deftypefn {Built-in Function} string dngettext @ (string @var{domain}, string @var{msgid}, string @var{msgid_plural}, @ number @var{n}) The @code{dngettext} functions attempts to translate a text string into the language specified by the current locale, by looking up the appropriate singular or plural form of the translation in a message catalog, set for the textual domain @var{domain}. @xref{Plural forms, Additional functions for plural forms, Additional functions for plural forms, gettext, GNU gettext utilities}, for a discussion of the plural form handling in different languages. @end deftypefn @deftypefn {Library Function} string textdomain (string @var{domain}) The @code{textdomain} function sets the current message domain to @var{domain}, if it is not empty. In any case the function returns the current message domain. The current domain is @samp{mailfromd} initially. For example, the following sequence of @code{textdomain} invocations will yield: @smallexample textdomain("") @result{} "mailfromd" textdomain("myfilter") @result{} "myfilter" textdomain("") @result{} "myfilter" @end smallexample @end deftypefn @deftypefn {Library Function} string gettext (string @var{msgid}) @code{gettext} attempts to translate the string @var{msgid} into the currently active locale, according to the settings of the current textual domain (set using @code{textdomain} function). If there is no translation available, @code{gettext} returns @var{msgid} unchanged. @end deftypefn @deftypefn {Library Function} string ngettext @ (string @var{msgid}, string @var{msgid_plural}, number @var{n}) The @code{ngettext} functions attempts to translate a text string into the language specified by the current locale, by looking up the appropriate singular or plural form of the translation in a message catalog, set for the current textual domain. @xref{Plural forms, Additional functions for plural forms, Additional functions for plural forms, gettext, GNU gettext utilities}, for a discussion of the plural form handling in different languages. @end deftypefn @node Debugging Functions @subsubsection Debugging Functions These functions allow to enable debugging and tracing for a certain piece of code. @deftypefn {Built-in Function} void debug (string @var{spec}) Enable debugging. The value of @var{spec} sets the debugging level. @xref{debugging level specification}, for a description of its format. @end deftypefn @deftypefn {Built-in Function} number debug_level ([string @var{srcname}]) This function returns the debugging level currently in effect for the source module @var{srcname}, or the global debugging level, if called without arguments. For example, if the program was started with @option{--debug=20,@/engine=8} option, then: @smallexample debug_level() @result{} 20 debug_level("engine") @result{} 8 debug_level("db") @result{} 0 @end smallexample @end deftypefn @deftypefn {Built-in Function} string debug_spec ([string @var{srcnames}]) Returns the current debugging level specification, as given by @option{--debug} command line option or by @code{#pragma option debug} statement. If the argument @var{srcnames} is specified, it is treated as a comma-separated list of source names for which the debugging specification is to be returned. For example, if @command{mailfromd} was started with @option{--debug=20,@/spf=50,@/engine=8,@/db=30} option, then: @smallexample debug_spec("all,engine") @result{} "20,engine=8" debug_spec("engine,db") @result{} "db=30,engine=8" @end smallexample @noindent When called without arguments, @code{debug_spec} returns full debugging level specification, as shown in the example below: @smallexample debug_spec() @result{} "20,debug=0,cache=0,dnscache=0,db=30,dns=0,dnsbase=0,engine=8, gram=0,lex=0,main=0,mf-status=0,mu_dbm=0,optab=0,prog=0, spf=50,stack=0,symtab=0,rate=0,bi_db=0,bi_dns=98,bi_io=0, bi_ipaddr=0,bi_mail=0,bi_poll=0,bi_sa=0,bi_spf=0,bi_string=7, bi_system=0,bi_other=0,bi_vars=0" @end smallexample @end deftypefn These three functions are intended to complement each other. The calls to @code{debug} can be placed around some piece of code you wish to debug, to enable specific debugging information for this code fragment only. For example: @smallexample @group /* @r{Save debugging level for @file{dns.c} source} */ set dlev debug_level("dns") /* @r{Set new debugging level} */ debug("dns=80") . . . /* @r{Restore previous level} */ debug("dns=%dlev") @end group @end smallexample You can also change debugging levels for several modules simultaneously: @smallexample @group /* @r{Save debugging specifications for the sources we are} * @r{interested in:} */ set dspec debug_spec("dns,dnsbase,db") /* @r{Set new debugging spec} */ debug("dns=80,dnsbase=100,db=1") . . . /* @r{Restore previous debug specification} */ debug("%dspec") @end group @end smallexample @deftypefn {Built-in Function} void program_trace (string @var{module}) Enable tracing for a set of modules given in @var{module} argument. @xref{--trace-program}, for a description of its format. @end deftypefn @deftypefn {Built-in Function} void cancel_program_trace (string @var{module}) Disable tracing for given modules. @end deftypefn This pair of functions is also designed to be used together in a bracket-like fashion. They are useful for debugging @command{mailfromd}, but are not advised to use otherwise, since tracing slows down the execution considerably. @deftypefn {Built-in Function} void stack_trace () Generate a stack trace in this point. @xref{tracing runtime errors}, for the detailed description of stack traces. @end deftypefn @node User-defined @subsection User-Defined Functions Complicated filter scripts can often be simplified and made more manageable by defining new functions. @cindex function definition, syntax of The function definitions can appear anywhere between the handler declarations in a filter program. The only requirement is that the function definition occurs before the place where the function is invoked. The definition of a function named @var{name} looks like this: @cindex @code{returns} statement, function definition @cindex @code{func} statement, function definition @smallexample @group func @var{name} (@var{param-decl}) returns @var{data-type} do @var{function-body} done @end group @end smallexample @noindent @var{name} is the name of the function to define, @var{param-decl} is a comma-separated list of parameter declarations. The syntax of the latter is the same as that of variable declarations (@pxref{Variables, Variable declarations}), i.e.: @smallexample @var{type} @var{name} @end smallexample @noindent declares the parameter @var{name} having the type @var{type}. The @var{type} is @code{string} or @code{number}. For example, the following declares a function @samp{sum}, that takes two numeric arguments and returns a numeric value: @smallexample func sum(number x, number y) returns number @end smallexample Parameters are referenced in the @var{function-body} by their name, using the syntax for variable references: @code{%@var{name}}. The value of a parameter can be altered using @code{set} statement, the same way as for variables. @cindex optional arguments to a function @cindex arguments, optional A function can be declared to take a certain number of @dfn{optional arguments}. In function declaration, optional abstract arguments must be placed after the mandatory ones, and must be separated from them with a semicolon. The following example is a definition of function @code{foo}, which takes two mandatory and two optional arguments: @smallexample func foo(string msg, string email; number x, string pfx) @end smallexample @noindent @cindex $#, special construct @cindex function arguments, getting the number of @cindex function arguments, counting @cindex number of actual arguments @cindex @@@var{var}, special construct @cindex argument number in the list of arguments Mandatory arguments are: @code{msg} and @code{email}. Optional arguments are: @code{x} and @code{pfx}. The actual number of parameters supplied to the function is returned by a special construct @code{$#}. In addition, the special construct @code{@@@var{arg}} evaluates to the ordinal number of variable @var{arg} in the list of formal parameters (the first argument has number @samp{0}). These two constructs can be used to verify whether an argument is supplied to the function. @cindex optional arguments, checking if supplied The actual parameter for argument @code{n} is supplied if the number of actual parameters (@code{$#}) is greater than its ordinal number in the declaration list (@code{@@@var{n}}). So, to check if an optional argument @var{arg} is supplied, the following condition can be used: @smallexample func foo(string msg, string email; number x, string arg) do if $# > @@arg @dots{} fi @end smallexample The default @command{mailfromd} installation provides a special macro for this purpose: @pxref{defined}. Using it, the example above could be rewritten as: @smallexample func foo(string msg, string email; number x, string arg) do if defined(arg) @dots{} fi @end smallexample Within a function body, optional arguments are referenced exactly the same way as the mandatory ones. Attempt to dereference an optional argument for which no actual parameter was supplied, results in an undefined value, so be sure to check whether a parameter is passed before dereferencing it. @anchor{variadic functions} @cindex variadic function @cindex variable number of arguments A function can also take variable number of arguments (such functions are called @dfn{variadic}). This is indicated by the use of ellipsis as the last abstract argument. The statement below defines a funtion @code{foo} taking one mandatory, one optional and any number of additional arguments: @smallexample func foo (string a ; string b, ...) @end smallexample All actual arguments passed in a list of variable arguments are coerced to string data type. To refer to these arguments in the function body, the following construct is used: @smallexample $(@var{expr}) @end smallexample @noindent where @var{expr} is any valid @acronym{MFL} expression, evaluating to a number @var{n}. This construct refers to the value of @var{n}th actual parameter from the variable argument list. Parameters are numbered from @samp{1}, so the first variable parametr is @code{$(1)}, and the last one is @code{$($# - @var{Nm} - @var{No})}, where @var{Nm} and @var{No} are numbers of mandatory and optional arguments to the function. For example, the function below prints all its arguments: @smallexample func pargs (string text, ...) do echo "text=%text" loop for number i 1, while %i <= $# - 1, set i %i + 1 do echo "arg %i=" $(%i) done done @end smallexample @noindent Note the loop limits. The last variable argument has number @code{$# - 1}, because the function takes one mandatory argument. @cindex return statement, defined The @var{function-body} is any list of valid @command{mailfromd} statements. In addition to the statements discussed below (@pxref{Statements}) it can also contain the @code{return} statement, which is used to return a value from the function. The syntax of the return statement is @smallexample return @var{value} @end smallexample As an example of this, consider the following code snippet that defines the function @samp{sum} to return a sum of its two arguments: @smallexample @group func sum(number x, number y) returns number do return %x + %y done @end group @end smallexample @cindex procedures @cindex function returning void @cindex void functions The @code{returns} part in the function declaration is optional. A declaration lacking it defines a @dfn{procedure}, or @dfn{void function}, i.e. a function that is not supposed to return any value. Such functions cannot be used in expressions, instead they are used as statements (@pxref{Statements}). The following example shows a function that emits a customized temporary failure notice: @smallexample @group func stdtf() do tempfail 451 4.3.5 "Try again later" done @end group @end smallexample @anchor{function alias} @cindex aliases @kwindex alias A function may have several names. An alernative name (or @dfn{alias}) can be assigned to a function by using @code{alias} keyword, placed after @var{param-decl} part, for example: @smallexample func foo() alias bar returns string do @dots{} done @end smallexample After this declaration, both @code{foo()} and @code{bar()} will refer to the same function. The number of function aliases is unlimited. The following fragment declares a function having three names: @smallexample func foo() alias bar alias baz returns string do @dots{} done @end smallexample Although this feature is rarely needed, there are sometimes cases when it may be necessary. @cindex automatic variables @cindex variables, local @cindex local variables @cindex variables, automatic A variable declared within a function becomes a local variable to this function. Its lexical scope ends with the terminating @code{done} statement. Parameters, local variables and global variables are using separate namespaces, so a parameter name can coincide with the name of a global, in which case a parameter is said to @dfn{shadow} the global. All references to its name will refer to the parameter, until the end of its scope is reached, where the global one becomes visible again. Consider the following example: @smallexample @group number x func foo(string x) do echo "foo: %x" done prog envfrom do set x "Global" foo("Local") echo %x done @end group @end smallexample @noindent Running @command{mailfromd --test} with this configuration will display: @smallexample @cartouche foo: Local Global @end cartouche @end smallexample @anchor{func-old-style} @cindex function declaration, old style For compatibility with previous versions, @command{mailfromd} also supports the @dfn{legacy} format of function declarations: @smallexample func @var{name} (@var{param-types}) returns @var{rettype} @end smallexample @noindent Here, @var{param-types} is a comma-separated list of parameter types. The following abbreviations can be used: @samp{s} for @code{string} and @samp{n} for numeric. The same holds true for @var{rettype} as well. @anchor{positional parameter} @cindex positional parameters, in functions The parameters declared this way are called @dfn{positional parameters}. The function can access its actual arguments using the notation @code{$@var{n}}, where @var{n} is the ordinal number of the argument@footnote{Well, to tell you the truth, you can access named arguments using positional notation as well. But such a mixing of styles is not recommended.}. Arguments are counted from left to right. The first argument is @code{$1}. Using this syntax, the above definition of sum would look like: @smallexample @group func sum(n, n) returns n do return $1 + $2 done @end group @end smallexample @menu * Some Useful Functions:: @end menu @node Some Useful Functions @subsubsection Some Useful Functions To illustrate the concept of user-defined functions, this subsection shows definitions of some of the library functions shipped with @command{mailfromd}. These functions are contained in modules installed along with the @command{mailfromd} binary. To use any of them in your code, require the appropriate module as described in @ref{require, #require statement}, e.g. to use the @code{revip} function, do @code{#require revip}. Functions and their definitions: @enumerate 1 @cindex revip, definition of @item @code{revip}@* The function @code{revip} (@pxref{revip}) is implemented as follows: @smallexample func revip(string ip) returns string do return inet_ntoa(ntohl(inet_aton(%ip))) done @end smallexample Previously it was implemented using regular expressions. Below we include this variant as well, as an illustration for the use of regular expressions: @smallexample @group #pragma regex push +extended func revip(string ip) returns string do if %ip matches '([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)' return "\4.\3.\2.\1" fi return %ip done #pragma regex pop @end group @end smallexample @cindex strip_domain_part, definition of @item @code{strip_domain_part}@* This function returns at most @var{n} last components of the domain name @var{domain} (@pxref{strip_domain_part}). @smallexample @group #pragma regex push +extended func strip_domain_part(string domain, number n) returns string do if %n = 0 return domainpart %domain elif domainpart(%domain) matches '.*((\.[^.]+)@{' $2 '@})' return substring(\1, 1, -1) else return %domain fi done #pragma regex pop @end group @end smallexample @cindex valid_domain, definition @item @code{valid_domain}@* @xref{valid_domain}, for a description of this function. Its definition follows: @smallexample @group #require dns func valid_domain(string domain) returns number do return not (resolve(%domain) = "0" and not hasmx(%domain)) done @end group @end smallexample @cindex match_dnsbl, definition @item @code{match_dnsbl}@* The function @code{match_dnsbl} (@pxref{match_dnsbl}) is defined as follows: @smallexample #require dns #require match_cidr #pragma regex push +extended func match_dnsbl(string address, string zone, string range) returns number do string rbl_ip if %range = 'ANY' set rbl_ip '127.0.0.0/8' else set rbl_ip %range if not %range matches '^([0-9]@{1,3@}\.)@{3@}[0-9]@{1,3@}$' return 0 fi fi if not (%address matches '^([0-9]@{1,3@}\.)@{3@}[0-9]@{1,3@}$' and %address != %range) return 0 fi if %address matches '^([0-9]@{1,3@})\.([0-9]@{1,3@})\.([0-9]@{1,3@})\.([0-9]@{1,3@})$' if match_cidr (resolve ("\4.\3.\2.\1", %zone), %rbl_ip) return 1 else return 0 fi fi # never reached done @end smallexample @end enumerate @node Expressions @section Expressions @cindex expressions Expressions are language constructs, that evaluate to a value, that can subsequently be echoed, tested in a conditional statement, assigned to a variable or passed to a function. @menu * Constant expressions:: String and Numeric Constants. * Function calls:: A Function Call is an Expression. * Concatenation:: Adjacent Expressions Concatenate. * Arithmetic operations:: @samp{+}, @samp{-}, etc. * Relational expressions:: @samp{=}, @samp{<}, etc. * Special comparisons:: @code{matches}, @code{mx matches}, etc. * Boolean expressions:: @code{and}, @code{or}, @code{not}. * Precedence:: How various operators nest. * Type casting:: @end menu @node Constant expressions @subsection Constant Expressions Literals and numbers are @dfn{constant expressions}. They evaluate to string and numeric types. @node Function calls @subsection Function Calls A function call is an expression. Its type is the return type of the function. @node Concatenation @subsection Concatenation @cindex concatenation Any two adjacent expressions are converted to string type and concatenated, producing a new string. Thus, if @code{$f} is @samp{smith}, and @code{$client_addr} is @samp{10.10.1.1}, then: @smallexample $f "-" $client_addr @result{} "smith-10.10.1.1" @end smallexample This feature is often used in filter scripts to generate key values for database lookup functions. @node Arithmetic operations @subsection Arithmetic Operations The filter script language offers the common arithmetic operators: @samp{+}, @samp{-}, @samp{*} and @samp{/}. All of them follow usual precedence rules and work as you would expect them to. @node Relational expressions @subsection Relational Expressions Relational expressions are: @cindex @code{<} (left angle bracket), @code{<} operator @cindex left angle bracket (@code{<}), @code{<} operator @cindex @code{<} (left angle bracket), @code{<=} operator @cindex left angle bracket (@code{<}), @code{<=} operator @cindex @code{>} (right angle bracket), @code{>=} operator @cindex right angle bracket (@code{>}), @code{>=} operator @cindex @code{>} (right angle bracket), @code{>} operator @cindex right angle bracket (@code{>}), @code{>} operator @cindex @code{=} (equals sign), @code{=} operator @cindex equals sign (@code{=}), @code{=} operator @cindex @code{!} (exclamation point), @code{!=} operator @cindex exclamation point (@code{!}), @code{!=} operator @float Table,table-relational-expr @caption{Relational Expressions} @multitable @columnfractions .25 .75 @headitem Expression @tab Result @item @var{x} @code{<} @var{y} @tab True if @var{x} is less than @var{y}. @item @var{x} @code{<=} @var{y} @tab True if @var{x} is less than or equal to @var{y}. @item @var{x} @code{>} @var{y} @tab True if @var{x} is greater than @var{y}. @item @var{x} @code{>=} @var{y} @tab True if @var{x} is greater than or equal to @var{y}. @item @var{x} @code{=} @var{y} @tab True if @var{x} is equal to @var{y}. @item @var{x} @code{!=} @var{y} @tab True if @var{x} is not equal to @var{y}. @end multitable @end float The relational expressions apply to string as well as to numbers. When a relational operation applies to strings, case-sensitive comparison is used, e.g.: @smallexample @group "String" = "string" @result{} False "String" < "string" @result{} True @end group @end smallexample @node Special comparisons @subsection Special Comparisons In addition to the traditional relational operators, described above, @command{mailfromd} provides two operators for regular expression matching: @kwindex matches @kwindex fnmatches @cindex regular expression matching @cindex globbing patterns @float Table,table-special-comp-expr @caption{Regular Expression Matching} @multitable @columnfractions .25 .75 @headitem Expression @tab Result @item @var{x} @code{matches} @var{y} @tab True if the string @var{x} matches the regexp denoted by @var{y}. @item @var{x} @code{fnmatches} @var{y} @tab True if the string @var{x} matches the globbing pattern denoted by @var{y}. @end multitable @end float The type of the regular expression used by @code{matches} operator is controlled by @code{#pragma regex} (@pxref{pragma regex}). For example: @smallexample @group $f @result{} "gray@@gnu.org.ua" $f matches '.*@@gnu\.org\.ua' @result{} @code{true} $f matches '.*@@GNU\.ORG\.UA' @result{} @code{false} #pragma regex +icase $f matches '.*@@GNU\.ORG\.UA' @result{} @code{true} @end group @end smallexample The @code{fnmatches} operator compares its left-hand operand with a globbing pattern (see @cite{glob(7)}) given as its right-hand side operand. For example: @smallexample @group $f @result{} "gray@@gnu.org.ua" $f fnmatches "*ua" @result{} @code{true} $f fnmatches "*org" @result{} @code{false} $f fnmatches "*org*" @result{} @code{true} @end group @end smallexample @cindex mx matches Both operators have a special form, for @dfn{@samp{MX} pattern matching}. The expression: @smallexample @var{x} mx matches @var{y} @end smallexample @noindent is evaluated as follows: first, the expression @var{x} is analyzed and, if it is an email address, its domain part is selected. If it is not, its value is used verbatim. Then the list of @samp{MX}s for this domain is looked up. Each of @samp{MX} names is then compared with the regular expression @var{y}. If any of the names matches, the expression returns true. Otherwise, its result is false. @cindex mx fnmatches Similarly, the expression: @smallexample @var{x} mx fnmatches @var{y} @end smallexample @noindent returns true only if any of the @samp{MX}s for (domain or email) @var{x} match the globbing pattern @var{y}. Both @code{mx matches} and @code{mx fnmatches} can signal the following exceptions: @code{e_temp_failure}, @code{e_failure}. The value of any parenthesized subexpression occurring within the right-hand side argument to @code{matches} or @code{mx matches} can be referenced using the notation @samp{\@var{d}}, where @var{d} is the ordinal number of the subexpression (subexpressions are numbered from left to right, starting at 1). This notation is allowed in the program text as well as within double-quoted strings and here-documents, for example: @smallexample @group if $f matches '.*@@\(.*\)\.gnu\.org\.ua' set message "Your host name is \1;" fi @end group @end smallexample Remember that the grouping symbols are @samp{\(} and @samp{\)} for basic regular expressions, and @samp{(} and @samp{)} for extended regular expressions. Also make sure you properly escape all special characters (backslashes in particular) in double-quoted strings, or use single-quoted strings to avoid having to do so (@pxref{singe-vs-double}, for a comparison of the two forms). @node Boolean expressions @subsection Boolean Expressions @cindex and @cindex or @cindex not A @dfn{boolean expression} is a combination of relational or matching expressions using the boolean operators @code{and}, @code{or} and @code{not}, and, eventually, parentheses to control nesting: @float table, table boolean-expr @caption{Boolean Operators} @multitable @columnfractions .25 .75 @headitem Expression @tab Result @item @var{x} @code{and} @var{y} @tab True only if both @var{x} and @var{y} are true. @item @var{x} @code{or} @var{y} @tab True if any of @var{x} or @var{y} is true. @item @code{not} @var{x} @tab True if @var{x} is false. @end multitable @end float Binary boolean expressions are computed using @dfn{shortcut evaluation}: @table @code @item @var{x} and @var{y} If @code{@var{x} @result{} @code{false}}, the result is @code{false} and @var{y} is not evaluated. @item @var{x} or @var{y} If @code{@var{x} @result{} @code{true}}, the result is @code{true} and @var{y} is not evaluated. @end table @node Precedence @subsection Operator Precedence @cindex operator precedence, defined @cindex precedence, operators Operator @dfn{precedence} is an abstract value associated with each language operator, that determines the order in which operators are executed when they appear together within a single expression. Operators with higher precedence are executed first. For example, @samp{*} has a higher precedence than @samp{+}, therefore the expression @code{a + b * c} is evaluated in the following order: first @code{b} is multiplied by @code{c}, then @code{a} is added to the product. @cindex operator associativity @cindex associativity, operators When operators of equal precedence are used together they are evaluated from left to right (i.e., they are @dfn{left-associative}), except for comparison operators, which are non-associative (these are explicitly marked as such in the table below). This means that you cannot write: @smallexample if 5 <= %x <= 10 @end smallexample @noindent Instead, you should write: @smallexample if 5 <= %x and %x <= 10 @end smallexample The precedences of the @command{mailfromd} operators where selected so as to match that used in most programming languages.@footnote{The only exception is @samp{not}, whose precedence in @acronym{MFL} is much lower than usual (in most programming languages it has the same precedence as unary @samp{-}). This allows to write conditional expressions in more understandable manner. Consider the following condition: @smallexample if not %x < 2 and %y = 3 @end smallexample It is understood as ``if @code{x} is not less than 2 and @code{y} equals 3'', whereas with the usual precedence for @samp{not} it would have meant ``if negated @code{x} is less than 2 and @code{y} equals 3''.} The following table lists all operators in order of decreasing precedence: @table @code @item (...) Grouping @item $ % @command{Sendmail} macros and @command{mailfromd} variables @item * / Multiplication, division @item + - Addition, subtraction @item < <= >= > Relational operators (non-associative) @item = != matches fnmatches Equality and special comparison (non-associative) @item & Logical (bitwise) @sc{and} @item ^ Logical (bitwise) @sc{xor} @item | Logical (bitwise) @sc{or} @item not Boolean negation @item and Logical @samp{and}. @item or Logical @samp{or} @item String Concatenation There is no special operator, the operands are simply written side by side (@pxref{Concatenation}). @end table @node Type casting @subsection Type Casting When two operands on each side of a binary expression have different type, @command{mailfromd} evaluator has to coerce them to a common type. This is known as @dfn{implicit type casting}. The rules for implicit type casting are: @enumerate 1 @item Both arguments to an arithmetical operation are cast to numeric type. @item Both arguments to the concatenation operation are cast to string. @item Both arguments to `match' or `fnmatch' function are cast to string. @item The argument of the unary negation (arithmetical or boolean) is cast to numeric. @item Otherwise the right-hand side argument is cast to the type of the left-hand side argument. @end enumerate There is no special syntactic sugar for explicit type casting. However you can use the latter rule to make sure an expression is of desired type: to cast an expression to string, concatenate an empty string to it, e.g.: @smallexample "" %var @end smallexample Similarly, to cast an expression to numeric, add zero to it: @smallexample 0 + %var @end smallexample @node Shadowing @section Variable and Constant Shadowing @cindex shadowing, defined @cindex name clashes When any two named entities happen to have the same name we say that a @dfn{name clash} occurs. The handling of name clashes depends on types of the entities involved in it. @subheading function -- any A name of a constant or variable can coincide with that of a function, it does not produce any warnings or errors because functions, variables and constants use different namespaces. For example, the following code is correct: @smallexample const a 4 func a() do echo %a done @end smallexample When executed, it prints @samp{4}. @subheading function -- function, handler -- function, and function -- handler Redefinition of a function or using a predefined handler name (@pxref{Handlers}) as a function name results in a fatal error. For example, compiling this code: @smallexample func a() do echo "1" done func a() do echo "2" done @end smallexample @noindent causes the following error message: @smallexample mailfromd: sample.mf:9: syntax error, unexpected FUNCTION_PROC, expecting IDENTIFIER @end smallexample @subheading handler -- variable A variable name can coincide with a handler name. For example, the following code is perfectly OK: @smallexample string envfrom "M" prog envfrom do echo %envfrom done @end smallexample @subheading handler -- handler If two handlers with the same name are defined, the definition that appears further in the source text replaces the previous one. A warning message is issued, indicating locations of both definitions, e.g.: @smallexample mailfromd: sample.rc:116: Warning: Redefinition of handler `envfrom' mailfromd: sample.rc:34: Warning: This is the location of the previous definition @end smallexample @subheading variable -- variable @cindex variable shadowing @cindex shadowing, variable Defining a variable having the same name as an already defined one results in a warning message being displayed. The compilation succeeds. The second variable @dfn{shadows} the first, that is any subsequent references to the variable name will refer to the second variable. For example: @smallexample string x "Text" number x 1 prog envfrom do echo %x done @end smallexample Compiling this code results in the following diagnostics: @smallexample mailfromd: sample.mf:4: Redeclaring `x' as different data type mailfromd: sample.mf:2: This is the location of the previous definition @end smallexample Executing it prints @samp{1}, i.e. the value of the last definition of @code{x}. The scope of the shadowing depends on storage classes of the two variables. If both of them have external storage class (i.e. are global ones), the shadowing remains in effect until the end of input. In other words, the previous definition of the variable is effectively forgotten. If the previous definition is a global, and the shadowing definition is an automatic variable or a function parameter, the scope of this shadowing ends with the scope of the second variable, after which the previous definition (global) becomes visible again. Consider the following code: @smallexample set x "initial" func foo(string x) returns string do return %x done prog envfrom do echo foo("param") echo %x done @end smallexample Its compilation produces the following warning: @smallexample mailfromd: sample.mf:3: Warning: Parameter `x' is shadowing a global @end smallexample When executed, it produces the following output: @smallexample param initial State envfrom: continue @end smallexample @anchor{variable--constant shadowing} @subheading variable -- constant @cindex shadowing, variable--constant If a constant is defined which has the same name as a previously defined variable (the constant @dfn{shadows} the variable), the compiler prints the following diagnostic message: @smallexample @var{file}:@var{line}: Warning: Constant name `@var{name}' clashes with a variable name @var{file}:@var{line}: Warning: This is the location of the previous definition @end smallexample A similar diagnostics is issued if a variable is defined whose name coincides with a previously defined constant (the variable shadows the constant). In any case, any subsequent notation %@var{name} refers to the last defined symbol, be it variable or constant. Notice, that shadowing occurs only when using %@var{name} notation. Referring to the constant using its name without @samp{%} allows to avoid shadowing effects. If a variable shadows a constant, the scope of the shadowing depends on the storage class of the variable. For automatic variables and function parameters, it ends with the final @code{done} closing the function. For global variables, it lasts up to the end of input. For example, consider the following code: @smallexample const a 4 func foo(string a) do echo %a done prog envfrom do foo(10) echo %a done @end smallexample When run, it produces the following output: @smallexample $ mailfromd --test sample.mf mailfromd: sample.mf:3: Warning: Variable name `a' clashes with a constant name mailfromd: sample.mf:1: Warning: This is the location of the previous definition 10 4 State envfrom: continue @end smallexample @subheading constant -- constant @cindex shadowing, constant--constant Redefining a constant produces a warning message. The latter definition shadows the former. Shadowing remains in effect until the end of input. @node Statements @section Statements @cindex statements Statements are language constructs, that, unlike expressions, do not return any value. Statements execute some actions, such as assigning a value to a variable, or serve to control the execution flow in the program. @menu * Actions:: Actions control the handling of the mail. * Assignments:: * Pass:: * Echo:: @c Return statement:: @c Conditionals @c Exception handlers @end menu @node Actions @subsection Action Statements @cindex actions An @dfn{action} statement instructs @command{mailfromd} to perform a certain action over the message being processed. There are two kinds of actions: return actions and header manipulation actions. Return actions tell @command{Sendmail} to return given response code to the remote party. There are five such actions: @table @code @item accept @cindex accept action, defined @kwindex accept Return an @code{accept} reply. The remote party will continue transmitting its message. @item reject [@var{code}] [@var{excode}] [@var{message}] @cindex reject action, defined @kwindex reject Return a @code{reject} reply. The remote party will have to cancel transmitting its message. The three arguments are optional, their usage is described below. @item tempfail [@var{code}] [@var{excode}] [@var{message}] @cindex tempfail action, defined @kwindex tempfail Return a @samp{temporary failure} reply. The remote party can retry to send its message later. The three arguments are optional, their usage is described below. @item discard @cindex discard action, defined @kwindex discard Instructs @command{Sendmail} to accept the message and silently discard it without delivering it to any recipient. @item continue @cindex continue action, defined @kwindex continue Stops the current handler and instructs @command{Sendmail} to continue processing of the message. @end table @anchor{reject} Two actions, @code{reject} and @code{tempfail} can take up to three optional parameters. The first argument is a three-digit @acronym{RFC} 2821 reply code. It must begin with @samp{5} for @code{reject} and with @samp{4} for @code{tempfail}. If two arguments are supplied, the second argument must be either an @dfn{extended reply code} (@acronym{RFC} 1893/2034) or a textual string to be returned along with the @acronym{SMTP} reply. Finally, if all three arguments are supplied, then the second one must be an extended reply code and the third one must give the textual string. The following examples illustrate the possible ways of using the @code{reject} statement: @smallexample @group reject reject 503 reject 503 5.0.0 reject 503 "Need HELO command" reject 503 5.0.0 "Need HELO command" @end group @end smallexample @anchor{header manipulation} @cindex header manipulation actions @cindex actions, header manipulation Header manipulation actions provide basic means to add, delete or modify the message @acronym{RFC} 2822 headers. @table @command @item add @var{name} @var{string} @cindex add action, defined @kwindex add Add the header @var{name} with the value @var{string}. E.g.: @smallexample add "X-Seen-By" "Mailfromd @value{VERSION}" @end smallexample @noindent (notice argument quoting) @item replace @var{name} @var{string} @cindex replace action, defined @kwindex replace The same as @code{add}, but if the header @var{name} already exists, it will be removed first, for example: @smallexample replace "X-Last-Processor" "Mailfromd @value{VERSION}" @end smallexample @item delete @var{name} @cindex delete action, defined @kwindex delete Delete the header named @var{name}: @smallexample delete "X-Envelope-Date" @end smallexample @end table These actions impose some restrictions. First of all, their first argument must be a literal string (not a variable or expression). Secondly, there is no way to select a particular header instance to delete or replace, which may be necessary to properly handle multiple headers (e.g. @samp{Received}). For more elaborate ways of header modifications, @ref{Header modification functions}. @node Assignments @subsection Variable Assignments @cindex assignment, defined @cindex variable assignment @kwindex set An @dfn{assignment} is a special statement that assigns a value to the variable. It has the following syntax: @smallexample set @var{name} @var{value} @end smallexample @noindent where @var{name} is the variable name and @var{value} is the value to be assigned to it. Assignment statements can appear in any part of a filter program. If an assignment occurs outside of function or handler definition, the @var{value} must be a literal value (@pxref{Literals}). If it occurs within a function or handler definition, @var{value} can be any valid @command{mailfromd} expression (@pxref{Expressions}). In this case, the expression will be evaluated and its value will be assigned to the variable. For example: @smallexample @group set delay 150 prog envfrom do set delay %delay * 2 @dots{} done @end group @end smallexample @node Pass @subsection The @code{pass} statement @kwindex pass The @code{pass} statement has no effect. It is used in places where no statement is needed, but the language syntax requires one: @smallexample @group on poll $f do when success: pass when not_found or failure: reject 550 done @end group @end smallexample @node Echo @subsection The @code{echo} statement @kwindex echo @cindex debugging The @command{echo} statement concatenates all its arguments into a single string and sends it to the @command{syslog} using the priority @samp{info}. It is useful for debugging your script, in conjunction with built-in constants (@pxref{Built-in constants}), for example: @smallexample @group func foo(number x) do echo "%__file__:%__line__: foo called with arg %x" @dots{} done @end group @end smallexample @node Conditionals @section Conditional Statements @cindex conditional statements @cindex statements, conditional @dfn{Conditional expressions}, or conditionals for short, test some conditions and alter the control flow depending on the result. There are two kinds of conditional statements: @dfn{if-else} branches and @dfn{switch} statements. @kwindex if @kwindex elif @kwindex else @kwindex fi The syntax of an @dfn{if-else} branching construct is: @smallexample if @var{condition} @var{then-body} [else @var{else-body}] fi @end smallexample @noindent Here, @var{condition} is an expression that governs control flow within the statement. Both @var{then-body} and @var{else-body} are lists of @command{mailfromd} statements. If @var{condition} is true, @var{then-body} is executed, if it is false, @var{else-body} is executed. The @samp{else} part of the statement is optional. The condition is considered false if it evaluates to zero, otherwise it is considered true. For example: @smallexample @group if $f = "" accept else reject fi @end group @end smallexample @noindent This will accept the message if the value of the @command{Sendmail} macro @code{$f} is an empty string, and reject it otherwise. Both @var{then-body} and @var{else-body} can be compound statements including other @code{if} statements. Nesting level of conditional statements is not limited. To facilitate writing complex conditional statements, the @code{elif} keyword can be used to introduce alternative conditions, for example: @smallexample @group if $f = "" accept elif $f = "root" echo "Mail from root!" else reject fi @end group @end smallexample @anchor{switch} @kwindex switch @kwindex case @cindex @code{switch} statement @cindex @code{case}, @code{switch} statement Another type of branching instruction is @code{switch} statement: @smallexample @group switch @var{condition} do case @var{x1} [or @var{x2} @dots{}]: @var{stmt1} case @var{y1} [or @var{y2} @dots{}]: @var{stmt2} . . . [default: @var{stmt}] done @end group @end smallexample @noindent Here, @var{x1}, @var{x2}, @var{y1}, @var{y2} are literal expressions; @var{stmt1}, @var{stmt2} and @var{stmt} are arbitrary @command{mailfromd} statements (possibly compound); @var{condition} is the controlling expression. The vertical dotted row represent another eventual @samp{case} branches. This statement is executed as follows: the @var{condition} expression is evaluated and if its value equals @var{x1} or @var{x2} (or any other @var{x} from the first @code{case}), then @var{stmt1} is executed. Otherwise, if @var{condition} evaluates to @var{y1} or @var{y2} (or any other @var{y} from the second @code{case}), then @var{stmt2} is executed. Other @code{case} branches are tried in turn. If none of them matches, @var{stmt} (called the @dfn{default branch}) is executed. There can be as many @code{case} branches as you wish. The @code{default} branch is optional. There can be at most one @code{default} branch. An example of @code{switch} statement follows: @smallexample @group switch %x do case 1 or 3: add "X-Branch" "1" accept case 2 or 4 or 6: add "X-Branch" "2" default: reject done @end group @end smallexample If the value of @command{mailfromd} variable @code{x} is 2 or 3, it will accept the message immediately, and add a @samp{X-Branch: 1} header to it. If @code{x} equals 2 or 4 or 6, this code will add @samp{X-Branch: 2} header to the message and will continue processing it. Otherwise, it will reject the message. The controlling condition of a @code{switch} statement may evaluate to numeric or string type. The type of the condition governs the type of comparisons used in @code{case} branches: for numeric types, numeric equality will be used, whereas for string types, string equality is used. @node Loops @section Loop Statements @kwindex loop @kwindex while @cindex loop statement The loop statement allows for repeated execution of a block of code, controlled by some conditional expression. It has the following form: @smallexample @group loop [@var{label}] [for @var{stmt1},] [while @var{expr1},] [@var{stmt2}] do @var{stmt3} done [while @var{expr2}] @end group @end smallexample @noindent where @var{stmt1}, @var{stmt2}, and @var{stmt3} are statement lists, @var{expr1} and @var{expr2} are expressions. The control flow is as follows: @enumerate 1 @item If @var{stmt1} is specified, execute it. @item Evaluate @var{expr1}. If it is zero, go to 6. Otherwise, continue. @item Execute @var{stmt3}. @item If @var{stmt2} is supplied, execute it. @item If @var{expr2} is given, evaluate it. If it is zero, go to 6. Otherwise, go to 2. @item End. @end enumerate Thus, @var{stmt3} is executed until either @var{expr1} or @var{expr2} yield a zero value. @cindex loop body The @dfn{loop body} -- @var{stmt3} -- can contain special statements: @table @code @kwindex break @cindex break statement @item break [@var{label}] Terminates the loop immediately. Control passes to @samp{6} (End) in the formal definition above. If @var{label} is supplied, the statement terminates the loop statement marked with that label. This allows to break from nested loops. It is similar to @code{break} statement in @sc{c} or shell. @kwindex next @cindex next statement @item next [@var{label}] Initiates next iteration of the loop. Control passes to @samp{2} in the formal definition above. If @var{label} is supplied, the statement starts next iteration of the loop statement marked with that label. This allows to request next iteration of an upper-level loop from a nested loop statement. @end table The @code{loop} statement can be used to create iterative statements of arbitrary complexity. Let's illustrate it in comparison with @sc{c}. @cindex infinite loop @cindex loop, infinite The statement: @smallexample @group loop do @var{stmt-list} done @end group @end smallexample @noindent creates an infinite loop. The only way to exit from such a loop is to call @code{break} (or @code{return}, if used within a function), somewhere in @var{stmt-list}. @cindex loop, while-style @cindex while loop The following statement is equivalent to @code{while (@var{expr1}) @var{stmt-list}} in @sc{c}: @smallexample @group loop while @var{expr} do @var{stmt-list} done @end group @end smallexample @cindex loop, for-style @cindex for loop The @sc{c} construct @code{for (@var{expr1}; @var{expr2}; @var{expr3})} is written in @acronym{MFL} as follows: @smallexample @group loop for @var{stmt1}, while @var{expr2}, @var{stmt2} do @var{stmt3} done @end group @end smallexample For example, to repeat @var{stmt3} 10 times: @smallexample @group loop for set i 0, while %i < 10, set i %i + 1 do @var{stmt3} done @end group @end smallexample @cindex loop, do-style @cindex do loop Finally, the @sc{c} @samp{do} loop is implemented as follows: @smallexample @group loop do @var{stmt-list} done while @var{expr} @end group @end smallexample As a real-life example of a loop statement, let's consider the implementation of function @code{ptr_validate}, which takes a single argument @var{ipstr}, and checks its validity using the following algorithm: Perform a @acronym{DNS} reverse-mapping for @var{ipstr}, looking up the corresponding @code{PTR} record in @samp{in-addr.arpa}. For each record returned, look up its @acronym{IP} addresses (A records). If @var{ipstr} is among the returned @acronym{IP} addresses, return 1 (@code{true}), otherwise return 0 (@code{false}). The implementation of this function in @acronym{MFL} is: @smallexample #pragma regex push +extended func ptr_validate(string ipstr) returns number do loop for string names dns_getname(%ipstr) " " number i index(%names, " "), while %i != -1, set names substr(%names, %i + 1) set i index(%names, " ") do loop for string addrs dns_getaddr(substr(%names, 0, %i)) " " number j index(%addrs, " "), while %j != -1, set addrs substr(%addrs, %j + 1) set j index(%addrs, " ") do if %ipstr == substr(%addrs, 0, %j) return 1 fi done done return 0 done @end smallexample @node Exceptions @section Exceptional Conditions @cindex exceptions, defined When the running program encounters a condition it is not able to handle, it signals an @dfn{exception}. To illustrate the concept, let's consider the execution of the following code fragment: @smallexample @group if primitive_hasmx domainpart $f accept fi @end group @end smallexample @noindent The function @code{primitive_hasmx} (@pxref{primitive_hasmx}) tests whether the domain name given as its argument has any @samp{MX} records. It should return a boolean value. However, when querying the Domain Name System, it may fail to get a definite result. For example, the @acronym{DNS} server can be down or temporary unavailable. In other words, @code{primitive_hasmx} can be in a situation when, instead of returning @samp{yes} or @samp{no}, it has to return @samp{don't know}. That is exactly then when it signals an @dfn{exception}. @anchor{status.mfh} @cindex exception types @cindex @file{status.mfh}, header file @cindex exceptions, symbolic names Exceptions are identified by @dfn{exception types}, the decimal numbers associated with them. The header file @file{status.mfh} defines @dfn{symbolic exception names} for each of these. The following table summarizes all the exception types implemented by @command{mailfromd} version @value{VERSION}: @table @code @cindex e_dbfailure, exception type @item e_dbfailure General database failure. For example, the database cannot be opened. This exception can be signaled by any function that queries any @acronym{DBM} database. @cindex e_divzero, exception type @item e_divzero Division by zero. @cindex e_failure, exception type @cindex failure, exception type @item e_failure @itemx failure @itemx e_failure A general failure has occurred. In particular, this exception is signaled by @acronym{DNS} lookup functions when any permanent failure occurs. This exception can be signaled by any @acronym{DNS}-related function (@code{hasmx}, @code{poll}, etc.) or operation (@code{mx matches}). @cindex e_invcidr, exception type @item e_invcidr Invalid @acronym{CIDR} notation. This is signaled by @code{match_cidr} function when its second argument is not a valid @acronym{CIDR}. @cindex e_invip, exception type @item e_invip Invalid @acronym{IP} address. This is signaled by @code{match_cidr} function when its first argument is not a valid @acronym{IP} address. @cindex e_invtime, exception type @item e_invtime Invalid time interval specification. It is signaled by @code{interval} function if its argument is not a valid time interval (@pxref{time interval specification}). @cindex e_io, exception type @item e_io An error occurred during the input-output operation. @xref{I/O functions}, for a description of functions that can signal this exception. @cindex e_macroundef, exception type @item e_macroundef A Sendmail macro is undefined. @cindex e_noresolve, exception type @item e_noresolve The argument of a @acronym{DNS}-related function cannot be resolved to host name or @acronym{IP} address. Currently only @code{ismx} (@pxref{ismx}) raises this exception. @cindex e_range, exception type @item e_range The supplied argument is outside the allowed range. This is signalled, for example, by @code{substring} function (@pxref{substring}). @cindex e_regcomp, exception type @item e_regcomp Regular expression cannot be compiled. This can happen when a regular expression (a right-hand argument of a @code{matches} operator) is built at the runtime and the produced string is an invalid regex. @cindex e_ston_conv, exception type @item e_ston_conv String-to-number conversion failed. This can be signaled when a string is used in numeric context which cannot be converted to the numeric data type. For example: @smallexample @group set x "10a" if %x / 2 @dots{} @end group @end smallexample @noindent The @code{if} condition will signal @code{ston_conv}, since @samp{10a} cannot be converted to a number. @cindex e_temp_failure, exception type @cindex temp_failure, exception type @item e_temp_failure @itemx temp_failure @itemx e_temp_failure A temporary failure has occurred. This can be signaled by @acronym{DNS}-related functions or operations. @cindex e_url, exception type @item e_url The supplied @acronym{URL} is invalid. @xref{Interfaces to Third-Party Programs}. @end table @cindex success, exception type @cindex e_success, exception type @cindex not_found, exception type @cindex e_not_found, exception type In addition to these, two symbols are defined that are not exception types in the strict sense of the world, but are provided to make writing filter scripts more convenient. These are @code{success}, meaning successful return from a function, and @code{not_found}, meaning that the required entity (e.g. domain name or email address) was not found. @xref{figure-poll-wrapper}, for an illustration on how these can be used. For consistency with other exception codes, these can be spelled as @code{e_success} and @code{e_not_found}. @cindex exceptions, default handling @cindex default exception handling Normally when an exception is signalled, the program execution is terminated and the @acronym{MTA} is returned a @code{tempfail} status. Additional information regarding the exception is then output to the logging channel (@pxref{Logging and Debugging}). However, the user can intercept any exception by installing his own exception-handling routines. @cindex @code{catch} statement @cindex exception-handling routines @cindex exception handlers @kwindex catch An exception-handling routine is introduced by @code{catch} statement, which has the following syntax: @smallexample @group catch @var{exception-list} do @var{handler-body} done @end group @end smallexample @noindent where @var{exception-list} is the list of exception types, separated by the word @code{or}. A special form @samp{*}, which stands for all exceptions, is allowed as well. The @var{handler-body} is the list of statements comprising the handler body. For example, the code below installs a handler for exceptions 2 (@samp{e_failure}) and 3 (@samp{e_temp_failure}): @smallexample @group catch 2 or 3 do @dots{} done @end group @end smallexample @noindent @anchor{exception symbolic names} @cindex @file{status.mfh}, usage However, using numeric exception codes is not convenient and is not in fact recommended. We recommend to use exception symbolic names instead. These are declared in the header file @file{status.mfh}, which should be included in your startup script. Using this approach, the above code snippet will look like: @smallexample @group #include catch e_failure or e_temp_failure do @dots{} done @end group @end smallexample @cindex scope of exception handlers @cindex scope of a @code{catch} @cindex @code{catch} scope @cindex exception handler scope The @code{catch} statement can appear anywhere inside a function or a handler, but it cannot appear outside of them. It can also be nested within another @code{catch}. Each exception redefined by a catch remains in force until either another catch appears further in the same function or handler that redefines it or an end of the containing block is encountered, whichever occurs first. Upon exit from a function or milter handler, all exceptions are restored to the state they had when it has been entered. @cindex returning from a catch @cindex returning from an exception handler @cindex @code{catch}, returning from @cindex exception handler, returning from @cindex @code{catch} arguments @cindex arguments, @code{catch} Upon entry to a @code{catch} code, it receives two positional arguments, which can be referenced in @var{handler-body} as @code{$1} and @code{$2}. The first argument gives the numeric code of the exception that has occurred. The second argument is a textual string containing a human-readable description of the exception. A @code{catch} defined within a function must return from it by executing @code{return} statement. If it does not do that explicitly, the default value of 1 is returned. A @code{catch} defined within a milter handler must end execution with any of the following actions: @code{accept}, @code{continue}, @code{discard}, @code{reject}, @code{tempfail}. By default, @code{continue} is used. The following example shows an @code{envfrom} handler that catches eventual exceptions, signaled by @code{primitive_hasmx}. The handler accepts the message if the sender domain has any @samp{MX} records, rejects them if it does not, and continues execution if an exception occurs. In the latter case, a log message is also issued: @smallexample @group #include prog envfrom do catch e_failure or e_temp_failure do echo "Caught exception $1: $2" continue done if primitive_hasmx domainpart $f accept else reject fi done @end group @end smallexample @cindex @code{hasmx}, definition of the function The following example defines the function @code{hasmx} that returns true if the domain part of its argument has any @samp{MX} records, and false if it does not or if an exception occurs @footnote{This function is part of the @code{mailfromd} library, @xref{hasmx}.}. @smallexample @group func hasmx (s) returns n do catch * do return 0 done return primitive_hasmx domainpart $1 done @end group @end smallexample @cindex @code{catch}, accessing variables from @cindex variables, accessing from @code{catch} @cindex accessing variables from @code{catch} All variables remain visible within @code{catch} body, with the exception of positional arguments of the enclosing function or handler. So, if you wish to access function arguments from a @code{catch}, define your function using new style (@pxref{User-defined}) declaration. To access positional arguments of a handler, you will have to assign them to local variables prior to installing a catch, e.g.: @smallexample @group prog header do string hname $1 string hvalue $2 catch * do echo "Exception $1 while processing header %hname: %hvalue" echo $2 tempfail done @dots{} @end group @end smallexample @anchor{throw} @cindex exceptions, raising from code @cindex raising exceptions @kwindex throw You can also generate (or @dfn{raise}) exceptions explicitly in the filter code, using @code{throw} statement: @smallexample throw @var{excode} @var{descr} @end smallexample The arguments correspond exactly to the positional arguments of the @code{catch} statement: @var{excode} gives the numeric code of the exception, @var{descr} gives its textual description. This statement can be used in complex scripts to create non-local exits from deeply nested statements. @FIXME{Elaborate on that.} Notice several limitations of @code{throw}: first, the @var{excode} argument must be an immediate value, you cannot use an expression in its place. Secondly, its range is limited to exception codes, described in @ref{status.mfh}. In other words, you cannot (yet) invent your own exception types. @FIXME{This should be fixed in future releases.} @node Polling @section Sender Verification Tests @cindex sender verification, writing tests The filter script language provides a wide variety of functions for sender address verification or @dfn{polling}, for short. These functions, which were described in @ref{Polling functions}, can be used to implement any sender verification method. The additional data that can be needed is normally supplied by two global variables: @code{ehlo_domain}, keeping the default domain for the @code{EHLO} command, and @code{mailfrom_address}, which stores the sender address for probe messages (@pxref{Predefined variables}). For example, a simplest way to implement standard polling would be: @smallexample prog envfrom do if stdpoll($1, %ehlo_domain, %mailfrom_address) == 0 accept else reject 550 5.1.0 "Sender validity not confirmed" fi done @end smallexample However, this does not take into account exceptions that @code{stdpoll} can signal. To handle them, one will have to use @code{catch}, for example thus: @smallexample #include prog envfrom do catch failure or temp_failure do switch $1 do case failure: reject 550 5.1.0 "Sender validity not confirmed" case temp_failure: tempfail 450 4.1.0 "Try again later" done done if stdpoll($1, %ehlo_domain, %mailfrom_address) == 0 accept else reject 550 5.1.0 "Sender validity not confirmed" fi done @end smallexample If polls are used often, one can define a wrapper function, and use it instead. The following example illustrates this approach: @float Figure, figure-poll-wrapper @caption{Building Poll Wrappers} @smallexample func poll_wrapper(string email) returns number do catch failure or temp_failure do return %email done return stdpoll(%email, %ehlo_domain, %mailfrom_address) done prog envfrom do switch poll_wrapper($f) do case success: accept case not_found or failure: reject 550 5.1.0 "Sender validity not confirmed" case temp_failure: tempfail 450 4.1.0 "Try again later" done done @end smallexample @end float Notice the way @code{envfrom} handles @code{success} and @code{not_found}, which are not exceptions in the strict sense of the word. @cindex @code{on} statement @cindex @code{when} keyword The above paradigm is so common that @command{mailfromd} provides a special language construct to simplify it: the @code{on} statement. Instead of manually writing the wrapper function and using it as a @code{switch} condition, you can rewrite the above example as: @float Figure, figure-stdpoll @caption{Standard poll example} @smallexample @group prog envfrom do on stdpoll($1, %ehlo_domain, %mailfrom_address) do when success: accept when not_found or failure: reject 550 5.1.0 "Sender validity not confirmed" when temp_failure: tempfail 450 4.1.0 "Try again later" done done @end group @end smallexample @end float @noindent As you see the statement is pretty similar to @code{switch}. The major syntactic differences are: @enumerate 1 @item Use of the keyword @code{when} to introduce conditional branches; @item The ampersand before exception names is optional; @end enumerate General syntax of the @code{on} statement is: @smallexample @group on @var{condition} do when @var{x1} [or @var{x2} @dots{}]: @var{stmt1} when @var{y1} [or @var{y2} @dots{}]: @var{stmt2} . . . done @end group @end smallexample @noindent The @var{condition} is either a function call or a special @code{poll} statement (see below). The values used in @code{when} branches are normally symbolic exception names (@pxref{exception symbolic names}). When the compiler processes the @code{on} statement it does the following: @enumerate 1 @item Builds a unique wrapper function, similar to that described in @ref{figure-poll-wrapper}; The name of the function is constructed from the @var{condition} function name and an unsigned number, called @dfn{exception mask}, that is unique for each combination of exceptions used in @code{when} branches; To avoid name clashes with the user-defined functions, the wrapper name begins and ends with @samp{$} which normally is not allowed in the identifiers; @item Translates the @code{on} body to the corresponding @code{switch} statement; @end enumerate @anchor{poll} @cindex @code{poll} keyword @cindex @code{poll} statement, defined A special form of the @var{condition} is @code{poll} keyword, whose syntax is: @smallexample @group poll [for] @var{email} [host @var{host}] [from @var{domain}] [as @var{email}] @end group @end smallexample The order of particular keywords in the @code{poll} statement is arbitrary, for example @code{as @var{email}} can appear before @var{email} as well as after it. @cindex @code{poll} command, standard verification @cindex standard verification with @code{poll} The simplest form, @code{poll @var{email}}, performs the standard sender verification of email address @var{email}. It is translated to the following function call: @smallexample stdpoll(@var{email}, %ehlo_domain, %mailfrom_address) @end smallexample @cindex @code{poll} command, strict verification @cindex strict verification with @code{poll} The construct @code{poll @var{email} host @var{host}}, runs the strict sender verification of address @var{email} on the given host. It is translated to the following call: @smallexample strictpoll(@var{host}, @var{email}, %ehlo_domain, %mailfrom_address) @end smallexample @cindex as @cindex from Other keywords of the @code{poll} statement modify these two basic forms. The @code{as} keyword introduces the email address to be used in the @acronym{SMTP} @code{MAIL FROM} command, instead of @code{%mailfrom_address}. The @code{from} keyword sets the domain name to be used in @code{EHLO} command. So, for example the following construct: @smallexample poll @var{email} host @var{host} from @var{domain} as @var{addr} @end smallexample @noindent is translated to @smallexample strictpoll(@var{host}, @var{email}, @var{domain}, @var{addr}) @end smallexample To summarize the above, the code described in @ref{figure-stdpoll} can be written as: @smallexample @group prog envfrom do on poll $f do when success: accept when not_found or failure: reject 550 5.1.0 "Sender validity not confirmed" when temp_failure: tempfail 450 4.1.0 "Try again later" done done @end group @end smallexample @node Modules @section Modules @cindex module, defined A module is an @acronym{MFL} source file containing a collection of conceptually united functions and data. Currently, there are no special syntax rules that make an arbitrary source file a module, it suffices to make sure the module name ends in standard suffix @samp{.mf} and place it in one of the directories comprising the include source path (@pxref{include search path}). However, such syntax rules will appear in future versions. It is planned that modules will be compiled and stored on disk in form of object files or combined into libraries. In order to make definitions from module @file{@var{modname}.mf} available to your filter program, use the following statement: @smallexample #require @var{modname} @end smallexample The @code{#require} statement looks up the module @file{@var{modname}.mf} in the include path and attempts to compile it (@pxref{require}). It is not an error to require the same module several times. However, requiring a non-existing module results in compilation error. @node Preprocessor @section @acronym{MFL} Preprocessor @cindex preprocessor @cindex m4 Before compiling the script file, @command{mailfromd} preprocesses it. The built-in preprocessor handles only file inclusion (@pxref{include}), while the rest of traditional facilities, such as macro expansion, are supported via @command{m4}, which is used as an external preprocessor. The detailed description of @command{m4} facilities lies far beyond the scope of this document. You will find a complete user manual in @ref{Top, GNU M4 manual, GNU M4, m4, GNU M4 macro processor}. For the rest of this section we assume the reader is sufficiently acquainted with @command{m4} macro processor. @flindex pp-setup The external preprocessor is invoked with @option{-s} flag, instructing it to include line synchronization information in its output, which is subsequently used by @acronym{MFL} compiler for purposes of error reporting. The initial set of macro definitions is supplied in file @file{pp-setup}, located in the library search path@footnote{It is usually located in @file{/usr/local/share/mailfromd/@value{VERSION}/include/pp-setup}.}, which is fed to the preprocessor input before the script file itself. The default @file{pp-setup} file renames all @command{m4} built-in macro names so they all start with the prefix @samp{m4_}@footnote{This is similar to GNU m4 @option{--prefix-builtin} options. This approach was chosen to allow for using non-GNU @command{m4} implementations as well.}. It changes comment characters to @samp{/*}, @samp{*/} pair, and leaves the default quoting characters, grave (@samp{`}) and acute (@samp{'}) accents without change. Finally, @file{pp-setup} defines the following macros: @anchor{defined} @deftypefn {M4 Macro} boolean defined (@var{identifier}) The @var{identifier} must be the name of an optional abstract argument to the function. This macro must be used only within a function definition. It expands to the @acronym{MFL} expression that yields @code{true} if the actual parameter is supplied for @var{identifier}. For example: @smallexample func rcut(string text; number num) do if (defined(num)) return substr(%text, length(%text) - %num) else return %text fi done @end smallexample This function will return last @var{num} characters of @var{text} if @var{num} is supplied, and entire @var{text} otherwise, e.g.: @smallexample @group rcut("text string") @result{} "text string" rcut("text string", 3) @result{} "ing" @end group @end smallexample Invoking the @code{defined} macro with the name of a mandatory argument yields @code{true} @end deftypefn @deffn {M4 Macro} printf (@var{format}, @dots{}) Provides a @code{printf} statement, that formats its optional parameters in accordance with @var{format} and sends the resulting string to the current log output (@pxref{Logging and Debugging}). @xref{String formatting}, for a description of @var{format}. Example usage: @smallexample printf('Function %s returned %d', %funcname, %retcode) @end smallexample @end deffn @deftypefn {M4 Macro} string _ (@var{msgid}) A convenience macro. Expands to a call to @code{gettext} (@pxref{NLS Functions}). @end deftypefn @deffn {M4 Macro} N_ (@var{msgid}) A convenience macro, that expands to @var{msgid} verbatim. It is intended to mark the literal strings that should appear in the @file{.po} file, where actual call to @code{gettext} (@pxref{NLS Functions}) cannot be used. For example: @smallexample /* Mark the variable for translation: cannot use gettext here */ string message N_("Mail accepted") prog envfrom do @dots{} /* Translate and log the message */ echo gettext(%message) @end smallexample @end deffn @cindex E, -E @r{option, described} You can obtain the preprocessed output, without starting actual compilation, using @option{-E} command line option: @smallexample $ @kbd{mailfromf -E file.mf} @end smallexample The output is in the form of preprocessed source code, which is sent to the standard output. This can be useful, among others, to debug your own macro definitions. Macro definitions and deletions can be made on the command line, by using the @option{-D} and @option{-U} options. They have the following format: @table @option @xopindex{define, described} @cindex D, -D @r{option, described} @item -D @var{name}[=@var{value}] @itemx --define=@var{name}[=@var{value}] Define a symbol @var{name} to have a value @var{value}. If @var{value} is not supplied, the value is taken to be the empty string. The @var{value} can be any string, and the macro can be defined to take arguments, just as if it was defined from within the input using the @code{m4_define} statement. For example, the following invocation defines symbol @code{COMPAT} to have a value @code{43}: @smallexample $ mailfromf -DCOMPAT=43 @end smallexample @xopindex{undefine, described} @cindex U, -U @r{option, described} @item -U @var{name} @item --undefine=@var{name} A counterpart of the @option{-D} option is the option @option{-U} (@option{--undefine}). It undefines a preprocessor symbol whose name is given as its argument. The following example undefines the symbol @code{COMPAT}: @smallexample $ mailfromf -UCOMPAT @end smallexample @end table The following two options are supplied mainly for debugging purposes: @table @option @xopindex{no-preprocessor, usage} @item --no-preprocessor Disables the external preprocessor. @xopindex{preprocessor, usage} @item --preprocessor=@var{command} Use @var{command} as external preprocessor. Be especially careful with this option, because @command{mailfromd} cannot verify whether @var{command} is actually some kind of a preprocessor or not. @end table @node Filter Script Example @section Example of a Filter Script File This section will show a working example of the filter script file. For the ease of illustration, it is divided in several sections. Each section is prefaced with a comment explaining its function. The first part defines the configuration settings for this host: @smallexample #pragma option relay /etc/mail/sendmail.cw #pragma option relay /etc/mail/relay-domains #pragma option timeout 33 #pragma regex +extended +icase #pragma database cache negative-expire-interval 1 day #pragma database cache positive-expire-interval 2 weeks set mailfrom_address "<>" set ehlo_domain "gnu.org.ua" @end smallexample The second part includes the necessary header files and loads required source modules: @smallexample @group #include #require dns #require rateok @end group @end smallexample Next we define @code{envfrom} handler. In the first two rules, it accepts all mails coming from the null address and from the machines which we relay: @smallexample prog envfrom do if $f = "" accept elif relayed hostname $client_addr accept elif hostname $client_addr = $client_addr reject 550 5.7.7 "IP address does not resolve" @end smallexample Next rule rejects all messages coming from hosts with dynamic @acronym{IP} addresses. A regular expression used to catch such hosts is not 100% fail-proof, but it tries to cover most existing host naming patterns: @smallexample @group elif hostname $client_addr matches ".*(adsl|sdsl|hdsl|ldsl|xdsl|dialin|dialup|\ ppp|dhcp|dynamic|[-.]cpe[-.]).*" reject 550 5.7.1 "Use your SMTP relay" @end group @end smallexample Messages coming from the machines whose host names contain something similar to an @acronym{IP} are subject to strict checking: @smallexample elif hostname $client_addr matches ".*[0-9]@{1,3@}[-.][0-9]@{1,3@}[-.][0-9]@{1,3@}[-.][0-9]@{1,3@}.*" on poll host $client_addr for $f do when success: pass when not_found or failure: reject 550 5.1.0 "Sender validity not confirmed" when temp_failure: tempfail done @end smallexample If the sender domain is relayed by any of the @indicateurl{yahoo.com} or @indicateurl{nameserver.com} @samp{MX}s, no checks are performed. We will greylist this message in @code{envrcpt} handler: @smallexample @group elif $f mx fnmatches "*.yahoo.com" or $f mx fnmatches "*.namaeserver.com" pass @end group @end smallexample Finally, if the message does not meet any of the above conditions, it is verified by the standard procedure: @smallexample else on poll $f do when success: pass when not_found or failure: reject 550 5.1.0 "Sender validity not confirmed" when temp_failure: tempfail done fi @end smallexample At the end of the handler we check if the sender-client pair does not exceed allowed mail sending rate: @smallexample @group if not rateok($f "-" $client_addr, interval("1 hour 30 minutes"), 100) tempfail 450 4.7.0 "Mail sending rate exceeded. Try again later" fi done @end group @end smallexample Next part defines the @code{envrcpt} handler. Its primary purpose is to greylist messages from some domains that could not be checked otherwise: @smallexample prog envrcpt do set gltime 300 if $f mx fnmatches "*.yahoo.com" or $f mx fnmatches "*.namaeserver.com" and not dbmap("/var/run/whitelist.db", $client_addr) if greylist($client_addr "-" $f "-" $rcpt_addr, %gltime) if %greylist_seconds_left = %gltime tempfail 450 4.7.0 "You are greylisted for " %gltime " seconds" else tempfail 450 4.7.0 "Still greylisted for " %greylist_seconds_left " seconds" fi fi fi done @end smallexample @node Reserved Words @section Reserved Words @cindex reserved words @cindex keywords For your reference, here is an alphabetical list of all reserved words: @itemize @bullet @item __file__ @item __function__ @item __line__ @item __major__ @item __minor__ @item __package__ @item __patch__ @item __preproc__ @item __statedir__ @item __version__ @item accept @item add @item and @item alias @item begin @item break @item case @item catch @item const @item continue @item default @item delete @item discard @item do @item done @item echo @item end @item elif @item else @item fi @item fnmatches @item for @item func @item if @item loop @item matches @item next @item not @item number @item on @item or @item pass @item prog @item reject @item replace @item return @item returns @item set @item string @item switch @item tempfail @item throw @item vaptr @item when @item while @end itemize Several keywords are context-dependent: @code{mx} is a keyword if it appears before @code{matches} or @code{fnmatches}. Following strings are keywords in @code{on} context: @itemize @item as @item from @item host @item poll @end itemize The following keywords are preprocessor macros: @itemize @item defined @item _ (an underscore) @item N_ @end itemize Any keyword beginning with a @samp{m4_} prefix is a reserved preprocessor symbol. @node Using MFL Mode @chapter Using the GNU Emacs MFL Mode @cindex Emacs, @acronym{MFL} mode @cindex GNU Emacs, @acronym{MFL} mode @cindex @acronym{MFL} mode, GNU Emacs @acronym{MFL} sources are usual @acronym{ASCII} files and you may edit them with any editor you like. However, the best choice for this job (as well as for many others) is, without doubt, GNU Emacs. To ease the work of editing script files, the @command{mailfromd} package provides a special Emacs mode, called @dfn{@acronym{MFL} mode}. @flindex mfl-mode.el @flindex site-start.el @flindex ~/.emacs @cindex Enabling @acronym{MFL} mode @cindex @acronym{MFL} mode, enabling @cindex MFL mode, The elisp source file providing this mode, @file{mfl-mode.el}, is installed automatically, provided that GNU Emacs is present on your machine. To enable the mode, add the following lines to your Emacs setup file (either system-wide @file{site-start.el}, or your personal one, @file{~/.emacs}): @smalllisp @group (autoload 'mfl-mode "mfl-mode") (setq auto-mode-alist (append auto-mode-alist '(("/etc/mailfromd.rc" . mfl-mode) ("\\.mf$" . mfl-mode)))) @end group @end smalllisp The first directive loads the @acronym{MFL} mode, and the second one tells Emacs to apply it to any file whose name ends in @file{/etc/mailfromd.rc}@footnote{This will match most existing installations. In the unlikely case that your @code{$sysconfdir} does not end in @file{/etc}, you will have to edit the directive accordingly.} or in a @samp{.mf} suffix. @cindex indentation, @acronym{MFL}, default @acronym{MFL} mode provides automatic indentation and syntax highlighting for @acronym{MFL} sources. The default indentation setup is the same as the one used throughout this book: @itemize @bullet @item Handler and function definitions start at column 1; @item A block statement, i.e. @samp{do}, @samp{done}, @samp{if}, @samp{else}, @samp{elif} and @samp{fi}, occupies a line by itself, with the only exception that @samp{do} after an @samp{on} statement is located on the same line with it; @item A @samp{do} statement that follows function or handler definition is placed in column 1. @item Each subsequent level of nesting is indented two columns to the right (@pxref{mfl-basic-offset}). @item A closing statement (@samp{done}, @samp{else}, @samp{elif}, @samp{fi}) is placed at the same column as the corresponding opening statement; @item Branch statements (@samp{case} and @samp{when}) are placed in the same column as their controlling keyword (@samp{switch} and @samp{on}, correspondingly (@pxref{mfl-case-line-offset}). @item Loop substatements (@pxref{Loops}) are offset 5 columns to the right from the controlling @code{loop} keyword. (@pxref{mfl-loop-statement-offset}). Continuation statements within loop header are offset 5 columns from the indentation of their controlling keyword, either @code{for} or @code{while} (@pxref{mfl-loop-continuation-offset}). @end itemize @cindex Finding function definition @cindex Navigating through function definitions The mode provides two special commands that help navigate through the complex filter scripts: @table @kbd @item C-M-a Move to the beginning of current function or handler definition. @item C-M-e Move to the end of current function or handler definition. @end table Here, @dfn{current function or handler} means the one within which your cursor currently stays. You can use @kbd{C-M-e} repeatedly to walk through all function and handler definitions in your script files. Similarly, repeatedly pressing @kbd{C-M-a} will visit all the definitions in the opposite direction (from the last up to the very first one). @cindex Verifying script syntax Another special command, @kbd{C-c C-c}, allows to verify the syntax of your script file. This command runs @command{mailfromd} in syntax check mode (@pxref{Testing Filter Scripts}) and displays its output in a secondary window, which allows to navigate through eventual diagnostic messages and to jump to source locations described by them. @cindex customization, Emacs @cindex customization, @acronym{MFL} mode All @acronym{MFL} mode settings are customizable. To change any of them, press @kbd{M-x customize} and visit @samp{Environment/Unix/Mfl} customization group. This group offers two subgroups: @samp{Mfl Lint group} and @samp{Mfl Indentation group}. @samp{Mfl Lint group} controls invocation of mailfromd by @kbd{C-c C-c}. This group contains two variables: @defvr {MFL-mode setting} mfl-mailfromd-command The @command{mailfromd} to be invoked. By default, it is @samp{mailfromd}. You will have to change it, if @command{mailfromd} cannot be found using @env{PATH} environment variable, or if you wish to pass it some special options. However, do not include @option{--lint} or @option{-I} options in this variable. The @option{--lint} option is given automatically, and include paths are controlled by @code{mfl-include-path} variable (see below). @end defvr @defvr {MFL-mode setting} mfl-include-path A list of directories to be appended to @command{mailfromd} include search path (@pxref{include search path}). By default it is empty. @end defvr @samp{Mfl Indentation group} controls automatic indentation of @acronym{MFL} scripts. This group contains the following settings: @anchor{mfl-basic-offset} @defvr {MFL-mode setting} mfl-basic-offset This variable sets the basic indentation increment. It is set to 2, by default, which corresponds to the following indentation style: @smallexample prog envfrom do if $f = "" accept else @dots{} fi done @end smallexample @end defvr @anchor{mfl-case-line-offset} @defvr {MFL-mode setting} mfl-case-line-offset Indentation offset for @code{case} and @code{when} lines, relative to the column of their controlling keyword. The default is 0, i.e.: @smallexample switch %x do case 0: @dots{} default: @dots{} done @end smallexample @end defvr @defvr {MFL-mode setting} mfl-returns-offset Indentation offset of @code{returns} and @code{alias} statements, relative to the controlling @code{func} keyword. The default value is 2, which corresponds to: @smallexample @group func foo() alias bar returns string @end group @end smallexample @end defvr @defvr {MFL-mode setting} mfl-comment-offset Indentation increment for multi-line comments. The default value is 1, which makes: @smallexample @group /* first comment line second comment line */ @end group @end smallexample @end defvr @anchor{mfl-loop-statement-offset} @defvr {MFL-mode setting} mfl-loop-statement-offset Indentation increment for parts of a @code{loop} statement. The default value is 5, which corresponds to the following style: @smallexample @group loop for @var{stmt}, while @var{cond}, @var{incr} do @end group @end smallexample @end defvr @anchor{mfl-loop-continuation-offset} @defvr {MFL-mode setting} mfl-loop-continuation-offset If any of the @code{loop} parts occupies several lines, the indentation of continuation lines relative to the first line is controlled by @code{mfl-loop-continuation-offset}, which defaults to 5: @smallexample @group loop for set n 0 set z 1, while %n != 10 or z != 2, set n %n + 1 @end group @end smallexample @end defvr @node Mailfromd Configuration @chapter Configuring @command{mailfromd} In the simplest case you will be able to startup @command{mailfromd} without any additional command line options: the default values provided when compiling the package and the default script file are enough. If you need to alter any configuration settings, there are three ways of doing so. First of all, and this method should always be preferred, you can use various @samp{#pragma} directives in the filter script. These were described in @ref{Comments}. We advise to use this method because with it all the program settings are kept in a single file, which simplifies the maintenance and ensures they remain valid across program restarts. If you wish to temporarily override the configuration settings, use the command line. It is the second configuration method. Finally, there are several configuration options that are handled by @command{libmailutils} itself, and that cannot currently be configured in @file{mailfromd.rc}. We recommend to store these settings in the @dfn{mailutils system-wide configuration file}@footnote{The use of mailutils configuration file is covered in @xref{configuration,,Mailutils Configuration File,mailutils, GNU Mailutils Manual}.}. This approach is described in @ref{Local Account Verification}. In this chapter we will discuss @command{mailfromd} command line options and the ways of starting and shutting down the program. @menu * invocation:: * options:: Command Line Options. * Starting and Stopping:: How to Start and Shut Down the Daemon. @end menu @node invocation @section @command{Mailfromd} command line syntax @cindex invocation @cindex command line, @command{mailfromd} invocation syntax The @command{mailfromd} binary is started from the command line using the following syntax (brackets indicate optional parts): @smallexample $ @kbd{mailfromd [@var{options}] [@var{asgn}] [@file{@var{script}}]} @end smallexample @noindent The meaning of each invocation part is described in the table below: @table @var @item options The command line options (@pxref{options}). @item asgn Sendmail macro assignments. These are currently meaningful only with the @option{--test} option (@pxref{test mode}), but this may change in the future. Each assignment has the form: @smallexample @var{var}=@var{value} @end smallexample @noindent where @var{var} is the name of a Sendmail macro and @var{value} is the value to be assigned to it. @item script The file name of the filter script, if other than the default one. @end table @node options @section Command Line Options. @menu * Operation Modifiers:: * General Settings:: * Preprocessor Options:: * Timeout Control:: * Logging and Debugging Options:: * Informational Options:: @end menu @node Operation Modifiers @subsection Operation Modifiers @table @option @opsummary{compact} @item --compact Compact database (@pxref{compaction}). By default, @samp{cache} database is compacted. To specify another database, use @option{--format} option (@pxref{--format}). Full database name can be given in the command line (see @option{--file} option below), if it differs from the one specified in the script file. Use with the option @option{--all} (@pxref{--all}) to compact all databases. This option implies @option{--stderr} (@pxref{--stderr}). @opsummary{daemon} @item --daemon Run in daemon mode (default). @opsummary{delete} @item --delete Delete given entries from the database (@pxref{deleting from databases}). By default, @samp{cache} database is assumed. To specify another database, use @option{--format} option (@pxref{--format}). This option implies @option{--stderr} (@pxref{--stderr}). @opsummary{expire} @item --expire Delete all expired entries from the database (@pxref{Database Maintenance}). By default, @samp{cache} database is assumed. To specify another database, use @option{--format} option (@pxref{--format}). Full database name can be given in the command line (see @option{--file} option below), if it differs from the one specified in the script file. Use with the option @option{--all} (@pxref{--all}) to expire all databases. This option implies @option{--stderr} (@pxref{--stderr}). @opsummary{file} @item -f @var{filename} @itemx --file=@var{filename} Set the name of the database to operate upon (for @option{--compact}, @option{--delete}, @option{--expire}, and @option{--list} options). Useful if, for some reason, you need to operate on a database whose file name does not match the one @command{mailfromd} is configured to use. @opsummary{list} @item --list List the database. By default, @samp{cache} database is assumed. To list another database, use @option{--format} option (@pxref{--format}). This option implies @option{--stderr} (@pxref{--stderr}). @xref{Basic Database Operations}. @opsummary{run} @item --run[=@var{start}] Load the script named in the command line and execute the function named @var{start}, or @samp{main}, if @var{start} is not given. @xref{Run Mode}, for a detailed description of this feature. @opsummary{show-defaults} @item --show-defaults Show compilation defaults. @xref{Databases}. @opsummary{test} @item -t[@var{state}] @itemx --test[=@var{state}] Run in test mode. @xref{Testing Filter Scripts}. Default @var{state} is @samp{envfrom}. This option implies @option{--stderr} (@pxref{--stderr}). @end table @node General Settings @subsection General Settings @table @option @opsummary{all} @item --all When used with @option{--compact} or @option{--expire} option, applies the action to all available databases. @xref{compact cronjob}. @opsummary{expire-interval} @item -e @var{interval} @itemx --expire-interval=@var{interval} Set expiration intervals for all databases to the specified interval. @xref{time interval specification}, for a description of @var{interval} format. The option overrides @samp{#pragma option expire-interval} (@pxref{pragma expire-interval}), which you are advised to use instead. @opsummary{foreground} @item --foreground Stay in foreground. When given this option, @command{mailfromd} will not disconnect itself from the controlling terminal and will run in the foreground. @opsummary{format} @item -H @var{dbformat} @itemx --format=@var{dbformat} Use database of the given format, instead of the default @samp{cache}. @xref{Basic Database Operations}. @opsummary{group} @item -g @var{name} @itemx --group=@var{name} Retain the group @var{name} when switching to user privileges. @xref{Starting and Stopping}. This option overrides @samp{#pragma option group} (@pxref{pragma group}). @opsummary{ignore-failed-reads} @item --ignore-failed-reads Ignore records that cannot be retrieved while compacting the database. Without this option, @command{mailfromd} will abort the compaction if any such error is encountered. @opsummary{include} @item --include=@var{dir} @itemx -I @var{dir} Add the directory @var{dir} to the list of directories to be searched for header files. This will affect the functioning of @code{#include} statement. @xref{include}, for a discussion of file inclusion. @opsummary{lock-retry-count} @item --lock-retry-count=@var{number} Set maximum number of attempts to acquire the lock on a database. See the description of @code{#pragma option lock-retry-count}, @ref{pragma lock-retry-count}, for more information about the database locking. @opsummary{lock-retry-timeout} @item --lock-retry-timeout=@var{interval} Set the time span between the two locking attempts. See the description of @code{#pragma option lock-retry-count}, @ref{pragma lock-retry-count}, for more information about database locking. This option overrides the value set by @code{#pragma option lock-retry-timeout} (@pxref{pragma lock-retry-timeout}. @xref{time interval specification}, for a description of valid @var{interval} formats. @opsummary{mailer} @item --mailer=@var{url} @itemx -M @var{url} Set the @acronym{URL} of the mailer to use. @xref{Mail Sending Functions}. @opsummary{mtasim} @item --mtasim This option is reserved for use by @command{mtasim} (@pxref{mtasim}). @opsummary{optimize} @item -O[@var{level}] @itemx --optimize[=@var{level}] Set optimization level for code generator. Two levels are implemented: @samp{0}, meaning no optimization, and @samp{1}, meaning full optimization. @opsummary{port} @item -p @var{string} @itemx --port=@var{string} Set communication socket. Overrides @samp{#pragma option port}, which you are advised to use instead (@pxref{pragma port}). @opsummary{pidfile} @item --pidfile=@var{file} Set pidfile name. Overrides @samp{#pragma option pidfile}, which you are advised to use instead (@pxref{pragma pidfile}). @opsummary{predict} @item --predict=@var{rate-limit} Used with @option{--list} enables printing of the estimated times of sending along with the @samp{rate} database dump. Implies @option{--list --format=rate}. @xref{estimated time of sending}. @opsummary{relayed-domain-file} @item --relayed-domain-file=@var{file} @anchor{option relay} Read relayed domains from @var{file}. Overrides @samp{#pragma option relay}, which you are advised to use instead (@pxref{option relay}). @xref{Avoiding Verification Loops}, and the description of @code{relayed} function (@pxref{relayed}) for more information. @opsummary{remove} @item -r @itemx --remove Force removing local socket file, if it already exists. Unless this option is specified, @command{mailfromd} will refuse to start if this file exists. @opsummary{state-directory} @item --state-directory=@var{dir} Set new program state directory. @xref{statedir, Local state directory}, for the description of this directory and its purposes. This option overrides the settings of @samp{#pragma option state-directory}, described in @ref{pragma state-directory}. @opsummary{source} @item -S @itemx --source Set source address for @acronym{TCP} connections. Overrides @samp{#pragma option source}, which you are advised to use instead (@pxref{pragma source}). @opsummary{time-format} @item --time-format=@var{format} Set format to be used for timestamps in listings, produced by @option{--list}. The @var{format} is any valid @code{strftime} format string, see @ref{Time and Date Formats}, for a detailed description. The default @var{format} is @samp{%c} (@pxref{%c time format}). To analyze @kbd{mailfromd --list} output using text tools, such as @code{awk} or @code{grep}, the following format might be useful: @samp{%s} (@pxref{%s time format}). Another format I find useful is @samp{%Y-%m-%d_%H:%M:%S}. @opsummary{user} @item -u @var{name} @itemx --user @var{name} Switch to this user privileges after startup. Overrides @samp{#pragma option user}, which you are advised to use instead (@pxref{pragma user}). Default user is @samp{@value{DEFAULT-USER}}. @opsummary{variable} @item -v @var{var}=@var{value} @itemx --variable @var{var}=@var{value} Assign @var{value} to the global variable @var{var}. The variable must be declared in your startup script. @xref{overriding initial values}, for a detailed discussion of this option. @ignore -- Reserved for future use @opindex compile @end ignore @end table @node Preprocessor Options @subsection Preprocessor Options Following command line options control the preprocessor feature. @xref{Preprocessor}, for a detailed discussion of these. @table @option @opsummary{no-preprocessor} @item --no-preprocessor Do not run the preprocessor. @opsummary{preprocessor} @item --preprocessor=@var{command} Use @var{command} as the external preprocessor instead of the default @command{m4}. @opsummary{define} @cindex D, -D @r{option, summary} @item -D @var{name}[=@var{value}] @itemx --define=@var{name}[=@var{value}] Define a preprocessor symbol @var{name} to have a value @var{value}. @opsummary{undefine} @cindex U, -U @r{option, summary} @item -U @var{name} @itemx --undefine=@var{name} Undefine the preprocessor symbol @var{name}. @cindex E, -E @r{option, summary} @item -E Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output. @end table @node Timeout Control @subsection Timeout Control @xref{time interval specification}, for information on @var{interval} format. @table @option @opsummary{milter-timeout} @item --milter-timeout=@var{interval} Set @acronym{MTA} connection timeout. Overrides @samp{#pragma option milter-timeout}, which you are advised to use instead (@pxref{pragma milter-timeout}. @opsummary{timeout} @item --timeout=@var{number} Set @acronym{I/O} operation timeout (seconds). Overrides @samp{#pragma option timeout}, which you are advised to use instead (@pxref{pragma io-timeout}). @end table @node Logging and Debugging Options @subsection Logging and Debugging Options @table @option @opsummary{debug} @item -d @var{string} @itemx --debug=@var{string} Set debugging level. Overrides @samp{#pragma option debug}. @xref{Logging and Debugging}. @opsummary{dump-code} @item --dump-code Parse and compile the script file and dump the disassembled listing of the produced code to the terminal. @xref{Logging and Debugging}. @opsummary{dump-grammar-trace} @item --dump-grammar-trace Enable debugging the script file parser. While parsing the file, the detailed dump of the parser states and tokens seen will be output. @opsummary{dump-lex-trace} @item --dump-lex-trace Enable debugging the lexical analyzer. While parsing the script file, the detailed dump of the lexer states and matched rules will be output. @opsummary{dump-macros} @item --dump-macros Show Sendmail macros used in the script file. The macro names are displayed as comma-separated lists, grouped by handler names. @xref{Sendmail}, for a detailed description of this option and its usage. @opsummary{dump-tree} @item --dump-tree Parse and compile the script file and dump the parse tree in a printable form to the terminal. @opsummary{dump-xref} @item --dump-xref Print a cross-reference of variables used in the filter script. @xref{Testing Filter Scripts}. @cindex E, -E @r{option, summary} @item -E Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output. @xref{Preprocessor}. @opsummary{lint} @item --lint Check script file syntax and exit. If the file is @sc{ok}, return 0 to the shell, otherwise print appropriate messages to stderr and exit with code 78 (@samp{configuration error}). @opsummary{single-process} @item --single-process Do not fork sub-processes to serve requests. This option is meant to assist in debugging @command{mailfromd}. Don't use it for anything else but for debugging, as it terribly degrades performance! @opsummary{stack-trace} @item --stack-trace Add @acronym{MFL} stack trace information to runtime error output. Overrides @code{#pragma option stack-trace}, which you are advised to use instead (@pxref{pragma stack-trace}). @xref{tracing runtime errors}, for more information on this feature. @anchor{gacopyz-log option} @opsummary{gacopyz-log} @item --gacopyz-log=@var{level} Set desired logging level for @command{gacopyz} library (@pxref{Gacopyz}). There are five logging levels. The following table lists them in order of decreasing priority: @table @asis @item fatal Log fatal errors. @item err Log error messages. @item warn Log warning messages. @item info Log informational messages. In particular, this enables printing messages on each subprocess startup and termination, which look like that: @smallexample Apr 28 09:00:11 host mailfromd[9411]: connect from 192.168.10.1:50398 Apr 28 09:00:11 host mailfromd[9411]: finishing connection @end smallexample This level can be useful for debugging your scripts. @item debug Log debugging information. @item proto Log Milter protocol interactions. This level prints huge amounts of information, in particular it displays dumps of each Milter packet sent and received. @end table Although it is possible to set these levels independently of each other, it is seldom practical. Therefore, the option @option{--gacopyz-log=@var{level}} enables all logging levels from @var{level} up. For example, @option{--gacopyz-log=warn} enables log levels @samp{warn}, @samp{err} and @samp{fatal}. It is the default. If you need to trace each subprocess startup and shutdown, set @option{--gacopyz-log=info}. Setting the logging level to @samp{proto} can be needed only for @command{Gacopyz} developers, to debug the protocol. @xref{Testing Filter Scripts}. @opsummary{log-facility} @item --log-facility=@var{facility} Output logs to syslog @var{facility}. @opsummary{log-tag} @item --log-tag=@var{string} Tag syslog entries with the given @var{string}, instead of the program name. @opsummary{no-syslog-async} @item --no-syslog-async Use system @command{libc} syslog implementation. @xref{Logging and Debugging}, for more information about two syslog flavors, and see @ref{syslog-async, Using non-blocking syslog}, for information on how to set default syslog implementation at compile time. To inspect the default syslog implementation, use the @option{--show-defaults} command line option (@pxref{Databases, show-defaults}). @opsummary{stderr} @item -s @itemx --stderr Log to stderr (by default logging goes to syslog). @xref{Logging and Debugging}. This option is turned on implicitly by any of the following options: @option{--compact}, @option{--delete}, @option{--expire}, @option{--test}, and @option{--list}. @opsummary{source-info} @item --source-info Include @sc{c} source information in debugging messages. You do not need this option, unless you are developing and debugging @command{mailfromd}. @opsummary{syntax-check} @item --syntax-check Synonym for @option{--lint}. @opsummary{trace} @item --trace Enable action tracing. With this option @command{mailfromd} will log all executed actions. @xref{Logging and Debugging}. @opsummary{trace-program} @item --trace-program[=@var{string}] Enable program instruction tracing. With this option @command{mailfromd} will log execution of every instruction in the compiled filter program. The optional arguments allows to specify a comma-separated list of source code modules for which the tracing is to be enabled, for example @code{--trace-program=bi_io,bi_db} enables tracing for functions from modules @file{bi_io.c} and @file{bi_db.c} (notice, that you need not give file suffixes in @var{string}). This option is useful for debugging @command{mailfromd}, but is not advised to use otherwise, since it is very time-costly. @opsummary{transcript} @item -X @itemx --transcript Enable transcript of the @acronym{SMTP} sessions to the log channel. @xref{Logging and Debugging}. @opsummary{syslog} @item --syslog Output logs to syslog. This is the default, unless any of the following options is used: @option{--compact}, @option{--delete}, @option{--expire}, @option{--test}, and @option{--list}. @opsummary{syslog-async} @item --syslog-async Use asynchronous syslog implementation. @xref{Logging and Debugging}, for more information about two syslog flavors, and see @ref{syslog-async, Using non-blocking syslog}, for information on how to set default syslog implementation at compile time. To inspect the default syslog implementation, use the @option{--show-defaults} command line option (@pxref{Databases, show-defaults}). @opsummary{xref} @item --xref Same as @option{--dump-xref}. @xref{Logging and Debugging}. @end table @node Informational Options @subsection Informational Options @table @option @item -? @itemx --help Give a short help summary. @item --usage Give a short usage message. @item -V @itemx --version Print program version. @end table @node Starting and Stopping @section Starting and Stopping @cindex startup @cindex user privileges @cindex groups @cindex supplementary groups Right after startup, when @command{mailfromd} has done the operations that require root privileges, it switches to the privileges of the user it is configured to run as (@pxref{default user privileges}) or the one given in its script file (@pxref{pragma user}). During this process it will drop all supplementary groups and switch to the principal group of that user. Such limited privileges of the daemon can cause difficulties if your filter script needs to access some files (e.g. @command{Sendmail} databases) that are not accessible to that user and group. For example, the following fragment using @code{dbmap} function: @smallexample @group if dbmap("/etc/mail/aliases.db", $f, 1) @dots{} fi @end group @end smallexample @noindent will normally fail, because @file{/etc/mail/aliases.db} is readable only to the root and members of the group @samp{smmsp}. In such situations you need to instruct @command{mailfromd} to retain the privileges of one or several supplementary groups when switching to the user privileges. This is done using @code{#pragma option group} directive in the script file (@pxref{pragma group}). In example above, you need to use the following directive: @smallexample #pragma option group smmsp @end smallexample @noindent (The same effect can be achieved with @option{--group} command line option: @kbd{mailfromd --group=smmsp}). @cindex signals @cindex SIGQUIT @cindex SIGTERM @cindex SIGINT To stop a running instance of @command{mailfromd} use one of the following signals: @code{SIGQUIT}, @code{SIGTERM}, @code{SIGINT}. All three signals have the same effect: the program cancels handling any pending requests, uninitializes the communication socket (if it is a @acronym{UNIX} socket, the program unlinks it) and exits. @cindex SIGHUP To restart the running @command{mailfromd} instance, send it @code{SIGHUP}. For restart to be possible, two conditions must be met: @command{mailfromd} must be invoked with the full file name, and the configuration file name must be full as well. If either of them is not met, @command{mailfromd} displays a similar warning message: @smallexample @group warning: script file is given without full file name warning: restart (SIGHUP) will not work @end group @end smallexample @noindent or: @smallexample @group warning: mailfromd started without full file name warning: restart (SIGHUP) will not work @end group @end smallexample The reaction of @command{mailfromd} on @code{SIGHUP} in this case is the same as on the three signals described previously, i.e. cleanup and exit immediately. @cindex pidfile The @acronym{PID} of the master instance of @command{mailfromd} is kept on the @dfn{pidfile}, which is named @file{mailfromd.pid} and is located in the program @dfn{state directory}. Assuming the default location of the latter, the following command will stop the running instance of the daemon: @smallexample kill -TERM `head -n1 /usr/local/var/mailfromd/mailfromd.pid` @end smallexample The default pidfile location is shown in the output of @command{mailfromd --show-defaults} (@pxref{Databases}), and can be changed at run time using @code{#pragma option pidfile} statement (@pxref{pragma pidfile}). @cindex @file{rc.mailfromd} @cindex system-wide startup script To facilitate the use of @command{mailfromd}, it is shipped with a shell script that can be used to launch it on system startup and shut it down when the system goes down. The script, called @file{rc.mailfromd}, is located in the directory @file{/etc} of the distribution. It takes a single argument, specifying the action that should be taken: @table @asis @item start Start the program. @item stop Shut down the program @item reload Reload the program, by sending it @code{SIGHUP} signal. @item restart Shut down the program and start it again. @item status Display program status. It displays the @acronym{PID} of the master process and its command line, for example: @smallexample @group $ @kbd{/etc/rc.d/rc.mailfromd status} mailformd appears to be running at 26030 26030 /usr/local/sbin/mailfromd @/--remove @/--group smmsp @end group @end smallexample @noindent If the second line is not displayed, this most probably mean that there is a @samp{stale} pidfile, i.e. the one left though the program is not running. An empty @kbd{rc.mailfromd status} output means that @command{mailfromd} is not running. @item configtest [@var{file}] Check the script file syntax, report any errors found and exit. If @var{file} is given it is checked instead of the default one. @item macros [-c] [@var{file}] Parse the script file (or @var{file}, if it is given, extract the names of Sendmail macros it uses and generate corresponding export statements usable in the Sendmail configuration file. By default, @file{mc} statements are generated. If @option{-c} (@option{--cf}) is given, the statements for @file{sendmail.cf} are output. See the next chapter for the detailed description of this mode. @end table You can pass any additional arguments to @command{mailfromd} by editing @code{ARGS} variable near line 22. The script is not installed by default. You will have to copy it to the directory where your system start-up scripts reside and ensure it is called during the system startup and shut down. The exact instructions on how to do so depend on the operating system you use and are beyond the scope of this manual. @node Sendmail @chapter Using @command{mailfromd} with Sendmail. This chapter assumes you are familiar with Sendmail configuration in general and with Milter configuration directives in particular. It concentrates only on issues, specific for @command{mailfromd}. @cindex INPUT_MAIL_FILTER, mc file directive To prepare @command{Sendmail} to communicate with @command{mailfromd} you need first to set up the @dfn{milter port}. This is done with @code{INPUT_MAIL_FILTER} statement in your @command{Sendmail} file. Use the same value you have used in @command{#pragma option port} statement of @file{mailfromd.rc} file (@pxref{pragma port}): @smallexample INPUT_MAIL_FILTER(`mailfrom', `S=unix:/usr/local/var/mailfromd/mailfrom') @end smallexample If you prefer to fiddle directly with @file{sendmail.cf} file, use this statement instead: @smallexample Xmailfrom, S=unix:/usr/local/var/mailfromd/mailfrom @end smallexample @anchor{exporting macros} @cindex f, @command{Sendmail} macro @cindex i, @command{Sendmail} macro @cindex client_addr, @command{Sendmail} macro @cindex confMILTER_MACROS_ENVFROM, mc file directive @cindex @command{Sendmail} macros, exporting @cindex Message-ID, exporting in @file{mc} file Then, you need to make sure all @command{Sendmail} macros used in your @command{mailfromd.rc} file are properly exported. The simplest way to do so is using @command{rc.mailfromd} script, introduced in the previous chapter. Run it with @code{macros} command line argument and copy its output to your @file{sendmail.mc} configuration file: @smallexample $ @kbd{rc.mailfromd macros} @end smallexample If you prefer to work with @file{sendmail.cf} directly, use @option{-c} (@option{--cf}) command line option: @smallexample $ @kbd{rc.mailfromd macros -c} @end smallexample Finally, if you use other mailfromd script file than that already installed (for example, you are preparing a new configuration while the old one is still being used in production environment), give its name in the command line: @smallexample $ @kbd{rc.mailfromd macros newconfig.rc} # @r{or:} $ @kbd{rc.mailfromd macros -c newconfig.rc} @end smallexample If you use this method, you can skip the rest of this chapter. However, if you are a daring sort of person and prefer to do everything manually, follow the instructions below. @xopindex{dump-macros, described} First of all you need to build a list of macros used by handlers in your @file{mailfromd.rc} file. You can obtain it running @command{mailfromd --dump-macros}. This will display all macros used in your handlers, grouped by handler name, for example: @smallexample @group envfrom i, f, @{client_addr@} envrcpt f, @{client_addr@}, @{rcpt_addr@} @end group @end smallexample Now, modify @code{confMILTER_MACROS_@var{handler}} macros in your @file{mc} file. Here, @var{handler} means the uppercase name of the @command{mailfromd} handler you want to export macros to, i.e. the first word on each line of the above @command{mailfromd --dump-macros} output. @emph{Notice,} that in addition to these macros, you should also export the macro @code{i} for the very first handler (@command{rc.mailfromd macros} takes care of it automatically, but you preferred to do everything yourself...) It is necessary in order for @command{mailfromd} to include @samp{Message-ID} in its log messages (@pxref{Message-ID}). For example, given the above macros listing, which corresponds to our sample configuration (@pxref{Filter Script Example}), the @file{sendmail.mc} snippet will contain: @smallexample @group define(`confMILTER_MACROS_ENVFROM',dnl confMILTER_MACROS_ENVFROM `, i, f, @{client_addr@}') define(`confMILTER_MACROS_ENVRCPT',dnl confMILTER_MACROS_ENVRCPT `, f, @{client_addr@}, @{rcpt_addr@}') @end group @end smallexample @cindex s, @command{Sendmail} macro Special attention should be paid to @code{s} macro (@samp{HELO} domain name). In @command{Sendmail} versions up to 8.13.7 (at least) it is available only to @code{helo} handler. If you wish to make it available elsewhere you will need to use the method described in @ref{HELO Domain} Now, if you are a @emph{really} daring person and prefer to do everything manually @emph{and} to hack your @file{sendmail.cf} file directly, you certainly don't need any advices. Nonetheless, here's how the two statements above @emph{could} look in this case: @smallexample @group O Milter.macros.envfrom=i, @{auth_type@}, @{auth_authen@}, \ @{auth_ssf@}, @{auth_author@}, @{mail_mailer@}, @{mail_host@}, \ @{mail_addr@} ,@{mail_addr@}, @{client_addr@}, f O Milter.macros.envrcpt=@{rcpt_mailer@}, @{rcpt_host@}, @{rcpt_addr@} ,i, f, @{client_addr@} @end group @end smallexample @node MeTA1 @chapter Using @command{mailfromd} with MeTA1. @WRITEME{} @node mtasim @chapter @command{mtasim} --- a testing tool @include mtasim.texi @node smap @chapter A universal socket-map program for MeTA1. @include smap.texi @node pmult @chapter Pmilter multiplexer program. @include pmult.texi @node pies @chapter Pies -- a program execution supervisor. @include pies.texi @node Reporting Bugs @chapter How to Report a Bug @quotation @i{Documentation is like sex: when it is good, it is very, very good; and when it is bad, it is better than nothing.}@* Dick Brandon @end quotation Although the author has tried to make this documentation as detailed as is possible and practical, he is well aware that the result is rather ``better than nothing'', than ``very good''. So, if you find that some piece of explanation is lousy or if you find anything that should have been mentioned here, but is not, please report it to @email{bug-mailfromd@@gnu.org.ua}. Similarly, if the program itself fails to meet your expectations, or does not do what is described in this document; if you have found a bug or happen to have any suggestion... or have written a useful function you wish to share with the rest of @command{mailfromd} users, or wish to express your thanks, email it to the same address, @email{bug-mailfromd@@gnu.org.ua}. If you think you've found a bug, please be sure to include maximum information needed to reliably reproduce it, or at least to analyze it. The information needed is: @itemize @item Version of the package you are using. @item Compilation options used when configuring the package. @item Run-time configuration (@file{mailfromd.rc} file and the command line options used). @item Conditions under which the bug appears. @end itemize @node Gacopyz @appendix Gacopyz @include gacopyz.texi @node Time and Date Formats @appendix Time and Date Formats @include strftime.texi @node Upgrading @appendix Upgrading @include upgrade.texi @node Copying This Manual @appendix GNU Free Documentation License @include fdl.texi @node Concept Index @unnumbered Concept Index This is a general index of all issues discussed in this manual @printindex cp @bye