def test_build_string_valueerror(self):
     class MyExtension(object):
         def __init__(self):
             pass
         def __str__(self):
             raise ValueError('test')
     ext = Extensions()
     ext.extensions = {'ONE': 'OK VALUE', 'TWO': MyExtension()}
     expected = """the header\r\nONE OK VALUE"""
     self.assertEqual(expected, ext.build_string('the header'))
    def test_build_string_valueerror(self):
        class MyExtension(object):
            def __init__(self):
                pass

            def __str__(self):
                raise ValueError("test")

        ext = Extensions()
        ext.extensions = {"ONE": "OK VALUE", "TWO": MyExtension()}
        expected = """the header\r\nONE OK VALUE"""
        self.assertEqual(expected, ext.build_string("the header"))
Esempio n. 3
0
class TestSmtpExtensions(unittest.TestCase):
    def setUp(self):
        self.ext = Extensions()
        self.ext.extensions = {'EMPTY': None, 'TEST': 'STUFF'}

    def test_contains(self):
        self.assertTrue('TEST' in self.ext)
        self.assertTrue('test' in self.ext)
        self.assertFalse('BAD' in self.ext)

    def test_reset(self):
        self.assertTrue('TEST' in self.ext)
        self.ext.reset()
        self.assertFalse('TEST' in self.ext)

    def test_add(self):
        self.ext.add('new')
        self.assertTrue('NEW' in self.ext)

    def test_drop(self):
        self.assertTrue(self.ext.drop('test'))
        self.assertFalse('TEST' in self.ext)
        self.assertFalse(self.ext.drop('BAD'))

    def test_getparam(self):
        self.assertEqual(None, self.ext.getparam('BAD'))
        self.assertEqual(None, self.ext.getparam('EMPTY'))
        self.assertEqual('STUFF', self.ext.getparam('TEST'))

    def test_getparam_filter(self):
        ret = self.ext.getparam('TEST', lambda x: x.strip('F'))
        self.assertEqual('STU', ret)
        ret = self.ext.getparam('EMPTY', lambda x: x)
        self.assertEqual(None, ret)

    def test_getparam_filter_valueerror(self):
        self.assertEqual(None, self.ext.getparam('TEST', int))

    def test_parse_string(self):
        ext = Extensions()
        header = ext.parse_string("""\
the header
EXT1
PARSETEST DATA""")
        self.assertEqual('the header', header)
        self.assertTrue('EXT1' in ext)
        self.assertTrue('PARSETEST' in ext)
        self.assertEqual(None, ext.getparam('EXT1'))
        self.assertEqual('DATA', ext.getparam('PARSETEST'))

    def test_build_string(self):
        possibilities = ("""\
the header
EMPTY
TEST STUFF""", """\
the header
TEST STUFF
EMPTY""")
        ret = self.ext.build_string('the header').replace('\r', '')
        self.assertTrue(ret in possibilities)

    def test_build_string_valueerror(self):
        class MyExtension(object):
            def __init__(self):
                pass

            def __str__(self):
                raise ValueError('test')

        ext = Extensions()
        ext.extensions = {'ONE': 'OK VALUE', 'TWO': MyExtension()}
        expected = """the header\r\nONE OK VALUE"""
        self.assertEqual(expected, ext.build_string('the header'))
class TestSmtpExtensions(unittest.TestCase):

    def setUp(self):
        self.ext = Extensions()
        self.ext.extensions = {'EMPTY': None, 'TEST': 'STUFF'}

    def test_contains(self):
        self.assertTrue('TEST' in self.ext)
        self.assertTrue('test' in self.ext)
        self.assertFalse('BAD' in self.ext)

    def test_reset(self):
        self.assertTrue('TEST' in self.ext)
        self.ext.reset()
        self.assertFalse('TEST' in self.ext)

    def test_add(self):
        self.ext.add('new')
        self.assertTrue('NEW' in self.ext)

    def test_drop(self):
        self.assertTrue(self.ext.drop('test'))
        self.assertFalse('TEST' in self.ext)
        self.assertFalse(self.ext.drop('BAD'))

    def test_getparam(self):
        self.assertEqual(None, self.ext.getparam('BAD'))
        self.assertEqual(None, self.ext.getparam('EMPTY'))
        self.assertEqual('STUFF', self.ext.getparam('TEST'))

    def test_getparam_filter(self):
        ret = self.ext.getparam('TEST', lambda x: x.strip('F'))
        self.assertEqual('STU', ret)
        ret = self.ext.getparam('EMPTY', lambda x: x)
        self.assertEqual(None, ret)

    def test_getparam_filter_valueerror(self):
        self.assertEqual(None, self.ext.getparam('TEST', int))

    def test_parse_string(self):
        ext = Extensions()
        header = ext.parse_string("""\
the header
EXT1
PARSETEST DATA""")
        self.assertEqual('the header', header)
        self.assertTrue('EXT1' in ext)
        self.assertTrue('PARSETEST' in ext)
        self.assertEqual(None, ext.getparam('EXT1'))
        self.assertEqual('DATA', ext.getparam('PARSETEST'))

    def test_build_string(self):
        possibilities = ("""\
the header
EMPTY
TEST STUFF""", """\
the header
TEST STUFF
EMPTY""")
        ret = self.ext.build_string('the header').replace('\r', '')
        self.assertTrue(ret in possibilities)

    def test_build_string_valueerror(self):
        class MyExtension(object):
            def __init__(self):
                pass
            def __str__(self):
                raise ValueError('test')
        ext = Extensions()
        ext.extensions = {'ONE': 'OK VALUE', 'TWO': MyExtension()}
        expected = """the header\r\nONE OK VALUE"""
        self.assertEqual(expected, ext.build_string('the header'))
class TestSmtpExtensions(unittest.TestCase):
    def setUp(self):
        self.ext = Extensions()
        self.ext.extensions = {"EMPTY": None, "TEST": "STUFF"}

    def test_contains(self):
        self.assertTrue("TEST" in self.ext)
        self.assertTrue("test" in self.ext)
        self.assertFalse("BAD" in self.ext)

    def test_reset(self):
        self.assertTrue("TEST" in self.ext)
        self.ext.reset()
        self.assertFalse("TEST" in self.ext)

    def test_add(self):
        self.ext.add("new")
        self.assertTrue("NEW" in self.ext)

    def test_drop(self):
        self.assertTrue(self.ext.drop("test"))
        self.assertFalse("TEST" in self.ext)
        self.assertFalse(self.ext.drop("BAD"))

    def test_getparam(self):
        self.assertEqual(None, self.ext.getparam("BAD"))
        self.assertEqual(None, self.ext.getparam("EMPTY"))
        self.assertEqual("STUFF", self.ext.getparam("TEST"))

    def test_getparam_filter(self):
        ret = self.ext.getparam("TEST", lambda x: x.strip("F"))
        self.assertEqual("STU", ret)
        ret = self.ext.getparam("EMPTY", lambda x: x)
        self.assertEqual(None, ret)

    def test_getparam_filter_valueerror(self):
        self.assertEqual(None, self.ext.getparam("TEST", int))

    def test_parse_string(self):
        ext = Extensions()
        header = ext.parse_string(
            """\
the header
EXT1
PARSETEST DATA"""
        )
        self.assertEqual("the header", header)
        self.assertTrue("EXT1" in ext)
        self.assertTrue("PARSETEST" in ext)
        self.assertEqual(None, ext.getparam("EXT1"))
        self.assertEqual("DATA", ext.getparam("PARSETEST"))

    def test_build_string(self):
        possibilities = (
            """\
the header
EMPTY
TEST STUFF""",
            """\
the header
TEST STUFF
EMPTY""",
        )
        ret = self.ext.build_string("the header").replace("\r", "")
        self.assertTrue(ret in possibilities)

    def test_build_string_valueerror(self):
        class MyExtension(object):
            def __init__(self):
                pass

            def __str__(self):
                raise ValueError("test")

        ext = Extensions()
        ext.extensions = {"ONE": "OK VALUE", "TWO": MyExtension()}
        expected = """the header\r\nONE OK VALUE"""
        self.assertEqual(expected, ext.build_string("the header"))
Esempio n. 6
0
class Server(object):
    """Class that implements an SMTP server given a connected socket. This
    object has an ``extensions`` attribute that is an |Extensions| object that
    contains the SMTP extensions the server supports.

    :param socket: Connected socket for the session.
    :type socket: :class:`gevent.socket.socket`
    :param handlers: Object with methods that will be called when
                     corresponding SMTP commands are received. These methods
                     can modify the |Reply| before the command response is sent.
    :param auth_class: Optional |Auth| sub-class to enable authentication.
    :param tls: Optional dictionary of TLS settings passed directly as
                keyword arguments to :class:`gevent.ssl.SSLSocket`.
    :param tls_immediately: If True, the socket will be encrypted
                            immediately.
    :param tls_wrapper: Optional function that takes a socket and the ``tls``
                        dictionary, creates a new encrypted socket, performs
                        the TLS handshake, and returns it. The default uses
                        :class:`~gevent.ssl.SSLSocket`.
    :type tls_immediately: True or False
    :param command_timeout: Optional timeout waiting for a command to be
                            sent from the client.
    :param data_timeout: Optional timeout waiting for data to be sent from
                         the client.

    """

    def __init__(self, socket, handlers, auth_class=None,
                       tls=None, tls_immediately=False, tls_wrapper=None,
                       command_timeout=None, data_timeout=None):
        self.handlers = handlers
        self.extensions = Extensions()

        self.have_mailfrom = None
        self.have_rcptto = None
        self.ehlo_as = None
        self.auth_result = None
        self.encrypted = False

        self.extensions.add('8BITMIME')
        self.extensions.add('PIPELINING')
        self.extensions.add('ENHANCEDSTATUSCODES')
        if tls and not tls_immediately:
            self.extensions.add('STARTTLS')
        if auth_class:
            self.extensions.add('AUTH', auth_class(self))

        self.io = IO(socket, tls_wrapper)

        if tls:
            self.tls = tls.copy()
            self.tls.setdefault('server_side', True)
        else:
            self.tls = None
        self.tls_immediately = tls_immediately

        self.command_timeout = command_timeout
        self.data_timeout = data_timeout or command_timeout

    def _recv_command(self):
        timeout = Timeout(self.command_timeout)
        timeout.start()
        try:
            return self.io.recv_command()
        finally:
            timeout.cancel()

    def _get_message_data(self):
        max_size = self.extensions.getparam('SIZE', filter=int)
        reader = DataReader(self.io, max_size)

        err = None
        timeout = Timeout(self.data_timeout)
        timeout.start()
        try:
            data = reader.recv()
        except ConnectionLost:
            raise
        except SmtpError as e:
            data = None
            err = e
        finally:
            timeout.cancel()

        reply = Reply('250', '2.6.0 Message Accepted for Delivery')
        self._call_custom_handler('HAVE_DATA', reply, data, err)

        self.io.send_reply(reply)
        self.io.flush_send()

        self.have_mailfrom = None
        self.have_rcptto = None

    def _encrypt_session(self):
        if not self.io.encrypt_socket(self.tls):
            return False
        self._call_custom_handler('TLSHANDSHAKE')
        self.encrypted = True
        return True

    def _handle_command(self, which, arg):
        method = '_command_'+which
        if hasattr(self, method):
            return getattr(self, method)(arg)
        else:
            return self._command_custom(which, arg)

    def _call_custom_handler(self, which, *args):
        if hasattr(self.handlers, which):
            return getattr(self.handlers, which)(*args)

    def handle(self):
        """Runs through the SMTP session, receiving commands, calling handlers,
        and sending responses.

        :raises: :class:`~slimta.smtp.ConnectionLost` or unhandled exceptions.

        """
        if self.tls and self.tls_immediately:
            if not self._encrypt_session():
                tls_failure.send(self.io, flush=True)
                return

        command, arg = 'BANNER_', None
        while True:
            try:
                if command:
                    self._handle_command(command, arg)
                else:
                    unknown_command.send(self.io)
            except StopIteration:
                break
            except ConnectionLost:
                raise
            except TimeoutHappened:
                timed_out.send(self.io)
                self.io.flush_send()
                break
            except Exception as e:
                unhandled_error.send(self.io)
                raise
            finally:
                self.io.flush_send()

            try:
                command, arg = self._recv_command()
            except TimeoutHappened:
                timed_out.send(self.io)
                self.io.flush_send()
                break

    def _command_BANNER_(self, arg):
        reply = Reply('220', 'ESMTP server')
        reply.enhanced_status_code = False
        self._call_custom_handler('BANNER_', reply)

        reply.send(self.io)

        if reply.code != '220':
            self._call_custom_handler('CLOSE')
            raise StopIteration()

    def _command_EHLO(self, ehlo_as):
        reply = Reply('250', 'Hello {0}'.format(ehlo_as))
        reply.enhanced_status_code = False
        self._call_custom_handler('EHLO', reply, ehlo_as)

        # Add extension list to message, if successful.
        if reply.code == '250':
            reply.message = self.extensions.build_string(reply.message)

            self.have_mailfrom = None
            self.have_rcptto = None
            self.ehlo_as = ehlo_as

        reply.send(self.io)

    def _command_HELO(self, ehlo_as):
        reply = Reply('250', 'Hello {0}'.format(ehlo_as))
        reply.enhanced_status_code = False
        self._call_custom_handler('HELO', reply, ehlo_as)

        if reply.code == '250':
            self.have_mailfrom = None
            self.have_rcptto = None
            self.ehlo_as = ehlo_as
            self.extensions.reset()

        reply.send(self.io)

    def _command_STARTTLS(self, arg):
        if 'STARTTLS' not in self.extensions:
            unknown_command.send(self.io)
            return

        if arg:
            bad_arguments.send(self.io)
            return

        if not self.ehlo_as:
            bad_sequence.send(self.io)
            return

        reply = Reply('220', '2.7.0 Go ahead')
        self._call_custom_handler('STARTTLS', reply, self.extensions)

        reply.send(self.io, flush=True)

        if reply.code == '220':
            if not self._encrypt_session():
                tls_failure.send(self.io)
                raise StopIteration()
            self.ehlo_as = None
            self.extensions.drop('STARTTLS')

    def _command_AUTH(self, arg):
        if 'AUTH' not in self.extensions:
            unknown_command.send(self.io)
            return
        if not self.ehlo_as or self.auth_result or self.have_mailfrom:
            bad_sequence.send(self.io)
            return
        auth = self.extensions.getparam('AUTH')

        reply = Reply('235', '2.7.0 Authentication successful')
        try:
            result = auth.server_attempt(self.io, arg)
        except ServerAuthError as e:
            reply.copy(e.reply)
            result = None
        reply.send(self.io)

        self._call_custom_handler('AUTH', reply, result)

        if reply.code == '235':
            self.auth_result = result

    def _command_MAIL(self, arg):
        match = from_pattern.match(arg)
        if not match:
            bad_arguments.send(self.io)
            return

        start = match.end(0)
        end = find_outside_quotes(arg, '>', start)
        if end == -1:
            bad_arguments.send(self.io)
            return
        address = arg[start:end]

        if not self.ehlo_as:
            bad_sequence.send(self.io)
            return

        if self.have_mailfrom:
            bad_sequence.send(self.io)
            return

        match = size_pattern.search(arg, end+1)
        if match:
            try:
                size = int(match.group(1))
            except ValueError:
                bad_arguments.send(self.io)
                return
            max_size = self.extensions.getparam('SIZE', filter=int)
            if max_size is not None:
                if size > max_size:
                    m = '5.3.4 Message size exceeds {0} limit'.format(max_size)
                    Reply('552', m).send(self.io)
                    return
            else:
                unknown_parameter.send(self.io)
                return

        reply = Reply('250', '2.1.0 Sender <{0}> Ok'.format(address))
        self._call_custom_handler('MAIL', reply, address)

        reply.send(self.io)

        self.have_mailfrom = self.have_mailfrom or (reply.code == '250')

    def _command_RCPT(self, arg):
        match = to_pattern.match(arg)
        if not match:
            bad_arguments.send(self.io)
            return

        start = match.end(0)
        end = find_outside_quotes(arg, '>', start)
        if end == -1:
            bad_arguments.send(self.io)
            return
        address = arg[start:end]

        if not self.have_mailfrom:
            bad_sequence.send(self.io)
            return

        reply = Reply('250', '2.1.5 Recipient <{0}> Ok'.format(address))
        self._call_custom_handler('RCPT', reply, address)

        reply.send(self.io)

        self.have_rcptto = self.have_rcptto or (reply.code == '250')

    def _command_DATA(self, arg):
        if arg:
            bad_arguments.send(self.io)
            return

        if not self.have_mailfrom or not self.have_rcptto:
            bad_sequence.send(self.io)
            return

        reply = Reply('354', 'Start mail input; end with <CRLF>.<CRLF>')
        self._call_custom_handler('DATA', reply)

        reply.send(self.io)
        self.io.flush_send()

        if reply.code == '354':
            self._get_message_data()

    def _command_RSET(self, arg):
        if arg:
            bad_arguments.send(self.io)
            return

        reply = Reply('250', 'Ok')
        self._call_custom_handler('RSET', reply)

        if reply.code == '250':
            self.have_mailfrom = None
            self.have_rcptto = None

        reply.send(self.io)

    def _command_NOOP(self, arg):
        reply = Reply('250', 'Ok')
        self._call_custom_handler('NOOP', reply)

        reply.send(self.io)

    def _command_QUIT(self, arg):
        if arg:
            bad_arguments.send(self.io)
            return

        reply = Reply('221', 'Bye')
        self._call_custom_handler('QUIT', reply)

        reply.send(self.io)

        if reply.code == '221':
            self._call_custom_handler('CLOSE')
            raise StopIteration()

    def _command_custom(self, command, arg):
        reply = Reply()
        reply.copy(unknown_command)
        self._call_custom_handler(command, reply, arg, self)

        reply.send(self.io)