"""An RFC 2821 smtp proxy.
Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]]
This program generally tries to setuid `nobody', unless this flag is
set. The setuid call will fail if this program is not run as root (in
which case, use this flag).
Print the version number and exit.
Use `classname' as the concrete SMTP proxy class. Uses `PureProxy' by
Turn on debugging prints.
Print this message and exit.
If localhost is not given then `localhost' is used, and if localport is not
given then 8025 is used. If remotehost is not given then `localhost' is used,
and if remoteport is not given, then 25 is used.
# This file implements the minimal SMTP protocol as defined in RFC 821. It
# has a hierarchy of classes which implement the backend functionality for the
# smtpd. A number of classes are provided:
# SMTPServer - the base class for the backend. Raises NotImplementedError
# DebuggingServer - simply prints each message it receives on stdout.
# PureProxy - Proxies all messages to a real smtpd which does final
# delivery. One known problem with this class is that it doesn't handle
# SMTP errors from the backend server at all. This should be fixed
# (contributions are welcome!).
# MailmanProxy - An experimental hack to work with GNU Mailman
# <www.list.org>. Using this server as your real incoming smtpd, your
# mailhost will automatically recognize and accept mail destined to Mailman
# lists when those lists are created. Every message not destined for a list
# gets forwarded to a real backend smtpd, as with PureProxy. Again, errors
# are not handled correctly yet.
# Please note that this script requires Python 2.0
# Author: Barry Warsaw <barry@python.org>
# - support mailbox delivery
# - handle error codes from the backend smtpd
__all__ = ["SMTPServer","DebuggingServer","PureProxy","MailmanProxy"]
__version__ = 'Python SMTP proxy version 0.2'
def write(self, msg): pass
print >> sys.stderr, __doc__ % globals()
class SMTPChannel(asynchat.async_chat):
def __init__(self, server, conn, addr):
asynchat.async_chat.__init__(self, conn)
self.__state = self.COMMAND
self.__fqdn = socket.getfqdn()
self.__peer = conn.getpeername()
except socket.error, err:
# a race condition may occur if the other end is closing
# before we can get the peername
if err[0] != errno.ENOTCONN:
print >> DEBUGSTREAM, 'Peer:', repr(self.__peer)
self.push('220 %s %s' % (self.__fqdn, __version__))
self.set_terminator('\r\n')
# Overrides base class for convenience
asynchat.async_chat.push(self, msg + '\r\n')
# Implementation of base class abstract method
def collect_incoming_data(self, data):
# Implementation of base class abstract method
def found_terminator(self):
line = EMPTYSTRING.join(self.__line)
print >> DEBUGSTREAM, 'Data:', repr(line)
if self.__state == self.COMMAND:
self.push('500 Error: bad syntax')
command = line[:i].upper()
method = getattr(self, 'smtp_' + command, None)
self.push('502 Error: command "%s" not implemented' % command)
if self.__state != self.DATA:
self.push('451 Internal confusion')
# Remove extraneous carriage returns and de-transparency according
# to RFC 821, Section 4.5.2.
for text in line.split('\r\n'):
if text and text[0] == '.':
self.__data = NEWLINE.join(data)
status = self.__server.process_message(self.__peer,
self.__state = self.COMMAND
self.set_terminator('\r\n')
# SMTP and ESMTP commands
def smtp_HELO(self, arg):
self.push('501 Syntax: HELO hostname')
self.push('503 Duplicate HELO/EHLO')
self.push('250 %s' % self.__fqdn)
def smtp_NOOP(self, arg):
self.push('501 Syntax: NOOP')
def smtp_QUIT(self, arg):
def __getaddr(self, keyword, arg):
if arg[:keylen].upper() == keyword:
address = arg[keylen:].strip()
elif address[0] == '<' and address[-1] == '>' and address != '<>':
# Addresses can be in the form <person@dom.com> but watch out
# for null address, e.g. <>
def smtp_MAIL(self, arg):
print >> DEBUGSTREAM, '===> MAIL', arg
address = self.__getaddr('FROM:', arg) if arg else None
self.push('501 Syntax: MAIL FROM:<address>')
self.push('503 Error: nested MAIL command')
self.__mailfrom = address
print >> DEBUGSTREAM, 'sender:', self.__mailfrom
def smtp_RCPT(self, arg):
print >> DEBUGSTREAM, '===> RCPT', arg
self.push('503 Error: need MAIL command')
address = self.__getaddr('TO:', arg) if arg else None
self.push('501 Syntax: RCPT TO: <address>')
self.__rcpttos.append(address)
print >> DEBUGSTREAM, 'recips:', self.__rcpttos
def smtp_RSET(self, arg):
self.push('501 Syntax: RSET')
# Resets the sender, recipients, and data, but not the greeting
self.__state = self.COMMAND
def smtp_DATA(self, arg):
self.push('503 Error: need RCPT command')
self.push('501 Syntax: DATA')
self.set_terminator('\r\n.\r\n')
self.push('354 End data with <CR><LF>.<CR><LF>')
class SMTPServer(asyncore.dispatcher):
def __init__(self, localaddr, remoteaddr):
self._localaddr = localaddr
self._remoteaddr = remoteaddr
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
# try to re-use a server port if possible
# cleanup asyncore.socket_map before raising
'%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
self.__class__.__name__, time.ctime(time.time()),
print >> DEBUGSTREAM, 'Incoming connection from %s' % repr(addr)
channel = SMTPChannel(self, conn, addr)
# API for "doing something useful with the message"
def process_message(self, peer, mailfrom, rcpttos, data):
"""Override this abstract method to handle messages from the client.
peer is a tuple containing (ipaddr, port) of the client that made the
socket connection to our smtp port.
mailfrom is the raw address the client claims the message is coming
rcpttos is a list of raw addresses the client wishes to deliver the
data is a string containing the entire full text of the message,
headers (if supplied) and all. It has been `de-transparencied'
according to RFC 821, Section 4.5.2. In other words, a line
containing a `.' followed by other text has had the leading dot
This function should return None, for a normal `250 Ok' response;
otherwise it returns the desired response string in RFC 821 format.
raise NotImplementedError
class DebuggingServer(SMTPServer):
# Do something with the gathered message
def process_message(self, peer, mailfrom, rcpttos, data):
print '---------- MESSAGE FOLLOWS ----------'
if inheaders and not line:
print '------------ END MESSAGE ------------'
class PureProxy(SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data):
# Look for the last header
lines.insert(i, 'X-Peer: %s' % peer[0])
data = NEWLINE.join(lines)
refused = self._deliver(mailfrom, rcpttos, data)
# TBD: what to do with refused addresses?
print >> DEBUGSTREAM, 'we got some refusals:', refused
def _deliver(self, mailfrom, rcpttos, data):
s.connect(self._remoteaddr[0], self._remoteaddr[1])
refused = s.sendmail(mailfrom, rcpttos, data)
except smtplib.SMTPRecipientsRefused, e:
print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
except (socket.error, smtplib.SMTPException), e:
print >> DEBUGSTREAM, 'got', e.__class__
# All recipients were refused. If the exception had an associated
# error code, use it. Otherwise,fake it with a non-triggering
errcode = getattr(e, 'smtp_code', -1)
errmsg = getattr(e, 'smtp_error', 'ignore')
refused[r] = (errcode, errmsg)
class MailmanProxy(PureProxy):
def process_message(self, peer, mailfrom, rcpttos, data):
from cStringIO import StringIO
from Mailman import Utils
from Mailman import Message
from Mailman import MailList
# If the message is to a Mailman mailing list, then we'll invoke the
# Mailman script directly, without going through the real smtpd.
# Otherwise we'll forward it to the local proxy for disposition.
local = rcpt.lower().split('@')[0]
# We allow the following variations on the theme
if not Utils.list_exists(listname) or command not in (
'', 'admin', 'owner', 'request', 'join', 'leave'):
listnames.append((rcpt, listname, command))
# Remove all list recipients from rcpttos and forward what we're not
# going to take care of ourselves. Linear removal should be fine
# since we don't expect a large number of recipients.
for rcpt, listname, command in listnames:
# If there's any non-list destined recipients left,
print >> DEBUGSTREAM, 'forwarding recips:', ' '.join(rcpttos)
refused = self._deliver(mailfrom, rcpttos, data)
# TBD: what to do with refused addresses?
print >> DEBUGSTREAM, 'we got refusals:', refused
# Now deliver directly to the list commands
# These headers are required for the proper execution of Mailman. All
# MTAs in existence seem to add these if the original message doesn't
if not msg.getheader('from'):
if not msg.getheader('date'):
msg['Date'] = time.ctime(time.time())
for rcpt, listname, command in listnames:
print >> DEBUGSTREAM, 'sending message to', rcpt
mlist = mlists.get(listname)
mlist = MailList.MailList(listname, lock=0)
# dispatch on the type of command
msg.Enqueue(mlist, tolist=1)
msg.Enqueue(mlist, toadmin=1)
msg.Enqueue(mlist, toowner=1)
elif command == 'request':
msg.Enqueue(mlist, torequest=1)
elif command in ('join', 'leave'):
msg['Subject'] = 'subscribe'
msg['Subject'] = 'unsubscribe'
msg.Enqueue(mlist, torequest=1)
opts, args = getopt.getopt(
['class=', 'nosetuid', 'version', 'help', 'debug'])
if opt in ('-h', '--help'):
elif opt in ('-V', '--version'):
print >> sys.stderr, __version__
elif opt in ('-n', '--nosetuid'):
elif opt in ('-c', '--class'):
elif opt in ('-d', '--debug'):
# parse the rest of the arguments
localspec = 'localhost:8025'
remotespec = 'localhost:25'
remotespec = 'localhost:25'