miltertest-1.0.0/.github/workflows/publish.yml0000644000000000000000000000113513615410400016412 0ustar00on: push: tags: - v1.* jobs: pypi-publish: name: Upload release to PyPI runs-on: ubuntu-latest environment: publish permissions: id-token: write steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: '3.12' - name: Install dependencies run: python -m pip install -U build pytest - name: Test run: python -m pytest - name: Build run: python -m build - name: Publish package distributions to PyPI uses: pypa/gh-action-pypi-publish@release/v1 miltertest-1.0.0/.github/workflows/test.yml0000644000000000000000000000047713615410400015733 0ustar00on: - push jobs: pytest: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: '3.8' - name: Install dependencies run: python -m pip install pytest - name: Run tests run: python -m pytest miltertest-1.0.0/miltertest/__init__.py0000644000000000000000000000036413615410400015134 0ustar00# Copyright 2011 Chris Siebenmann # Copyright 2024 Paul Arthur MacIain # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ruff: noqa from .client import * from .constants import * from . import codec miltertest-1.0.0/miltertest/client.py0000644000000000000000000002075113615410400014655 0ustar00# Copyright 2011 Chris Siebenmann # Copyright 2024 Paul Arthur MacIain # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Support for having a milter protocol conversation over a network # socket (or at least something that supports .recv). # Much of this support is only useful for something doing the MTA side # of the milter conversation. from . import codec from . import constants __all__ = [ 'MilterConnection', 'MilterError', 'DISPOSITION_REPLIES', 'EOM_REPLIES', ] class MilterError(Exception): """Conversation sequence error""" # Specific command sets: DISPOSITION_REPLIES = frozenset( [ constants.SMFIR_ACCEPT, constants.SMFIR_CONTINUE, constants.SMFIR_REJECT, constants.SMFIR_TEMPFAIL, constants.SMFIR_REPLYCODE, constants.SMFIR_DISCARD, constants.SMFIR_QUARANTINE, ] ) EOM_REPLIES = frozenset( [ *DISPOSITION_REPLIES, constants.SMFIR_ADDRCPT, constants.SMFIR_DELRCPT, constants.SMFIR_ADDRCPT_PAR, constants.SMFIR_REPLBODY, constants.SMFIR_CHGFROM, constants.SMFIR_ADDHEADER, constants.SMFIR_INSHEADER, constants.SMFIR_CHGHEADER, ] ) class MilterConnection: """Maintain a buffered socket connection with another end that is speaking the milter protocol. This class supplies various convenience methods for handling aspects of the milter conversation.""" def __init__(self, sock, blksize=16 * 1024): self.sock = sock self.buf = b'' self.blksize = blksize self.action_flags = None self.protocol_flags = None def _recv(self, eof_ok=False): """Retrieve the next message from the connection message. Returns the decoded message as a tuple of (cmd, paramdict). Raises MilterDecodeError if we see EOF with an incomplete packet. If we see a clean EOF, we normally raise MilterError. If eof_ok is True, we instead return None.""" while True: try: # .decode_msg will fail with an incomplete # error if self.buf is empty, so we don't # have to check for that ourselves. (rcmd, rdict, data) = codec.decode_msg(self.buf) self.buf = data return (rcmd, rdict) except codec.MilterIncomplete: # Fall through to read more data pass data = self.sock.recv(self.blksize) # Check for EOF on the recv. # If we have data left in self.buf, it axiomatically # failed to decode above and so it must be an # incomplete packet. if not data: if self.buf: raise codec.MilterDecodeError('packet truncated by EOF') if not eof_ok: raise MilterError('unexpected EOF') return None self.buf += data del data def recv(self, eof_ok=False): """Read the next real message, one that is not an SMFIR_PROGRESS notification. The arguments are for get_msg.""" while True: r = self._recv(eof_ok) if not r or r[0] != constants.SMFIR_PROGRESS: return r def _send(self, cmd, **args): """Send an encoded milter message. The arguments are the same arguments that codec.encode_msg() takes.""" self.sock.sendall(codec.encode_msg(cmd, **args)) def send_macro(self, cmdcode, **args): """Send an SMFIC_MACRO message for the specific macro. The name and values are taken from the keyword arguments.""" namevals = [x for items in args.items() for x in items] self._send(constants.SMFIC_MACRO, cmdcode=cmdcode, nameval=namevals) # The following methods are only useful if you are handling # the MTA side of the milter conversation. def send_get(self, cmd, **args): """Send a message (as with ._send()) and then wait for a real reply message.""" self._send(cmd, **args) return self.recv() def send_get_specific(self, reply_cmds, cmd, **args): """Send a message and then wait for a real reply message. Raises MilterError if the reply has a command code not in reply_cmds.""" r = self.send_get(cmd, **args) if r[0] not in reply_cmds: raise MilterError('unexpected response: ' + r[0]) return r def send(self, cmd, **kwargs): """Send a message and wait for SMFIR_CONTINUE. If any other response is received, that's an error.""" self.send_get_specific(constants.SMFIR_CONTINUE, cmd, **kwargs) def send_ar(self, cmd, **args): """Send a message and then wait for a real reply message that is from the accept/reject set.""" return self.send_get_specific(DISPOSITION_REPLIES, cmd, **args) def send_body(self, body): """Send the body of a message, properly chunked and handling progress. Returns a progress response. If it is anything except SMFIR_CONTINUE, processing cannot continue because the body may not have been fully transmitted.""" for cstart in range(0, len(body), constants.MILTER_CHUNK_SIZE): cend = cstart + constants.MILTER_CHUNK_SIZE blob = body[cstart:cend] r = self.send_ar(constants.SMFIC_BODY, buf=blob) if r[0] != constants.SMFIR_CONTINUE: raise MilterError(f'Unexpected reply to {constants.SMFIC_BODY}: {r}') return r def send_headers(self, headertuples): """Send message headers, handling progress; returns a progress response, normally SMFIR_CONTINUE. headertuples is a sequence of (header-name, header-value) tuples. If the response is anything but SMFIR_CONTINUE, processing cannot continue because the headers may not have been completely transmitted.""" for hname, hval in headertuples: r = self.send_ar(constants.SMFIC_HEADER, name=hname, value=hval) if r[0] != constants.SMFIR_CONTINUE: raise MilterError(f'Unexpected reply to {constants.SMFIC_HEADER}: {r}') return r def send_eom(self): """Send EOM and collect any EOM actions""" res = [] self._send(constants.SMFIC_BODYEOB) while True: msg = self.recv() res.append(msg) if msg[0] in DISPOSITION_REPLIES: return res # Option negotiation from the MTA and milter view. def optneg_mta(self, actions=constants.SMFI_V6_ACTS, protocol=constants.SMFI_V6_PROT, strict=True): """Perform the initial option negotiation as an MTA. Returns a tuple of (actions, protocol) bitmasks for what we support. If strict is True (the default), raises MilterError if the milter returns an SMFIC_OPTNEG that asks for things we told it that we do not support. """ actions, protocol = codec.optneg_mta_capable(actions, protocol) self.sock.sendall(codec.encode_optneg(actions, protocol)) r = self._recv() if r[0] != constants.SMFIC_OPTNEG: raise MilterError(f'Bad reply to SMFIR_OPTNEG, {r[0]}/{r[1]}') ract = r[1]['actions'] rprot = r[1]['protocol'] if strict: # There should be no bits outside what we claim to # support. if (ract & actions) != ract or (rprot & protocol) != rprot: raise MilterError(f'SMFIR_OPTNEG reply with unsupported bits in actions or protocol: 0x{ract:x}/0x{rprot:x}') else: ract = ract & actions rprot = rprot & protocol self.action_flags = ract self.protocol_flags = rprot return ract, rprot def optneg_milter(self, actions=constants.SMFI_V6_ACTS, protocol=0): """Perform the initial option negotiation as a milter, reading the MTA's SMFIR_OPTNEG and replying with ours. Returns a tuple of (actions, protocol) bitmasks for what both we and the MTA will do.""" r = self._recv() if r[0] != constants.SMFIC_OPTNEG: raise MilterError(f'Expected SMFIR_OPTNEG, received {r[0]}/{r[1]}') ract, rprot = codec.optneg_milter_capable(r[1]['actions'], r[1]['protocol'], actions, protocol) self.sock.sendall(codec.encode_optneg(ract, rprot, is_milter=True)) self.action_flags = ract self.protocol_flags = rprot return (ract, rprot) miltertest-1.0.0/miltertest/codec.py0000644000000000000000000003256713615410400014464 0ustar00# Copyright 2011 Chris Siebenmann # Copyright 2024 Paul Arthur MacIain # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """Encode and decode the milter protocol. This does not do any network conversation; it simply takes data buffers and decodes them to milter messages or encodes milter messages into a binary string. """ import struct from . import constants __all__ = [ 'MilterDecodeError', 'MilterIncomplete', 'MilterProtoError', 'decode_msg', 'encode_msg', 'encode_optneg', 'optneg_milter_capable', 'optneg_mta_capable', ] # (Public) exceptions class MilterProtoError(Exception): """General encoding or decoding failure.""" class MilterIncomplete(MilterProtoError): """The data buffer passed for decoding needs more data.""" class MilterDecodeError(MilterProtoError): """The milter packet we are trying to decode is malformed.""" # This is effectively an internal exception; it is turned into either # MilterIncomplete or MilterDecodeError. class MilterNotEnough(MilterProtoError): """Not enough data to finish decoding.""" # This maps milter commands and responses to the data structures that # they use. The value is a tuple of (fieldname, fieldtype) tuples, in # the order that they occur in the binary encoding. # # A note: # The reverse engineered spec I've seen says that SMFIR_REPLBODY is # the entire new body as one message and is a null-terminated string. # This is wrong. Experience with PureMessage and inspection of the # sendmail source code says that both SMFIC_BODY and SMFIR_REPLBODY # are simply character blocks, and in fact are supposed to have # bare LF converted to CRLF when sending to the milter and converted # back to a bare LF on receive. (We opt not to try to do that at this # level, since it may require spanning block buffers.) # Like SMFIC_BODY, SMFIR_REPLBODY may be sent multiple times (and there # is no requirement that the chunks be large). # codec = { constants.SMFIC_ABORT: (), constants.SMFIC_BODY: (('buf', 'buf'),), constants.SMFIC_CONNECT: ( ('hostname', 'str'), ('family', 'char'), ('port', 'u16'), ('address', 'str'), ), constants.SMFIC_MACRO: (('cmdcode', 'char'), ('nameval', 'strpairs')), constants.SMFIC_BODYEOB: (), constants.SMFIC_HELO: (('helo', 'str'),), constants.SMFIC_QUIT_NC: (), constants.SMFIC_HEADER: (('name', 'str'), ('value', 'str')), constants.SMFIC_MAIL: (('args', 'strs'),), constants.SMFIC_EOH: (), # It might be nice to decode bits for people, but that's too much # work for now. constants.SMFIC_OPTNEG: ( ('version', 'u32'), ('actions', 'u32'), ('protocol', 'u32'), ), constants.SMFIC_QUIT: (), constants.SMFIC_RCPT: (('args', 'strs'),), constants.SMFIC_DATA: (), # Responses. constants.SMFIR_ADDRCPT: (('rcpt', 'str'),), constants.SMFIR_DELRCPT: (('rcpt', 'str'),), constants.SMFIR_ADDRCPT_PAR: (('rcpt', 'str'), ('args', 'strs')), constants.SMFIR_SHUTDOWN: (), constants.SMFIR_ACCEPT: (), constants.SMFIR_REPLBODY: (('buf', 'buf'),), constants.SMFIR_CONTINUE: (), constants.SMFIR_DISCARD: (), constants.SMFIR_CHGFROM: (('from', 'str'), ('args', 'strs')), constants.SMFIR_CONN_FAIL: (), constants.SMFIR_ADDHEADER: (('name', 'str'), ('value', 'str')), constants.SMFIR_INSHEADER: (('index', 'u32'), ('name', 'str'), ('value', 'str')), constants.SMFIR_SETSYMLIST: (('where', 'u32'), ('macros', 'str')), constants.SMFIR_CHGHEADER: (('index', 'u32'), ('name', 'str'), ('value', 'str')), constants.SMFIR_PROGRESS: (), constants.SMFIR_QUARANTINE: (('reason', 'str'),), constants.SMFIR_REJECT: (), constants.SMFIR_SKIP: (), constants.SMFIR_TEMPFAIL: (), # It is kind of lame that we force people to explicitly encode # the space field (with a ' ', to be spec-compliant). But doing # a nicer version requires building an encoding/decoding system # that knows about padding fields, just for this one field in one # message. constants.SMFIR_REPLYCODE: ( ('smtpcode', 'char3'), ('space', 'char'), ('text', 'str'), ), # SMFIC_OPTNEG is also a valid response. } # ---- # Encoders and decoders for all of the different types we know about. # # Content constraints: # char3: must have exactly three characters. We explicitly check this # only on encode; on decode it is implicitly checked by the field # specification. # strpairs: this generates an array, so we check that the array has an # even number of elements (ie, has pairs). The array is allowed # to be empty; as far as I can see, it is and should be valid to # send an SMFIC_MACRO with no macro values set. # strs: this generates an array and we insist that the array has at least # one value. 'strs' is used only by SMFIC_MAIL and SMFIC_RCPT, # and the spec requires that the first array element is the actual # argument ... which must exist, even if it is '<>' for a null sender # or recipient. # # (Because the 'strs' encoder and decoder are also used by strpairs, they # take a private argument to control this behavior.) # Encoders take a value and return that value encoded as a binary string. def encode_buf(val): return val.encode() def encode_str(val): return f'{val}\0'.encode() def encode_strs(val, empty_ok=False): if len(val) == 0 and not empty_ok: # See comment above for why this is justified. raise MilterProtoError('empty string array') return b''.join(encode_str(x) for x in val) def encode_strpairs(val): if len(val) % 2 != 0: raise MilterProtoError('uneven number of name/value pairs') return encode_strs(val, empty_ok=True) def encode_chr(val): return struct.pack('c', val.encode()) def encode_u16(val): return struct.pack('!H', val) def encode_u32(val): return struct.pack('!L', val) def encode_chr3(val): if len(val) != 3: raise MilterProtoError('mis-sized char3') return struct.pack('3s', val.encode()) ## # decoding. # # Decoders take a data buffer and return the decoded value and the # remaining data. If they have completely consumed the data, the # remaining buffer is ''. def unpack_n(data, fmt): """Unpack a single struct module format item from data Returns the unpacked item and the remaining data. Raises MilterNotEnough if there is too little data to contain the item (eg, 3 bytes of data when we are decoding a 32-bit unsigned integer). """ nbytes = struct.calcsize(fmt) if len(data) < nbytes: raise MilterNotEnough('too little data') return (struct.unpack(fmt, data[:nbytes])[0], data[nbytes:]) def decode_chr(data): ret = unpack_n(data, 'c') return (ret[0].decode(), ret[1]) def decode_chr3(data): ret = unpack_n(data, '3s') return (ret[0].decode(), ret[1]) def decode_u16(data): return unpack_n(data, '!H') def decode_u32(data): return unpack_n(data, '!L') def decode_str(data): r = data.split(b'\0', 1) if len(r) != 2: raise MilterNotEnough('short string') return (r[0].decode(), r[1]) # A buffer necessarily consumes all remaining data, since it has no # terminator. def decode_buf(data): return data.decode(), b'' # A string array consumes the rest of the data. def decode_strs(data, empty_ok=False): r = [] while data: s, data = decode_str(data) r.append(s) if not empty_ok and not r: # See comment above for why this is justified. raise MilterNotEnough('no strings in string array') return r, b'' def decode_strpairs(data): r, data = decode_strs(data, empty_ok=True) if len(r) % 2 != 0: raise MilterNotEnough('uneven string pairs') return r, data codectypes = { 'buf': (encode_buf, decode_buf), 'str': (encode_str, decode_str), 'char': (encode_chr, decode_chr), 'char3': (encode_chr3, decode_chr3), 'u16': (encode_u16, decode_u16), 'u32': (encode_u32, decode_u32), 'strs': (encode_strs, decode_strs), 'strpairs': (encode_strpairs, decode_strpairs), } def encode(ctype, val): return codectypes[ctype][0](val) def decode(ctype, data): return codectypes[ctype][1](data) # A milter message itself is: # uint32 len # char cmd # char data[len-1] def encode_msg(cmd, **kwargs): """Encode a milter message to a binary string. Returns the string. The cmd argument is the milter command/response code. Parameters for the command are then given as keyword arguments, eg encode_msg('H', helo="localhost.localdomain").""" if cmd not in codec: raise MilterProtoError(f'encode: unknown command {cmd}') parmlst = codec[cmd] parms = {x[0] for x in parmlst} uparms = set(kwargs.keys()) if parms != uparms: raise MilterProtoError('encode: parameter mismatch') data = [] for name, ctype in parmlst: data.append(encode(ctype, kwargs[name])) dstr = b''.join(data) return struct.pack('!Lc', len(dstr) + 1, cmd.encode()) + dstr def decode_msg(data): """Decode data into a milter message. This returns a tuple of (cmd, msgstruct, remaining_data) where cmd is the milter command/response code, msgstruct is a dictionary of the per-message parameters, and remaining_data is any remaining data from the buffer. We raise MilterIncomplete if there is not enough data yet to fully decode the milter message; read more data and try again. """ # We need to read the initial message length and the command. If # we don't have that much, the message is clearly incomplete. rawdata = data try: mlen, data = decode_u32(data) if mlen == 0: raise MilterDecodeError('zero-length message') cmd, data = decode_chr(data) except MilterNotEnough: raise MilterIncomplete('Need more data') from None if cmd not in codec: raise MilterDecodeError(f'decode: unknown command {cmd}') # The rest of the packet is len-1 bytes long, so if we have less # data than that we need more. dlen = mlen - 1 if len(data) < dlen: raise MilterIncomplete('need more data') # From now onwards, a decoder raising MilterNotEnough means # that the structure inside the message packet was truncated or # incomplete, ie incorrectly encoded. This is a fatal error. rest = data[dlen:] buf = data[:dlen] rstruct = {} for name, ctype in codec[cmd]: try: rstruct[name], buf = decode(ctype, buf) except MilterNotEnough: raise MilterDecodeError(f'Packet contents for {cmd} truncated decoding {ctype}: {mlen} / {buf} / {rawdata[:mlen + 10]}') from None # If the packet buffer has remaining data, it means that there was # extra, un-consumed data after the data we expected. This is a fatal # encoding error. if len(buf) > 0: raise MilterDecodeError(f'Packet contents for {cmd} too long: {mlen} / {buf} / {rawdata[: mlen + 4]}') return (cmd, rstruct, rest) # Option negotiation is somewhat complex. # First, we can't claim to support things that this module can't handle. # Next, we can't accept (or claim to accept) things that the other end # told us it can't handle. # Finally, while we theoretically can advertise support for less than # the full V2 protocol, there are milters that object to this to the # extent that they just drop the connection. # # Note that the protocol handling is significantly different from the # actions handling. In actions, the MTA advertises what actions the # milter can perform and the milter replies with what actions out of # them that it may perform; in the simple case this is SMFI_V2_ACTS # from the MTA and SMFI_V2_ACTS back from the milter. In protocol, # the MTA advertises what protocol steps it supports skipping and the # milter replies with what protocol steps *should* be skipped. # The common case is that the milter client wants all steps that are # in the V6 protocol and not any steps that aren't. def optneg_mta_capable(actions, protocol): """Return a bitmask of actions and protocols that we can support.""" return (actions & constants.SMFI_V6_ACTS, protocol & constants.SMFI_V6_PROT) def optneg_milter_capable(ractions, rprotocol, actions=constants.SMFI_V6_ACTS, protocol=0x0): """Given an MTA's actions and protocol, and our actions and protocol, return an (actions, protocol) tuple suitable for use in an SMFIC_OPTNEG reply. Since our protocol is the steps we wish the MTA to exclude, it will often be zero.""" actions = actions & constants.SMFI_V6_ACTS oactions = ractions & actions pmask = protocol | (0xFFFFFFF ^ constants.SMFI_V6_PROT) oprotocol = rprotocol & pmask return (oactions, oprotocol) def encode_optneg(actions, protocol, is_milter=False): """Encode an SMFIC_OPTNEG message based on the supplied actions and protocol. Actions and protocol should normally have been passed through either optneg_mta_capable() or optneg_milter_capable() depending on which side of the protocol you are implementing.""" # We never encode any actions beyond what we support. actions = actions & constants.SMFI_V6_ACTS # Unless we are handling the milter side of the protocol, # clamp the protocol bitmask to what we support. if not is_milter: protocol = protocol & constants.SMFI_V6_PROT return encode_msg(constants.SMFIC_OPTNEG, version=constants.MILTER_VERSION, actions=actions, protocol=protocol) miltertest-1.0.0/miltertest/constants.py0000644000000000000000000001056113615410400015411 0ustar00# Copyright 2011 Chris Siebenmann # Copyright 2024 Paul Arthur MacIain # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Constants for the milter protocol. # fmt: off MILTER_VERSION = 6 # Milter version we claim to speak MILTER_CHUNK_SIZE = 65535 # How large an SMFIC_BODY body can be # Address families SMFIA_UNKNOWN = 'U' SMFIA_UNIX = 'L' SMFIA_INET = '4' SMFIA_INET6 = '6' # Commands SMFIC_ABORT = 'A' SMFIC_BODY = 'B' # body chunk SMFIC_CONNECT = 'C' # connection information SMFIC_MACRO = 'D' # define macro SMFIC_BODYEOB = 'E' # final body chunk SMFIC_HELO = 'H' # HELO or EHLO SMFIC_QUIT_NC = 'K' # QUIT but new connection follows SMFIC_HEADER = 'L' SMFIC_MAIL = 'M' # MAIL FROM SMFIC_EOH = 'N' SMFIC_OPTNEG = 'O' # option negotiation SMFIC_QUIT = 'Q' SMFIC_RCPT = 'R' # RCPT TO SMFIC_DATA = 'T' # What the filter might do SMFIF_ADDHDRS = 0x0001 # add headers SMFIF_CHGBODY = 0x0002 # replace body SMFIF_ADDRCPT = 0x0004 # add recipients SMFIF_DELRCPT = 0x0008 # delete recipientes SMFIF_CHGHDRS = 0x0010 # change and delete headers SMFIF_QUARANTINE = 0x0020 SMFIF_CHGFROM = 0x0040 # change envelope sender SMFIF_ADDRCPT_PAR = 0x0080 # add recipients including arguments SMFIF_SETSYMLIST = 0x0100 # send set of symbols that it wants # Macro places SMFIM_CONNECT = 0 # connect SMFIM_HELO = 1 # HELO/EHLO SMFIM_ENVFROM = 2 # MAIL FROM SMFIM_ENVRCPT = 3 # RCPT TO SMFIM_DATA = 4 # DATA SMFIM_EOM = 5 # end of message SMFIM_EOH = 6 # end of header # bitmask of actions supported in each protocol version SMFI_V1_ACTS = 0x000f SMFI_V2_ACTS = 0x003f SMFI_V6_ACTS = 0x01ff # protocol negotiation SMFIP_NOCONNECT = 0x00000001 # MTA should not send connection info SMFIP_NOHELO = 0x00000002 # MTA should not send hello SMFIP_NOMAIL = 0x00000004 # MTA should not send MAIL SMFIP_NORCPT = 0x00000008 # MTA should not send RCPT SMFIP_NOBODY = 0x00000010 # MTA should not send body SMFIP_NOHDRS = 0x00000020 # MTA should not send headers SMFIP_NOEOH = 0x00000040 # MTA should not send EOH SMFIP_NR_HDR = 0x00000080 # No reply for headers SMFIP_NOUNKNOWN = 0x00000100 # MTA should not send unknown commands SMFIP_NODATA = 0x00000200 # MTA should not send DATA SMFIP_SKIP = 0x00000400 # MTA understands SMFIS_SKIP SMFIP_RCPT_REJ = 0x00000800 # MTA should also send rejected RCPTs SMFIP_NR_CONN = 0x00001000 # No reply for connect SMFIP_NR_HELO = 0x00002000 # No reply for HELO SMFIP_NR_MAIL = 0x00004000 # No reply for MAIL SMFIP_NR_RCPT = 0x00008000 # No reply for RCPT SMFIP_NR_DATA = 0x00010000 # No reply for DATA SMFIP_NR_UNKN = 0x00020000 # No reply for UNKN SMFIP_NR_EOH = 0x00040000 # No reply for eoh SMFIP_NR_BODY = 0x00080000 # No reply for body chunk SMFIP_HDR_LEADSPC = 0x00100000 # header value leading space SMFIP_MDS_256K = 0x10000000 # MILTER_MAX_DATA_SIZE=256K SMFIP_MDS_1M = 0x20000000 # MILTER_MAX_DATA_SIZE=1M # bitmask of protocol steps supported in each version SMFI_V1_PROT = 0x00003f SMFI_V2_PROT = 0x00007f SMFI_V6_PROT = 0x1fffff # Acceptable response commands/codes to return to sendmail (with accompanying # command data). SMFIR_ADDRCPT = '+' # Add recipient SMFIR_DELRCPT = '-' # Delete recipient SMFIR_ADDRCPT_PAR = '2' # Add recipient (including ESMTP args) SMFIR_SHUTDOWN = '4' # 421: shutdown (internal to MTA) SMFIR_ACCEPT = 'a' # Accept SMFIR_REPLBODY = 'b' # Replace body (chunk) SMFIR_CONTINUE = 'c' # Continue SMFIR_DISCARD = 'd' # Discard SMFIR_CHGFROM = 'e' # Change envelope sender (from) SMFIR_CONN_FAIL = 'f' # Cause a connection failure SMFIR_ADDHEADER = 'h' # Add header SMFIR_INSHEADER = 'i' # Insert header SMFIR_SETSYMLIST = 'l' # Set list of symbols (macros) SMFIR_CHGHEADER = 'm' # Change header SMFIR_PROGRESS = 'p' # Progress SMFIR_QUARANTINE = 'q' # Quarantine SMFIR_REJECT = 'r' # Reject SMFIR_SKIP = 's' # Skip SMFIR_TEMPFAIL = 't' # Tempfail SMFIR_REPLYCODE = 'y' # Reply code miltertest-1.0.0/tests/test_client.py0000644000000000000000000002235513615410400014664 0ustar00# Copyright 2011 Chris Siebenmann # Copyright 2024 Paul Arthur MacIain # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) import unittest from miltertest import codec from miltertest import constants from miltertest import ( MilterConnection, MilterError, ) class ConvError(Exception): pass # --- # test infrastructure # These are from the perspective of the socket; it expects you to read # or write. READ, WRITE = object(), object() # A fake socket object that implements .recv() and .sendall(). # It is fed a conversation that it expects (a sequence of read and # write operations), and then verifies that the sequence that happens # is what you told it to expect. # Because this is specific to verifying the milter conversation, it # does not bother having to know exactly what the written messages are; # for our purpose, it is enough to know their type. # (Optionally it can also know the result dictionary and verify it, # because that turned out to be necessary.) class FakeSocket: def __init__(self, conv=None): if conv is None: conv = [] self.conv = conv self.cindex = 0 # verify that a .recv() or .sendall() is proper, ie that it # is the next expected action. def _verify_conv(self, adir): if self.cindex >= len(self.conv): raise ConvError('unexpected action') if adir != self.conv[self.cindex][0]: raise ConvError('sequence mismatch') def _add(self, adir, what): self.conv.append((adir, what)) def addReadMsg(self, cmd, **args): """Add a message to be read; arguments are as per encode_msg.""" self._add(READ, codec.encode_msg(cmd, **args)) def addRead(self, buf): """Add a raw string to be read.""" self._add(READ, buf) def addWrite(self, cmd): """Add an expected write command.""" self._add(WRITE, (cmd,)) def addFullWrite(self, cmd, **args): """Add an expected write command and its full parameters.""" self._add(WRITE, (cmd, args)) def addMTAWrite(self, cmd): """Add an expected write command and then an SMFIR_CONTINUE reply to it.""" self._add(WRITE, (cmd,)) self.addReadMsg(constants.SMFIR_CONTINUE) def isEmpty(self): """Returns whether or not all expected reads and writes have been consumed.""" return self.cindex == len(self.conv) # # The actual socket routines we emulate. def recv(self, nbytes): self._verify_conv(READ) # nbytes should be at least as large as what we are # scheduled to send. _, obj = self.conv[self.cindex] self.cindex += 1 if isinstance(obj, (list, tuple)): obj = codec.encode_msg(obj[0], **obj[1]) if len(obj) > nbytes: raise ConvError('short read') return obj def sendall(self, buf): self._verify_conv(WRITE) # We verify that we got the right sort of stuff r = codec.decode_msg(buf) _, wres = self.conv[self.cindex] self.cindex += 1 otype = wres[0] if r[0] != otype: raise ConvError(f'Received unexpected reply {r[0]} instead of {otype}') if len(wres) > 1 and r[1] != wres[1]: raise ConvError(f'Unexpected reply parameters: {r[1]} instead of {wres[1]}') # ----- # class basicTests(unittest.TestCase): def testShortReads(self): """Test that we correctly read multiple times to reassemble a short message, and that we get the right answer.""" ams = constants.SMFIC_CONNECT adict = {'hostname': 'localhost', 'family': '4', 'port': 1678, 'address': '127.10.10.1'} msg = codec.encode_msg(ams, **adict) msg1, msg2 = msg[:10], msg[10:] s = FakeSocket() s.addRead(msg1) s.addRead(msg2) mbuf = MilterConnection(s) rcmd, rdict = mbuf._recv() self.assertEqual(ams, rcmd) self.assertEqual(adict, rdict) self.assertTrue(s.isEmpty()) def testProgressReads(self): """Test that we correctly read multiple progress messages before getting the real one.""" s = FakeSocket() s.addReadMsg(constants.SMFIR_PROGRESS) s.addReadMsg(constants.SMFIR_PROGRESS) s.addReadMsg(constants.SMFIR_PROGRESS) s.addReadMsg( constants.SMFIR_DELRCPT, rcpt=[ '', ], ) mbuf = MilterConnection(s) rcmd, rdict = mbuf.recv() self.assertEqual(rcmd, constants.SMFIR_DELRCPT) self.assertTrue(s.isEmpty()) class continuedTests(unittest.TestCase): def testHeaders(self): """Test that we handle writing a sequence of headers in the way that we expect.""" s = FakeSocket() hdrs = (('From', 'Chris'), ('To', 'Simon'), ('Subject', 'Yak')) for _ in hdrs: s.addMTAWrite(constants.SMFIC_HEADER) mbuf = MilterConnection(s) rcmd, rdict = mbuf.send_headers(hdrs) self.assertEqual(rcmd, constants.SMFIR_CONTINUE) self.assertTrue(s.isEmpty()) def testShortHeaders(self): """Test that we return early from a series of header writes if SMFIR_CONTINUE is not the code returned.""" s = FakeSocket() hdrs = (('From', 'Chris'), ('To', 'Simon'), ('Subject', 'Yak')) s.addMTAWrite(constants.SMFIC_HEADER) s.addWrite(constants.SMFIC_HEADER) s.addReadMsg(constants.SMFIR_ACCEPT) with self.assertRaises(MilterError): MilterConnection(s).send_headers(hdrs) self.assertTrue(s.isEmpty()) def testBodySequence(self): """Test that we handle writing a large body in the way we expect.""" s = FakeSocket() body = 3 * 65535 * '*' s.addMTAWrite(constants.SMFIC_BODY) s.addMTAWrite(constants.SMFIC_BODY) s.addMTAWrite(constants.SMFIC_BODY) mbuf = MilterConnection(s) rcmd, rdict = mbuf.send_body(body) self.assertEqual(rcmd, constants.SMFIR_CONTINUE) self.assertTrue(s.isEmpty()) def testShortBody(self): """Test that we return early from a series of body writes if SMFIR_CONTINUE is not the code returned.""" s = FakeSocket() body = 3 * 65535 * '*' s.addMTAWrite(constants.SMFIC_BODY) s.addWrite(constants.SMFIC_BODY) s.addReadMsg(constants.SMFIR_ACCEPT) with self.assertRaises(MilterError): MilterConnection(s).send_body(body) self.assertTrue(s.isEmpty()) optneg_mta_pairs = ( ((constants.SMFI_V6_ACTS, constants.SMFI_V6_PROT), (constants.SMFI_V6_ACTS, constants.SMFI_V6_PROT)), ((constants.SMFI_V2_ACTS, constants.SMFI_V2_PROT), (constants.SMFI_V2_ACTS, constants.SMFI_V2_PROT)), ((0x10, 0x10), (0x10, 0x10)), ) def testMTAOptneg(self): """Test that the MTA version of option negotiation returns what we expect it to.""" for a, b in self.optneg_mta_pairs: s = FakeSocket() s.addWrite(constants.SMFIC_OPTNEG) s.addReadMsg(constants.SMFIC_OPTNEG, version=constants.MILTER_VERSION, actions=a[0], protocol=a[1]) # strict=True would blow up on the last test. ract, rprot = MilterConnection(s).optneg_mta(strict=False) self.assertEqual(ract, b[0]) self.assertEqual(rprot, b[1]) optneg_exc_errors = ( (constants.SMFI_V1_ACTS, 0xFFFFFF), (0xFFFFFF, constants.SMFI_V1_PROT), (0xFFFFFF, 0xFFFFFF), ) def testMilterONOutside(self): """Test that the MTA version of option negotiation errors out if there are excess bits in the milter reply.""" for act, prot in self.optneg_exc_errors: s = FakeSocket() s.addWrite(constants.SMFIC_OPTNEG) s.addReadMsg(constants.SMFIC_OPTNEG, version=constants.MILTER_VERSION, actions=act, protocol=prot) bm = MilterConnection(s) self.assertRaises(MilterError, bm.optneg_mta) optneg_milter_pairs = ( # The basic case; MTA says all V6 actions, all V6 protocol # exclusions, we say we'll take all actions and we want the # MTA not to exclude any protocol steps. ((constants.SMFI_V6_ACTS, constants.SMFI_V6_PROT), (constants.SMFI_V6_ACTS, 0x0)), # MTA offers additional protocol exclusions, we tell it not # to do them but to do all V6 protocol actions. ((constants.SMFI_V6_ACTS, 0xFFFFFF), (constants.SMFI_V6_ACTS, 0xE00000)), # MTA offers additional actions, we decline. ((constants.SMFI_V6_ACTS, constants.SMFI_V6_PROT), (constants.SMFI_V2_ACTS, 0x00)), ) def testMilterOptneg(self): """Test the milter version of option negotiation.""" for a, b in self.optneg_milter_pairs: s = FakeSocket() s.addReadMsg(constants.SMFIC_OPTNEG, version=constants.MILTER_VERSION, actions=a[0], protocol=a[1]) s.addFullWrite(constants.SMFIC_OPTNEG, version=constants.MILTER_VERSION, actions=b[0], protocol=b[1]) ract, rprot = MilterConnection(s).optneg_milter(actions=b[0]) self.assertEqual(ract, b[0]) self.assertEqual(rprot, b[1]) if __name__ == '__main__': unittest.main() miltertest-1.0.0/tests/test_codec.py0000644000000000000000000002534613615410400014466 0ustar00# Copyright 2011 Chris Siebenmann # Copyright 2024 Paul Arthur MacIain # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # TODO: we should have some real, validated binary messages so that we can # test proper interoperability. import struct import unittest from miltertest import codec from miltertest import constants class codingTests(unittest.TestCase): ctypes = ( ('char', 'A'), ('char3', 'abc'), ('u16', 10), ('u32', 30000), ('str', 'a long string'), ( 'strs', [ 'a', 'b', 'c', ], ), ( 'strpairs', [ 'd', 'e', 'f', 'g', 'h', 'i', ], ), ('buf', 'a buffer with an embedded \0 just for fun'), # Corner case for strings ('str', ''), ('strs', ['a', '']), ('strpairs', []), # these are corner cases for unsigned int ranges ('u16', (2**16) - 1), ('u32', (2**32) - 1), ) def testEncodeDecode(self): """Test that we can encode and then decode an example of every known type.""" for ctype, val in self.ctypes: d = codec.encode(ctype, val) r, d2 = codec.decode(ctype, d) self.assertEqual(val, r) # also, nothing left over from the data self.assertEqual(d2, b'') # Test bad encodes that should error out. bencs = ( ('char3', 'a'), ('char3', 'abcd'), ('strs', []), ( 'strpairs', [ 'a', ], ), ) def testBadEncode(self): """Test that certain things fail to encode with errors.""" for ctype, val in self.bencs: self.assertRaises(codec.MilterProtoError, codec.encode, ctype, val) bdecs = ( # No terminating \0 ('str', b'abcdef'), # uneven number of pairs ('strpairs', b'abc\0def\0ghi\0'), # No strings in string array ('strs', b''), ) def testBadDecode(self): """Test that certain things fail to decode.""" for ctype, data in self.bdecs: self.assertRaises(codec.MilterProtoError, codec.decode, ctype, data) # A sample message for every milter protocol message that we know about. sample_msgs = [ ('A', {}), ('B', {'buf': 'abcdefghi\nthis is a test, yes.\n\t-cks'}), ('C', {'hostname': 'localhost', 'family': '4', 'port': 3000, 'address': '127.0.0.1'}), ('D', {'cmdcode': 'R', 'nameval': ['rcpt_mailer', 'abc', 'rcpt_host', 'localhost', 'rcpt_addr', 'cks']}), ('E', {}), ('H', {'helo': 'localhost.localdomain'}), ('K', {}), ('L', {'name': 'Subject', 'value': 'Tedium'}), ('M', {'args': ['<>', 'haha']}), ('N', {}), ('O', {'version': 2, 'actions': 0x01, 'protocol': 0x02}), ('Q', {}), ('R', {'args': ['', 'SIZE=100']}), ('T', {}), ('+', {'rcpt': ''}), ('-', {'rcpt': ''}), ('2', {'rcpt': '', 'args': ['SIZE=100']}), ('4', {}), ('a', {}), ('b', {'buf': 'ARGLEBARGLE TEDIUM'}), ('c', {}), ('d', {}), ('e', {'from': '', 'args': ['AUTH=bar']}), ('f', {}), ('h', {'name': 'X-Annoyance', 'value': 'Testing'}), ('l', {'where': 1, 'macros': 'i dunno, probably something'}), ('m', {'index': 10, 'name': 'X-Spam-Goblets', 'value': '100% canned'}), ('p', {}), ('q', {'reason': 'Your mother was an Englishman'}), ('r', {}), ('s', {}), ('t', {}), ('y', {'smtpcode': '450', 'space': ' ', 'text': 'lazyness strikes'}), # It is explicitly valid to have an empty value for a modified # header; this deletes the header. We test that we can at least # generate such a message. ('m', {'index': 1, 'name': 'Subject', 'value': ''}), # Macros can be empty. ('D', {'cmdcode': 'H', 'nameval': []}), ] class basicTests(unittest.TestCase): def testMessageEncode(self): """Can we encode every sample message to a non-zero message that has the cmd code as its fifth character?""" for cmd, args in sample_msgs: r = codec.encode_msg(cmd, **args) self.assertNotEqual(len(r), 0) self.assertTrue(len(r) >= 5) self.assertEqual(chr(r[4]), cmd) if not args: self.assertEqual(len(r), 5) def testMessageDecode(self): """Test that encoded messages decode back to something that is identical to what we started with.""" suffix = b'\nabc' for cmd, args in sample_msgs: r = codec.encode_msg(cmd, **args) dcmd, dargs, rest = codec.decode_msg(r) self.assertEqual(cmd, dcmd) self.assertEqual(args, dargs) self.assertEqual(rest, b'') # As a bonus, test that decoding with more data works # right for all messages. dcmd, dargs, rest = codec.decode_msg(r + suffix) self.assertEqual(rest, suffix) def testTruncatedDecode(self): """Test that we signal not-enough on truncated decodes.""" for cmd, args in sample_msgs: r = codec.encode_msg(cmd, **args) r = r[:-1] self.assertRaises(codec.MilterIncomplete, codec.decode_msg, r) def testBrokenCommands(self): """Sleazily test that we signal errors on malformed packets.""" # Encode something that has no arguments. r = codec.encode_msg('A') # Break the command byte to something that doesn't exist. r = r[:4] + b'!' self.assertRaises(codec.MilterDecodeError, codec.decode_msg, r) # Break the command byte to something that requires arguments. r = r[:4] + b'D' self.assertRaises(codec.MilterDecodeError, codec.decode_msg, r) # Change the claimed length of a message by delta (may be positive # or negative). If this lengthens the message, you need to supply # extra actual data yourself. def _changelen(self, msg, delta): tlen = struct.unpack('!L', msg[:4])[0] tlen = tlen + delta if tlen <= 0: raise IndexError('new length too short') return struct.pack('!L', tlen) + msg[4:] def testBrokenLength(self): """Sleazily test for a too-short version of every message.""" minlen = struct.pack('!L', 1) for cmd, args in sample_msgs: # We can't shorten a message that has no arguments. if not args: continue # We can't shorten or grow SMFIC_BODY or # SMFIR_REPLYBODY messages. if cmd in (constants.SMFIC_BODY, constants.SMFIR_REPLBODY): continue r = codec.encode_msg(cmd, **args) r = self._changelen(r, -1) self.assertRaises(codec.MilterDecodeError, codec.decode_msg, r) # See what happens with a minimum-length message. r = minlen + r[4:] self.assertRaises(codec.MilterDecodeError, codec.decode_msg, r) def testExtraLength(self): """Sleazily test that messages with extra packet data fail to decode.""" for cmd, args in sample_msgs: # We can't shorten or grow SMFIC_BODY or # SMFIR_REPLYBODY messages. if cmd in (constants.SMFIC_BODY, constants.SMFIR_REPLBODY): continue r = codec.encode_msg(cmd, **args) # remember: we've got to supply the actual extra # data, or we just get a 'message incomplete' note. r = self._changelen(r, +10) + (b'*' * 10) self.assertRaises(codec.MilterDecodeError, codec.decode_msg, r) def testZeroLength(self): """Trying to decode a zero-length message should fail with a decode error.""" zlen = struct.pack('!L', 0) self.assertRaises(codec.MilterDecodeError, codec.decode_msg, zlen) def testExtraArgsEncode(self): """Test that adding arguments results in an encode error.""" for cmd, args in sample_msgs: args = args.copy() args['blarg'] = 10 self.assertRaises(codec.MilterProtoError, codec.encode_msg, cmd, **args) def testMissingArgsEncode(self): """Test that removing arguments results in an encode error.""" for cmd, args in sample_msgs: # Can't remove an argument if we don't have one if not args: continue args = args.copy() args.popitem() self.assertRaises(codec.MilterProtoError, codec.encode_msg, cmd, **args) # These test results are from the MTA side of things. optneg_tests = ( ((0x0, 0x0), (0x0, 0x0)), ((0xFFFFFF, 0xFFFFFF), (constants.SMFI_V6_ACTS, constants.SMFI_V6_PROT)), ((0x10, 0x10), (0x10, 0x10)), ((constants.SMFI_V2_ACTS, constants.SMFI_V2_PROT), (constants.SMFI_V2_ACTS, constants.SMFI_V2_PROT)), ) def testOptnegCap(self): """Test that optneg_mta_capable correctly masks things.""" for a, b in self.optneg_tests: r = codec.optneg_mta_capable(a[0], a[1]) self.assertEqual(r, b) optneg_milter_tests = ( ((constants.SMFI_V6_ACTS, constants.SMFI_V6_PROT), (constants.SMFI_V6_ACTS, 0), (constants.SMFI_V6_ACTS, 0)), ((constants.SMFI_V2_ACTS, constants.SMFI_V2_PROT), (constants.SMFI_V2_ACTS, 0), (constants.SMFI_V2_ACTS, 0)), ((constants.SMFI_V2_ACTS, 0xFFFFFF), (constants.SMFI_V2_ACTS, 0), (constants.SMFI_V2_ACTS, 0xE00000)), ) def testOptnegMilterCap(self): """Test that optneg_milter_capable correctly masks things.""" for a, b, c in self.optneg_milter_tests: r = codec.optneg_milter_capable(a[0], a[1], b[0], b[1]) self.assertEqual(r, c) def testOptnegEncode(self): """Test that encode_optneg() works right.""" return for a, b in self.optneg_tests: r = codec.encode_optneg(actions=a[0], protocol=a[1]) rcmd, rdict, data = codec.decode_msg(r) self.assertEqual(data, '') self.assertEqual(rcmd, constants.SMFIC_OPTNEG) rpair = (rdict['actions'], rdict['protocol']) self.assertEqual(rpair, b) def testOptnegMilterEncode(self): """Test encode_optneg() with is_milter=True, which should not clamp protocol to SMFI_V6_PROT.""" r = codec.encode_optneg(actions=0xFFFFFF, protocol=0xFFFFFF, is_milter=True) rcmd, rdict, data = codec.decode_msg(r) self.assertEqual(rdict['actions'], constants.SMFI_V6_ACTS) self.assertEqual(rdict['protocol'], 0xFFFFFF) if __name__ == '__main__': unittest.main() miltertest-1.0.0/.gitignore0000644000000000000000000000001713615410400012612 0ustar00*~ *.pyc dist/ miltertest-1.0.0/COPYING0000644000000000000000000010451513615410400011665 0ustar00 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . miltertest-1.0.0/README.md0000644000000000000000000000057413615410400012111 0ustar00# miltertest This is a pure Python module implementing the milter protocol, based on Chris Siebenmann's work in [python-milter-tools](https://github.com/siebenmann/python-milter-tools). The main goal is to provide an acceptable interface for acting as an MTA to test milter implementations; it may also be usable for implementing milters, but there are better options for that. miltertest-1.0.0/pyproject.toml0000644000000000000000000000137013615410400013541 0ustar00[project] name = "miltertest" version = "1.0.0" authors = [ { name="Paul Arthur", email="paul.arthur@flowerysong.com" }, ] description = "Pure Python implementation of the milter protocol" readme = "README.md" requires-python = ">=3.8" classifiers = [ "Programming Language :: Python :: 3", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Operating System :: OS Independent", ] [project.urls] Homepage = "https://github.com/flowerysong/miltertest" [build-system] requires = ["hatchling"] build-backend = "hatchling.build" [tool.pytest.ini_options] addopts = [ "--import-mode=importlib", ] [tool.ruff] line-length = 160 [tool.ruff.format] quote-style = 'single' [tool.ruff.lint] select = ["F", "E", "W", "B", "RUF"] miltertest-1.0.0/PKG-INFO0000644000000000000000000000155013615410400011722 0ustar00Metadata-Version: 2.3 Name: miltertest Version: 1.0.0 Summary: Pure Python implementation of the milter protocol Project-URL: Homepage, https://github.com/flowerysong/miltertest Author-email: Paul Arthur License-File: COPYING Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 3 Requires-Python: >=3.8 Description-Content-Type: text/markdown # miltertest This is a pure Python module implementing the milter protocol, based on Chris Siebenmann's work in [python-milter-tools](https://github.com/siebenmann/python-milter-tools). The main goal is to provide an acceptable interface for acting as an MTA to test milter implementations; it may also be usable for implementing milters, but there are better options for that.