Debian Codegraph @

ansible_collections/community/general/tests/integration/targets/mail/files/smtpserver.py

raw
1 #!/usr/bin/env python
2
3 # Copyright (c) 2018, Dag Wieers (@dagwieers) <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 import asyncore
10 import os.path
11 import ssl
12 import sys
13
14 # Handle TLS and non-TLS support
15 try:
16 import smtpd_tls
17
18 HAS_TLS = True
19 except ImportError:
20 import smtpd
21
22 HAS_TLS = False
23 print("Library smtpd-tls is missing or not supported, hence starttls is NOT supported.")
24
25 # Handle custom ports
26 port = "25:465"
27 if len(sys.argv) > 1:
28 port = sys.argv[1]
29 ports = port.split(":")
30 port1: int
31 port2: int | None
32 if len(ports) > 1:
33 port1, port2 = int(ports[0]), int(ports[1])
34 else:
35 port1, port2 = int(port), None
36
37 # Handle custom certificate
38 basename = os.path.splitext(sys.argv[0])[0]
39 certfile = basename + ".crt"
40 if len(sys.argv) > 2:
41 certfile = sys.argv[2]
42
43 # Handle custom key
44 keyfile = basename + ".key"
45 if len(sys.argv) > 3:
46 keyfile = sys.argv[3]
47
48 ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
49
50 if HAS_TLS and ssl_ctx is not None:
51 print(f"Using {certfile} and {keyfile}")
52 ssl_ctx.load_cert_chain(certfile=certfile, keyfile=keyfile)
53
54 print("Start SMTP server on port", port1)
55 smtp_server1 = smtpd_tls.DebuggingServer(("127.0.0.1", port1), None, ssl_ctx=ssl_ctx, starttls=True)
56 if port2:
57 print("Start TLS SMTP server on port", port2)
58 smtp_server2 = smtpd_tls.DebuggingServer(("127.0.0.1", port2), None, ssl_ctx=ssl_ctx, starttls=False)
59 else:
60 print("Start SMTP server on port", port1)
61 smtp_server1 = smtpd.DebuggingServer(("127.0.0.1", port1), None) # pylint: disable=used-before-assignment
62 if port2:
63 print(f"WARNING: TLS is NOT supported on this system, not listening on port {port2}.")
64
65 asyncore.loop()