|
| 1 | +# SPDX-PackageName: gel-python |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# SPDX-FileCopyrightText: Copyright Gel Data Inc. and the contributors. |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | +from typing import cast, Optional, TYPE_CHECKING |
| 7 | + |
| 8 | +import asyncio |
| 9 | +import email.message |
| 10 | +import email.parser |
| 11 | +import email.policy |
| 12 | +import signal |
| 13 | + |
| 14 | +import gel |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + import rich_toolkit |
| 18 | + |
| 19 | + |
| 20 | +class SMTPServerProtocol(asyncio.Protocol): |
| 21 | + _transport: asyncio.Transport |
| 22 | + _mail_from: Optional[str] |
| 23 | + _rcpt_to: list[str] |
| 24 | + _parser: email.parser.BytesFeedParser |
| 25 | + _in_data: bool = False |
| 26 | + |
| 27 | + def __init__(self, cli: rich_toolkit.RichToolkit): |
| 28 | + self._cli = cli |
| 29 | + self._buffer = bytearray() |
| 30 | + self._reset() |
| 31 | + |
| 32 | + def connection_made(self, transport: asyncio.BaseTransport) -> None: |
| 33 | + trans = cast("asyncio.Transport", transport) |
| 34 | + self._transport = trans |
| 35 | + trans.write(b"220 localhost Simple SMTP server\r\n") |
| 36 | + |
| 37 | + def connection_lost(self, exc: Optional[Exception]) -> None: |
| 38 | + del self._transport |
| 39 | + |
| 40 | + def data_received(self, data: bytes) -> None: |
| 41 | + self._buffer.extend(data) |
| 42 | + |
| 43 | + while True: |
| 44 | + newline_index = self._buffer.find(b"\r\n") |
| 45 | + if newline_index == -1: |
| 46 | + break |
| 47 | + |
| 48 | + line = self._buffer[:newline_index] |
| 49 | + self._buffer = self._buffer[newline_index + 2 :] |
| 50 | + |
| 51 | + self._handle_line(bytes(line)) |
| 52 | + |
| 53 | + def _handle_line(self, line: bytes) -> None: |
| 54 | + if self._in_data: |
| 55 | + if line == b".": # End of DATA mode |
| 56 | + message = self._parser.close() |
| 57 | + assert isinstance(message, email.message.EmailMessage) |
| 58 | + self._handle_message(message) |
| 59 | + self._reset() |
| 60 | + self._transport.write(b"250 OK\r\n") |
| 61 | + else: |
| 62 | + self._parser.feed(line + b"\r\n") |
| 63 | + return |
| 64 | + |
| 65 | + # Handle SMTP commands |
| 66 | + upper = line.upper() |
| 67 | + if upper.startswith((b"HELO", b"EHLO")): |
| 68 | + self._transport.write(b"250 Hello\r\n") |
| 69 | + elif upper.startswith(b"MAIL FROM:"): |
| 70 | + self._mail_from = line[10:].strip().decode() |
| 71 | + self._transport.write(b"250 OK\r\n") |
| 72 | + elif upper.startswith(b"RCPT TO:"): |
| 73 | + self._rcpt_to.append(line[8:].strip().decode()) |
| 74 | + self._transport.write(b"250 OK\r\n") |
| 75 | + elif upper == b"DATA": |
| 76 | + self._transport.write(b"354 End data with <CR><LF>.<CR><LF>\r\n") |
| 77 | + self._in_data = True |
| 78 | + elif upper == b"QUIT": |
| 79 | + self._transport.write(b"221 Bye\r\n") |
| 80 | + self._transport.close() |
| 81 | + else: |
| 82 | + self._transport.write(b"500 Unrecognized command\r\n") |
| 83 | + |
| 84 | + def _handle_message(self, message: email.message.EmailMessage) -> None: |
| 85 | + self._cli.print("Received email:", tag="gel") |
| 86 | + self._cli.print(f" From: {self._mail_from}", tag="gel") |
| 87 | + self._cli.print(f" To: {', '.join(self._rcpt_to)}", tag="gel") |
| 88 | + self._cli.print(f" Subject: {message.get('Subject')}", tag="gel") |
| 89 | + has_gel_header = False |
| 90 | + for key in message: |
| 91 | + if key.lower().startswith("x-gel-"): |
| 92 | + self._cli.print(f" {key}: {message[key]}", tag="gel") |
| 93 | + has_gel_header = True |
| 94 | + if not has_gel_header: |
| 95 | + text_parts = [] |
| 96 | + if message.is_multipart(): |
| 97 | + for part in message.walk(): |
| 98 | + content_type = part.get_content_type() |
| 99 | + content_disposition = part.get("Content-Disposition", "") |
| 100 | + if ( |
| 101 | + content_type == "text/plain" |
| 102 | + and "attachment" not in content_disposition |
| 103 | + ): |
| 104 | + charset = part.get_content_charset() or "utf-8" |
| 105 | + payload = part.get_payload(decode=True) |
| 106 | + if isinstance(payload, bytes): |
| 107 | + text = payload.decode(charset, errors="replace") |
| 108 | + text_parts.append(text) |
| 109 | + else: |
| 110 | + if message.get_content_type() == "text/plain": |
| 111 | + charset = message.get_content_charset() or "utf-8" |
| 112 | + payload = message.get_payload(decode=True) |
| 113 | + if isinstance(payload, bytes): |
| 114 | + text_parts.append( |
| 115 | + payload.decode(charset, errors="replace") |
| 116 | + ) |
| 117 | + self._cli.print( |
| 118 | + "No X-Gel-* headers found, email content:", tag="gel" |
| 119 | + ) |
| 120 | + if text_parts: |
| 121 | + for text in text_parts: |
| 122 | + self._cli.print(text, tag="gel") |
| 123 | + else: |
| 124 | + self._cli.print( |
| 125 | + repr(message.get_payload(decode=True)), tag="gel" |
| 126 | + ) |
| 127 | + |
| 128 | + def _reset(self) -> None: |
| 129 | + self._mail_from = None |
| 130 | + self._rcpt_to = [] |
| 131 | + self._parser = email.parser.BytesFeedParser(policy=email.policy.SMTP) |
| 132 | + self._in_data = False |
| 133 | + self._buffer.clear() |
| 134 | + |
| 135 | + |
| 136 | +class SMTPServer: |
| 137 | + _server: asyncio.Server |
| 138 | + |
| 139 | + async def maybe_start( |
| 140 | + self, |
| 141 | + client: gel.AsyncIOClient, |
| 142 | + ) -> None: |
| 143 | + from fastapi_cli.utils.cli import get_rich_toolkit # noqa: PLC0415 |
| 144 | + |
| 145 | + # get_rich_toolkit() installs a SIGTERM handler underneath, which |
| 146 | + # causes unnecessary noise in the logs at CTRL + C shutdown. |
| 147 | + orig_handler = signal.getsignal(signal.SIGTERM) |
| 148 | + try: |
| 149 | + toolkit = get_rich_toolkit() |
| 150 | + finally: |
| 151 | + signal.signal(signal.SIGTERM, orig_handler) |
| 152 | + |
| 153 | + try: |
| 154 | + config = await client.query_single(""" |
| 155 | + select cfg::SMTPProviderConfig { |
| 156 | + host, |
| 157 | + port, |
| 158 | + security |
| 159 | + } filter .name = |
| 160 | + assert_single(cfg::Config).current_email_provider_name; |
| 161 | + """) |
| 162 | + except gel.QueryError as ex: |
| 163 | + toolkit.print( |
| 164 | + f"Skipping SMTP server startup due to " |
| 165 | + f"error reading configuration: {ex}", |
| 166 | + tag="gel", |
| 167 | + ) |
| 168 | + return None |
| 169 | + |
| 170 | + if config is None: |
| 171 | + toolkit.print( |
| 172 | + "No SMTP configuration found, skipping SMTP server startup", |
| 173 | + tag="gel", |
| 174 | + ) |
| 175 | + return None |
| 176 | + if config.security not in {"PlainText", "STARTTLSOrPlainText"}: |
| 177 | + toolkit.print( |
| 178 | + "SMTP server only supports security=PlainText or " |
| 179 | + "STARTTLSOrPlainText, skipping SMTP server startup", |
| 180 | + tag="gel", |
| 181 | + ) |
| 182 | + return None |
| 183 | + |
| 184 | + try: |
| 185 | + self._server = await asyncio.get_running_loop().create_server( |
| 186 | + lambda: SMTPServerProtocol(toolkit), |
| 187 | + host=config.host, |
| 188 | + port=config.port, |
| 189 | + ) |
| 190 | + except Exception as ex: |
| 191 | + toolkit.print( |
| 192 | + f"Skipping SMTP server startup due to error: {ex}", |
| 193 | + tag="gel", |
| 194 | + ) |
| 195 | + else: |
| 196 | + toolkit.print( |
| 197 | + f"Started SMTP server on {config.host}:{config.port} " |
| 198 | + f"for testing purposes.", |
| 199 | + tag="gel", |
| 200 | + ) |
| 201 | + |
| 202 | + async def stop(self) -> None: |
| 203 | + if hasattr(self, "_server"): |
| 204 | + self._server.close() |
| 205 | + await self._server.wait_closed() |
0 commit comments