summaryrefslogtreecommitdiff
path: root/src/leap/bitmask/mail/smtp/service.py
blob: 788b27918a808c297bd2086a30c83375a25fe484 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# -*- coding: utf-8 -*-
# service.py
# Copyright (C) 2013-2016 LEAP
#
# 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 <http://www.gnu.org/licenses/>.
"""
SMTP gateway helper function.
"""
import os

from twisted.internet import reactor
from twisted.internet.error import CannotListenError
from twisted.logger import Logger

from leap.common.events import emit_async, catalog
from leap.bitmask.mail.smtp.gateway import SMTPFactory

log = Logger()

SMTP_PORT = 2013


def run_service(outgoing_sessions, soledad_sessions, port=SMTP_PORT,
                factory=None):
    """
    Main entry point to run the service from the client.

    :param outgoing_sessions: a dict-like object, containing instances
                              of outgoing, indexed by userid.
    :param soledad_sessions: a dict-like object, containing instances
                             of a Store (soledad instances), indexed by userid.
    :param factory: a factory for the protocol that will listen in the given
                    port

    :returns: the port as returned by the reactor when starts listening, and
              the factory for the protocol.
    :rtype: tuple
    """
    if not factory:
        factory = SMTPFactory(outgoing_sessions, soledad_sessions)

    try:
        interface = "localhost"
        # don't bind just to localhost if we are running on docker since we
        # won't be able to access smtp from the host
        if os.environ.get("LEAP_DOCKERIZED"):
            interface = ''

        # TODO Use Endpoints instead --------------------------------
        tport = reactor.listenTCP(port, factory, interface=interface)
        emit_async(catalog.SMTP_SERVICE_STARTED, str(port))

        return tport, factory
    except CannotListenError:
        log.error('STMP Service failed to start: '
                  'cannot listen in port %s' % port)
        emit_async(catalog.SMTP_SERVICE_FAILED_TO_START, str(port))
    except Exception as exc:
        log.error('Unhandled error while launching smtp gateway service')
        log.error('%r' % exc)