diff -r 38a325c84564 Doc/library/smtpd.rst --- a/Doc/library/smtpd.rst Wed Jun 11 17:09:43 2014 -0400 +++ b/Doc/library/smtpd.rst Thu Jun 12 00:35:08 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,10 @@ 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. This will set *decode_data* + to ``False`` regardless of the given value. 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 @@ -68,8 +73,9 @@ .. 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. DebuggingServer Objects @@ -109,7 +115,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 +126,10 @@ 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. This will set *decode_data* + to ``False`` regardless of the given value. 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 +141,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 38a325c84564 Lib/smtpd.py --- a/Lib/smtpd.py Wed Jun 11 17:09:43 2014 -0400 +++ b/Lib/smtpd.py Thu Jun 12 00:35:08 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,31 @@ 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: + # raised if command_size_limits has no values. 'MAIL' is just a + # random string here (wich would be added anyway). + return self.command_size_limits['MAIL'] 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", @@ -287,9 +302,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 +333,16 @@ if not line: self.push('500 Error: bad syntax') return - method = None if not self._decode_data: line = str(line, 'utf-8') + #XXX: Should we check this? (breaks bug compatibility) + try: + line.encode('utf-8' if self.enable_SMTPUTF8 else 'ascii') + except UnicodeEncodeError: + self.push( + '500 Error: unknown characters in input.') + return + method = None i = line.find(' ') if i < 0: command = line.upper() @@ -327,8 +350,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 @@ -391,9 +413,16 @@ else: self.seen_greeting = arg self.extended_smtp = True + self.command_size_limits.pop('MAIL') 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): @@ -427,8 +456,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 +535,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(): @@ -598,10 +643,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: + 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", @@ -627,8 +679,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): @@ -790,17 +845,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 +869,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 +930,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 38a325c84564 Lib/test/test_smtpd.py --- a/Lib/test/test_smtpd.py Wed Jun 11 17:09:43 2014 -0400 +++ b/Lib/test/test_smtpd.py Thu Jun 12 00:35:08 2014 +0200 @@ -228,24 +228,47 @@ 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 - len('MAIL from:<@example>') + 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') 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_unicode_output_raises_error_by_default(self): + self.write_line('EHLO éxämplé'.encode('utf-8')) + self.assertEqual( + self.channel.socket.last, + b'500 Error: unknown characters in input.\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_MAIL_command_accepts_SMTPUTF8_when_announced(self): + self.channel.enable_SMTPUTF8 = True + 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') + self.channel.enable_SMTPUTF8 = False def test_data_longer_than_default_data_size_limit(self): # Hack the default so we don't have to generate so much data.