diff -r a82d7e028458 Doc/library/smtpd.rst --- a/Doc/library/smtpd.rst Mon Jun 16 19:26:56 2014 -0400 +++ b/Doc/library/smtpd.rst Tue Jun 17 02:29:49 2014 +0200 @@ -20,7 +20,8 @@ Additionally the SMTPChannel may be extended to implement very specific interaction behaviour with SMTP clients. -The code supports :RFC:`5321`, plus the :rfc:`1870` SIZE extension. +The code supports :RFC:`5321`, plus the :rfc:`1870` SIZE and :rfc:`6531` +SMTPUTF8 extensions. SMTPServer Objects @@ -28,7 +29,7 @@ .. class:: SMTPServer(localaddr, remoteaddr, data_size_limit=33554432,\ - map=None, decode_data=True) + map=None, enable_SMTPUTF8=False, decode_data=True) Create a new :class:`SMTPServer` object, which binds to local address *localaddr*. It will treat *remoteaddr* as an upstream SMTP relayer. It @@ -39,6 +40,12 @@ accepted in a ``DATA`` command. A value of ``None`` or ``0`` means no limit. + *enable_SMTPUTF8* determins whether the ``SMTPUTF8`` extension (as defined + in :RFC:`6531`) should be enabled. A :exc:`ValueError` is raised if + *decode_data* is set to ``True`` at the same time. Make sure to implement + :meth:`process_unicode_message` to support ``SMTPUTF8``. + Default: ``False``. + A dictionary can be specified in *map* to avoid using a global socket map. *decode_data* specifies whether the data portion of the SMTP transaction @@ -60,6 +67,16 @@ argument will be a unicode string. If it is set to ``False``, it will be a bytes object. + .. method:: process_unicode_message(peer, mailfrom, rcpttos, data) + + Same as :meth:`process_message` but for messages which require + ``SMTPUTF8`` support. This method is called instead of + :meth:`process_message` if the client reqested ``SMTPUTF8`` support + after the server announced it. + + This function should return ``None``, for a normal ``250 Ok`` response; + otherwise it returns the desired response string in :RFC:`6531` format. + .. attribute:: channel_class Override this in subclasses to use a custom :class:`SMTPChannel` for @@ -68,8 +85,12 @@ .. versionchanged:: 3.4 The *map* argument was added. - .. versionchanged:: 3.5 the *decode_data* argument was added, and *localaddr* - and *remoteaddr* may now contain IPv6 addresses. + .. versionchanged:: 3.5 + the *decode_data* and *enable_SMTPUTF8* arguments were added, and + *localaddr* and *remoteaddr* may now contain IPv6 addresses. + + .. versionadded:: 3.5 + the :meth:`process_unicode_message` method. DebuggingServer Objects @@ -109,7 +130,7 @@ ------------------- .. class:: SMTPChannel(server, conn, addr, data_size_limit=33554432,\ - map=None, decode_data=True) + map=None, enable_SMTPUTF8=False, decode_data=True) Create a new :class:`SMTPChannel` object which manages the communication between the server and a single SMTP client. @@ -120,6 +141,11 @@ accepted in a ``DATA`` command. A value of ``None`` or ``0`` means no limit. + *enable_SMTPUTF8* determins whether the ``SMTPUTF8`` extension (as defined + in :RFC:`6531`) should be enabled. A :exc:`ValueError` is raised if + *decode_data* is set to ``True`` at the same time. + Default: ``False``. + A dictionary can be specified in *map* to avoid using a global socket map. *decode_data* specifies whether the data portion of the SMTP transaction @@ -131,7 +157,7 @@ :attr:`SMTPServer.channel_class` of your :class:`SMTPServer`. .. versionchanged:: 3.5 - the *decode_data* argument was added. + the *decode_data* and *enable_SMTPUTF8* arguments were added. The :class:`SMTPChannel` has the following instance variables: diff -r a82d7e028458 Lib/smtpd.py --- a/Lib/smtpd.py Mon Jun 16 19:26:56 2014 -0400 +++ b/Lib/smtpd.py Tue Jun 17 02:29:49 2014 +0200 @@ -1,5 +1,5 @@ #! /usr/bin/env python3 -"""An RFC 5321 smtp proxy. +"""An RFC 5321 (opt. RFC 6532) smtp proxy. Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]] @@ -25,6 +25,10 @@ Restrict the total size of the incoming message to "limit" number of bytes via the RFC 1870 SIZE extension. Defaults to 33554432 bytes. + --smtputf8 + -u + Enable the SMTPUTF8 extension and behave as RFC 6532 smtp proxy. + --debug -d Turn on debugging prints. @@ -113,20 +117,29 @@ COMMAND = 0 DATA = 1 - command_size_limit = 512 - command_size_limits = collections.defaultdict(lambda x=command_size_limit: x) - command_size_limits.update({ - 'MAIL': command_size_limit + 26, - }) - max_command_size_limit = max(command_size_limits.values()) + command_size_limits = collections.defaultdict(lambda : 512) + + @property + def max_command_size_limit(self): + try: + return max(self.command_size_limits.values()) + except ValueError: + return self.command_size_limits.default_factory() def __init__(self, server, conn, addr, data_size_limit=DATA_SIZE_DEFAULT, - map=None, decode_data=None): + map=None, enable_SMTPUTF8=False, decode_data=None): asynchat.async_chat.__init__(self, conn, map=map) self.smtp_server = server self.conn = conn self.addr = addr self.data_size_limit = data_size_limit + self.enable_SMTPUTF8 = enable_SMTPUTF8 + if enable_SMTPUTF8: + if decode_data: + warn("Setting value of decode_data to False (enable_SMTPUTF8" + " implies this). Do not set decode_data to True to" + " suppress this warning.") + decode_data = False if decode_data is None: warn("The decode_data default of True will change to False in 3.6;" " specify an explicit value for this keyword", @@ -143,14 +156,8 @@ self._linesep = b'\r\n' self._dotsep = b'.' self._newline = b'\n' - self.received_lines = [] - self.smtp_state = self.COMMAND - self.seen_greeting = '' - self.mailfrom = None - self.rcpttos = [] - self.received_data = '' + self._set_initial_state() self.fqdn = socket.getfqdn() - self.num_bytes = 0 try: self.peer = conn.getpeername() except OSError as err: @@ -162,8 +169,27 @@ return print('Peer:', repr(self.peer), file=DEBUGSTREAM) self.push('220 %s %s' % (self.fqdn, __version__)) + + def _set_initial_state(self, + skip_greeting=False, + skip_received_data=False): + """Set all variables which may change by SMTP conversations to their + initial state. + """ + self.smtp_state = self.COMMAND + self.mailfrom = None + self.rcpttos = [] + self.require_SMTPUTF8 = False + self.num_bytes = 0 self.set_terminator(b'\r\n') - self.extended_smtp = False + if not skip_received_data: + self.received_data = '' + self.received_lines = [] + if not skip_greeting: + self.seen_greeting = '' + self.extended_smtp = False + self.command_size_limits.clear() + # properties for backwards-compatibility @property @@ -287,9 +313,10 @@ "set 'addr' instead", DeprecationWarning, 2) self.addr = value - # Overrides base class for convenience + # Overrides base class for convenience. def push(self, msg): - asynchat.async_chat.push(self, bytes(msg + '\r\n', 'ascii')) + asynchat.async_chat.push(self, bytes( + msg + '\r\n', 'utf-8' if self.enable_SMTPUTF8 else 'ascii')) # Implementation of base class abstract method def collect_incoming_data(self, data): @@ -317,9 +344,9 @@ if not line: self.push('500 Error: bad syntax') return - method = None if not self._decode_data: line = str(line, 'utf-8') + method = None i = line.find(' ') if i < 0: command = line.upper() @@ -327,8 +354,7 @@ else: command = line[:i].upper() arg = line[i+1:].strip() - max_sz = (self.command_size_limits[command] - if self.extended_smtp else self.command_size_limit) + max_sz = self.command_size_limits[command] if sz > max_sz: self.push('500 Error: line too long') return @@ -356,15 +382,18 @@ else: data.append(text) self.received_data = self._newline.join(data) - status = self.smtp_server.process_message(self.peer, - self.mailfrom, - self.rcpttos, - self.received_data) - self.rcpttos = [] - self.mailfrom = None - self.smtp_state = self.COMMAND - self.num_bytes = 0 - self.set_terminator(b'\r\n') + status = ( + self.smtp_server.process_unicode_message + if self.require_SMTPUTF8 + else self.smtp_server.process_message + )( + self.peer, + self.mailfrom, + self.rcpttos, + self.received_data + ) + self._set_initial_state( + skip_greeting=True, skip_received_data=True) if not status: self.push('250 OK') else: @@ -375,26 +404,37 @@ if not arg: self.push('501 Syntax: HELO hostname') return + # See issue #21783 for a discussion of this behavior. if self.seen_greeting: self.push('503 Duplicate HELO/EHLO') - else: - self.seen_greeting = arg - self.extended_smtp = False - self.push('250 %s' % self.fqdn) + return + + self._set_initial_state() + self.seen_greeting = arg + self.push('250 %s' % self.fqdn) def smtp_EHLO(self, arg): if not arg: self.push('501 Syntax: EHLO hostname') return + # See issue #21783 for a discussion of this behavior. if self.seen_greeting: self.push('503 Duplicate HELO/EHLO') - else: - self.seen_greeting = arg - self.extended_smtp = True - self.push('250-%s' % self.fqdn) - if self.data_size_limit: - self.push('250-SIZE %s' % self.data_size_limit) - self.push('250 HELP') + return + + self._set_initial_state() + self.seen_greeting = arg + self.extended_smtp = True + self.push('250-%s' % self.fqdn) + if self.data_size_limit: + self.push('250-SIZE %s' % self.data_size_limit) + self.command_size_limits['MAIL'] += 26 + if self.enable_SMTPUTF8: + self.push('250-8BITMIME') + self.push('250-SMTPUTF8') + self.command_size_limits['MAIL'] += 10 + + self.push('250 HELP') def smtp_NOOP(self, arg): if arg: @@ -427,8 +467,8 @@ def _getparams(self, params): # Return any parameters that appear to be syntactically valid according # to RFC 1869, ignore all others. (Postel rule: accept what we can.) - params = [param.split('=', 1) for param in params.split() - if '=' in param] + params = [param.split('=', 1) if '=' in param else (param, True) for + param in params.split()] return {k: v for k, v in params if k.isalnum()} def smtp_HELP(self, arg): @@ -506,6 +546,22 @@ if params is None: self.push(syntaxerr) return + # XXX: I assume that the 8BITMIME parameter can be ignored since we are + # using 8-bit clean streams anyway. (The variable is used to validate + # SMTPUTF8 later.) + body = params.pop('BODY', '7BIT') + if params.pop('SMTPUTF8', False): + if not self.enable_SMTPUTF8: + self.push( + '555 MAIL FROM parameter SMTPUTF8 is not enabled.' + ) + return + elif body != '8BITMIME': + self.push( + '501 Syntax: MAIL FROM:
BODY=8BITMIME SMTPUTF8') + return + else: + self.require_SMTPUTF8 = True size = params.pop('SIZE', None) if size: if not size.isdigit(): @@ -567,10 +623,7 @@ self.push('501 Syntax: RSET') return # Resets the sender, recipients, and data, but not the greeting - self.mailfrom = None - self.rcpttos = [] - self.received_data = '' - self.smtp_state = self.COMMAND + self._set_initial_state(skip_greeting=True) self.push('250 OK') def smtp_DATA(self, arg): @@ -598,10 +651,17 @@ def __init__(self, localaddr, remoteaddr, data_size_limit=DATA_SIZE_DEFAULT, map=None, - decode_data=None): + enable_SMTPUTF8=False, decode_data=None): self._localaddr = localaddr self._remoteaddr = remoteaddr self.data_size_limit = data_size_limit + self.enable_SMTPUTF8 = enable_SMTPUTF8 + if enable_SMTPUTF8: + if decode_data: + raise ValueError("The decode_data and enable_SMTPUTF8" + " parameters cannot be set to True at the" + " same time.") + decode_data = False if decode_data is None: warn("The decode_data default of True will change to False in 3.6;" " specify an explicit value for this keyword", @@ -627,8 +687,11 @@ def handle_accepted(self, conn, addr): print('Incoming connection from %s' % repr(addr), file=DEBUGSTREAM) - channel = self.channel_class(self, conn, addr, self.data_size_limit, - self._map, self._decode_data) + channel = self.channel_class( + self, conn, addr, self.data_size_limit, + self._map, + self.enable_SMTPUTF8, + self._decode_data) # API for "doing something useful with the message" def process_message(self, peer, mailfrom, rcpttos, data): @@ -655,6 +718,18 @@ """ raise NotImplementedError + # API for processing messeges needing Unicode support (RFC 6531, RFC 6532). + def process_unicode_message(self, peer, mailfrom, rcpttos, data): + """Same as ``process_message`` but for messages which have sent the + SMTPUTF8 parameter with the MAIL command to a SMTPUTF8 aware server + (see the enable_SMTPUTF8 init parameter). + + This function should return None, for a normal `250 Ok' response; + otherwise it returns the desired response string in RFC 6532 format. + + """ + raise NotImplementedError + class DebuggingServer(SMTPServer): # Do something with the gathered message @@ -670,8 +745,17 @@ print(line) print('------------ END MESSAGE ------------') + def process_unicode_message(self, *args, **kwargs): + self.process_message(*args, **kwargs) + class PureProxy(SMTPServer): + def __init__(self, *args, **kwargs): + if enable_SMTPUTF8: + raise ValueError("enable_SMTPUTF8 cannot be True: SMTPUTF8 is not" + " supported by PureProxy yet (Issue #TODOXXX.") + super(PureProxy, self).__init__(*args, **kwargs) + def process_message(self, peer, mailfrom, rcpttos, data): lines = data.split('\n') # Look for the last header @@ -712,6 +796,12 @@ class MailmanProxy(PureProxy): + def __init__(self, *args, **kwargs): + if enable_SMTPUTF8: + raise ValueError("enable_SMTPUTF8 cannot be True: SMTPUTF8 is not" + " supported by Mailman yet (Issue #TODOXXX.") + super(PureProxy, self).__init__(*args, **kwargs) + def process_message(self, peer, mailfrom, rcpttos, data): from io import StringIO from Mailman import Utils @@ -790,17 +880,19 @@ class Options: - setuid = 1 + setuid = True classname = 'PureProxy' size_limit = None + enable_SMTPUTF8 = False def parseargs(): global DEBUGSTREAM try: opts, args = getopt.getopt( - sys.argv[1:], 'nVhc:s:d', - ['class=', 'nosetuid', 'version', 'help', 'size=', 'debug']) + sys.argv[1:], 'nVhc:s:du', + ['class=', 'nosetuid', 'version', 'help', 'size=', 'debug', + 'smtputf8']) except getopt.error as e: usage(1, e) @@ -812,11 +904,13 @@ print(__version__) sys.exit(0) elif opt in ('-n', '--nosetuid'): - options.setuid = 0 + options.setuid = False elif opt in ('-c', '--class'): options.classname = arg elif opt in ('-d', '--debug'): DEBUGSTREAM = sys.stderr + elif opt in ('-u', '--smtputf8'): + options.enable_SMTPUTF8 = True elif opt in ('-s', '--size'): try: int_size = int(arg) @@ -871,7 +965,7 @@ class_ = getattr(mod, classname) proxy = class_((options.localhost, options.localport), (options.remotehost, options.remoteport), - options.size_limit) + options.size_limit, enable_SMTPUTF8=options.enable_SMTPUTF8) if options.setuid: try: import pwd diff -r a82d7e028458 Lib/test/test_smtpd.py --- a/Lib/test/test_smtpd.py Mon Jun 16 19:26:56 2014 -0400 +++ b/Lib/test/test_smtpd.py Tue Jun 17 02:29:49 2014 +0200 @@ -7,20 +7,19 @@ class DummyServer(smtpd.SMTPServer): - def __init__(self, localaddr, remoteaddr, decode_data=True): - smtpd.SMTPServer.__init__(self, localaddr, remoteaddr, - decode_data=decode_data) + def __init__(self, *args, **kwargs): + smtpd.SMTPServer.__init__(self, *args, **kwargs) self.messages = [] - if decode_data: - self.return_status = 'return status' - else: - self.return_status = b'return status' + self.return_status = 'return status' def process_message(self, peer, mailfrom, rcpttos, data): self.messages.append((peer, mailfrom, rcpttos, data)) if data == self.return_status: return '250 Okish' + def process_unicode_message(self, *args, **kwargs): + return '250 Unicode message okish' + class DummyDispatcherBroken(Exception): pass @@ -228,24 +227,31 @@ def test_command_too_long(self): self.write_line(b'HELO example') self.write_line(b'MAIL from: ' + - b'a' * self.channel.command_size_limit + + b'a' * self.channel.command_size_limits['MAIL'] + b'@example') self.assertEqual(self.channel.socket.last, b'500 Error: line too long\r\n') def test_MAIL_command_limit_extended_with_SIZE(self): self.write_line(b'EHLO example') - fill_len = self.channel.command_size_limit - len('MAIL from:<@example>') + fill_len = (512 + 26) - len('MAIL from:<@example> SIZE=1234') + self.write_line(b'MAIL from:<' + + b'a' * (fill_len + 1) + + b'@example> SIZE=1234') + self.assertEqual(self.channel.socket.last, + b'500 Error: line too long\r\n') self.write_line(b'MAIL from:<' + b'a' * fill_len + b'@example> SIZE=1234') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') - self.write_line(b'MAIL from:<' + - b'a' * (fill_len + 26) + - b'@example> SIZE=1234') - self.assertEqual(self.channel.socket.last, - b'500 Error: line too long\r\n') + def test_MAIL_command_rejects_SMTPUTF8_by_default(self): + self.write_line(b'EHLO example') + self.write_line( + b'MAIL from: BODY=8BITMIME SMTPUTF8') + self.assertEqual( + self.channel.socket.last, + b'555 MAIL FROM parameter SMTPUTF8 is not enabled.\r\n') def test_data_longer_than_default_data_size_limit(self): # Hack the default so we don't have to generate so much data. @@ -692,5 +698,92 @@ 'utf8 enriched text: żźć\nand some plain ascii') +class SMTPDChannelTestWithEnableSMTPUTF8True(unittest.TestCase): + def setUp(self): + smtpd.socket = asyncore.socket = mock_socket + self.old_debugstream = smtpd.DEBUGSTREAM + self.debug = smtpd.DEBUGSTREAM = io.StringIO() + self.server = DummyServer((support.HOST, 0), ('b', 0), + enable_SMTPUTF8=True) + conn, addr = self.server.accept() + self.channel = smtpd.SMTPChannel(self.server, conn, addr, + enable_SMTPUTF8=True) + + def tearDown(self): + asyncore.close_all() + asyncore.socket = smtpd.socket = socket + smtpd.DEBUGSTREAM = self.old_debugstream + + def write_line(self, line): + self.channel.socket.queue_recv(line) + self.channel.handle_read() + + def test_MAIL_command_accepts_SMTPUTF8_when_announced(self): + self.write_line(b'EHLO example') + self.write_line( + 'MAIL from: BODY=8BITMIME SMTPUTF8'.encode( + 'utf-8') + ) + self.assertEqual(self.channel.socket.last, b'250 OK\r\n') + + def test_process_unicode_message_is_called_when_needed(self): + self.write_line(b'EHLO example') + for mail_parameters in [b'', b'BODY=8BITMIME SMTPUTF8']: + self.write_line(b'MAIL from: ' + mail_parameters) + self.assertEqual(self.channel.socket.last[0:3], b'250') + self.write_line(b'rcpt to:') + self.assertEqual(self.channel.socket.last[0:3], b'250') + self.write_line(b'data') + self.assertEqual(self.channel.socket.last[0:3], b'354') + self.write_line(b'c\r\n.') + if mail_parameters == b'': + self.assertEqual(self.channel.socket.last, b'250 OK\r\n') + else: + self.assertEqual(self.channel.socket.last, + b'250 Unicode message okish\r\n') + + def test_utf8_data(self): + self.write_line(b'EHLO example') + self.write_line( + 'MAIL From: naïve@examplé BODY=8BITMIME SMTPUTF8'.encode('utf-8')) + self.assertEqual(self.channel.socket.last[0:3], b'250') + self.write_line('RCPT To:späm@examplé'.encode('utf-8')) + self.assertEqual(self.channel.socket.last[0:3], b'250') + self.write_line(b'DATA') + self.assertEqual(self.channel.socket.last[0:3], b'354') + self.write_line(b'utf8 enriched text: \xc5\xbc\xc5\xba\xc4\x87') + self.write_line(b'.') + self.assertEqual( + self.channel.received_data, + b'utf8 enriched text: \xc5\xbc\xc5\xba\xc4\x87') + + def test_MAIL_command_limit_extended_with_SIZE_and_SMTPUTF8(self): + self.write_line(b'ehlo example') + fill_len = (512 + 26 + 10) - len('mail from:<@example>') + self.write_line(b'MAIL from:<' + + b'a' * (fill_len + 1) + + b'@example>') + self.assertEqual(self.channel.socket.last, + b'500 Error: line too long\r\n') + self.write_line(b'MAIL from:<' + + b'a' * fill_len + + b'@example>') + self.assertEqual(self.channel.socket.last, b'250 OK\r\n') + + def test_multiple_emails_with_extended_command_length(self): + self.write_line(b'ehlo example') + fill_len = (512 + 26 + 10) - len('mail from:<@example>') + for char in [b'a', b'b', b'c']: + self.write_line(b'MAIL from:<' + char * fill_len + b'a@example>') + self.assertEqual(self.channel.socket.last[0:3], b'500') + self.write_line(b'MAIL from:<' + char * fill_len + b'@example>') + self.assertEqual(self.channel.socket.last[0:3], b'250') + self.write_line(b'rcpt to:') + self.assertEqual(self.channel.socket.last[0:3], b'250') + self.write_line(b'data') + self.assertEqual(self.channel.socket.last[0:3], b'354') + self.write_line(b'test\r\n.') + self.assertEqual(self.channel.socket.last[0:3], b'250') + if __name__ == "__main__": unittest.main()