# -*- coding: utf-8 -*-
"""POP3 - Post Office Protocol - Version 3
=============================================
.. module:: pcapkit.protocols.application.pop3.protocol
:mod:`pcapkit.protocols.application.pop3.protocol` holds
:class:`~pcapkit.protocols.application.pop3.protocol.POP3`, the extractor for the
Post Office Protocol - Version 3 (POP3) [:rfc:`1939`] at TCP port 110
(:rfc:`1939#section-3`), with its extension mechanism [:rfc:`2449`].
.. versionadded:: 1.10.0
"""
from typing import TYPE_CHECKING
from pcapkit.const.pop3.command import Command as Enum_Command
from pcapkit.const.pop3.response_code import ResponseCode as Enum_ResponseCode
from pcapkit.corekit.enum import EnumLookup
from pcapkit.corekit.module import ModuleDescriptor
from pcapkit.protocols.application.application import Application
from pcapkit.protocols.application.pop3.const import (POP3_CHALLENGE, POP3_COMMAND,
POP3_COMMAND_MAX, POP3_RESP_CODE, POP3_STATUS,
POP3_STATUS_MAX, POP3_UTF8_COMMANDS)
from pcapkit.protocols.application.pop3.data import POP3 as Data_POP3
from pcapkit.protocols.application.pop3.data import Challenge as Data_Challenge
from pcapkit.protocols.application.pop3.data import Command as Data_Command
from pcapkit.protocols.application.pop3.data import Response as Data_Response
from pcapkit.protocols.application.pop3.data import Tail as Data_Tail
from pcapkit.protocols.application.pop3.schema import POP3 as Schema_POP3
from pcapkit.utilities.compat import StrEnum, auto
from pcapkit.utilities.exceptions import ProtocolError, UnsupportedCall
from pcapkit.utilities.lines import block_end, join_lines, split_lines, unstuff
if TYPE_CHECKING:
from typing import Any, Iterable, NoReturn, Optional
from typing_extensions import Literal
from pcapkit.const.reg.apptype.tcp import TCP as AppType_TCP
__all__ = ['POP3']
#: The TCP port registry :meth:`POP3.__index__` reads its port from, resolved
#: there rather than imported, as ``import pcapkit`` leaves it unloaded
#: (:issue:`1538`), so its first import holds
#: :data:`~pcapkit.utilities.importlib.import_lock` (:issue:`2771`).
_TCP: 'ModuleDescriptor[AppType_TCP]' = ModuleDescriptor('pcapkit.const.reg.apptype.tcp', 'TCP')
[docs]
class Type(EnumLookup, StrEnum):
"""POP3 packet type.
Built on :class:`~pcapkit.corekit.enum.EnumLookup`, the lookup contract
shared by every non-registry enumeration (:issue:`877`).
"""
#: Command packet.
COMMAND = auto()
#: Response packet.
RESPONSE = auto()
#: Server challenge packet.
CHALLENGE = auto()
#: Packet ending a multi-line response.
TAIL = auto()
[docs]
class Status(EnumLookup, StrEnum):
"""POP3 status indicator (:rfc:`1939#section-3`), sent in upper case.
Built on :class:`~pcapkit.corekit.enum.EnumLookup`, the lookup contract
shared by every non-registry enumeration (:issue:`877`).
"""
#: Positive status indicator.
OK = '+OK'
#: Negative status indicator.
ERR = '-ERR'
[docs]
class POP3(Application[Data_POP3, Schema_POP3],
data=Data_POP3, schema=Schema_POP3):
"""This class implements Post Office Protocol - Version 3.
One segment carries no session state, so it reads as the first of these
that it is, whole:
* a response: a status line of a status indicator and its text
(:rfc:`1939#section-3`), alone, or followed by lines whose last, and only
the last, holds a single period, which ends a multi-line response;
* a server challenge of the ``AUTH`` command (:rfc:`5034#section-4`);
* a command, one line of a keyword and its parameters
(:rfc:`2449#section-3`);
* the rest of a multi-line response, lines whose last, and only the last,
holds a single period.
A multi-line response is read whole from one segment, or its end alone
from the segment ending it, so the segments between, and one holding a
status line and more lines but not that end, are refused: such a segment
may as well hold several pipelined responses (:rfc:`2449#section-6.6`).
Octets that are not whole lines, a status line of more than 512 octets and
a command line of more than 255 (:rfc:`2449#section-4`) are refused too,
so on a TCP port each such segment is kept as
:class:`~pcapkit.protocols.misc.raw.protocol.Raw`. A line of a response,
or a client's Base64 answer to a challenge, alone in a segment reads as a
command if it can, since only the session marks either.
Text is ASCII (:rfc:`1939#section-3`) or, after the ``UTF8`` and ``LANG``
commands, UTF-8 (:rfc:`6856#section-2`), so it is decoded as UTF-8 and
octets that are not are refused. A parameter is ASCII, but for those of
``USER``, ``PASS`` and ``APOP``, which may be UTF-8 too
(:rfc:`6856#section-2.2`). A response code a response's text opens with is
read into :attr:`Response.code
<pcapkit.protocols.application.pop3.data.Response.code>`
(:rfc:`2449#section-8`), and any other text is free text, as :rfc:`1939`
has it: the ``text`` grammar of :rfc:`2449#section-3` admits no SP, so it
would refuse that RFC's own examples. The greeting's timestamp
(:rfc:`1939#section-7`) stays in its text, since only the session marks a
greeting.
"""
##########################################################################
# Properties.
##########################################################################
@property
def name(self) -> 'Literal["Post Office Protocol - Version 3"]':
"""Name of current protocol."""
return 'Post Office Protocol - Version 3'
@property
def length(self) -> 'NoReturn':
"""Header length of current protocol.
Raises:
UnsupportedCall: This protocol doesn't support :attr:`length`.
"""
raise UnsupportedCall(f"'{self.__class__.__name__}' object has no attribute 'length'")
##########################################################################
# Methods.
##########################################################################
[docs]
def read(self, length: 'Optional[int]' = None, **kwargs: 'Any') -> 'Data_POP3': # pylint: disable=unused-argument
"""Read Post Office Protocol - Version 3 (POP3).
Args:
length: Length of packet data.
**kwargs: Arbitrary keyword arguments.
Returns:
Parsed packet data.
Raises:
ProtocolError: If the packet is no response, server challenge,
command or end of a multi-line response.
"""
if length is None:
length = len(self)
schema = self.__header__
lines = split_lines(schema.data)
if lines is None:
raise ProtocolError('POP3: invalid packet format: not whole lines')
pop3 = self._read_response(lines) # type: Optional[Data_POP3]
if pop3 is None:
pop3 = self._read_challenge(lines)
if pop3 is None:
pop3 = self._read_command(lines)
if pop3 is None:
pop3 = self._read_tail(lines)
if pop3 is None:
raise ProtocolError('POP3: invalid packet format: no response, challenge, command '
'or end of a multi-line response')
return pop3
[docs]
def make(self, *,
status: 'Optional[Status | str]' = None,
text: 'Optional[str | bytes | bytearray]' = None,
lines: 'Optional[Iterable[bytes | bytearray]]' = None,
challenge: 'Optional[str | bytes | bytearray]' = None,
cmmd: 'Optional[Enum_Command | str]' = None,
args: 'Optional[str | bytes | bytearray | Iterable[str | bytes | bytearray]]' = None,
raw_cmmd: 'Optional[bytes]' = None,
**kwargs: 'Any') -> 'Schema_POP3':
"""Make (construct) packet data.
A response takes ``status``, ``text`` and ``lines``, a server challenge
``challenge`` alone, a command ``cmmd``, ``args`` and ``raw_cmmd``, and
the end of a multi-line response ``lines`` alone. Each line is
terminated with CRLF, and the octets are checked to read back as made.
Args:
status: Status indicator, a :class:`str` (a
:class:`~pcapkit.protocols.application.pop3.protocol.Status`
member is one).
text: Text of the status line, written after a single SP, a
response code it opens with included; :obj:`None` writes
neither. A :obj:`str` is encoded as UTF-8; :class:`bytes` are
written verbatim.
lines: Lines of a multi-line response after its first, as sent,
byte-stuffed (see :func:`~pcapkit.utilities.lines.stuff`); the
line ending the response is written after them. With
``status``, :obj:`None` makes a single-line response.
challenge: Challenge in Base64, written after ``+`` and a single
SP; empty for an empty challenge.
cmmd: Command keyword, a :class:`str` (a
:class:`~pcapkit.const.pop3.command.Command` member is one).
args: Parameters, each written after a single SP, or one
parameter; a :obj:`str` is encoded as UTF-8, :class:`bytes`
are written verbatim.
raw_cmmd: Keyword as received, written in place of ``cmmd`` when
the two differ only in case (:rfc:`1939#section-3`).
**kwargs: Arbitrary keyword arguments.
Returns:
Constructed packet data.
Raises:
ProtocolError: If not exactly one of ``status``, ``challenge``,
``cmmd`` and ``lines`` alone is given, or with another's
keywords, or if the octets made would not read back as made.
"""
if status is not None and challenge is None and cmmd is None and args is None and raw_cmmd is None:
data = self._make_response(status, text, lines)
elif challenge is not None and status is None and text is None and lines is None \
and cmmd is None and args is None and raw_cmmd is None:
data = self._make_challenge(challenge)
elif cmmd is not None and status is None and text is None and lines is None and challenge is None:
data = self._make_command(cmmd, args, raw_cmmd)
elif lines is not None and status is None and text is None and challenge is None \
and cmmd is None and args is None and raw_cmmd is None:
data = self._make_tail(lines)
else:
raise ProtocolError('POP3: invalid packet type: give one of status, challenge, cmmd '
'and lines alone, with its own keywords alone')
return Schema_POP3(data=data)
##########################################################################
# Data models.
##########################################################################
[docs]
@classmethod
def __index__(cls) -> 'int': # type: ignore[override]
"""Numeral registry index of the protocol.
Returns:
Numeral registry index of the protocol in `IANA`_ service names and
port numbers: TCP port 110, the port of
:attr:`TCP.pop3 <pcapkit.const.reg.apptype.tcp.TCP.pop3>` as an
:class:`int`, which
:attr:`TCP.__proto__ <pcapkit.protocols.transport.tcp.protocol.TCP.__proto__>`
dispatches here (:ref:`registry-protocol-index`).
.. _IANA: https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
"""
return int(_TCP.klass.pop3) # type: ignore[call-overload]
##########################################################################
# Utilities.
##########################################################################
[docs]
@classmethod
def _make_data(cls, data: 'Data_POP3') -> 'dict[str, Any]': # type: ignore[override]
"""Create key-value pairs from ``data`` for protocol construction.
Args:
data: protocol data
Returns:
Key-value pairs for protocol construction.
"""
kind = getattr(data, 'type', None)
if kind == Type.RESPONSE:
return {
'status': getattr(data, 'status', None),
'text': getattr(data, 'text', None),
'lines': getattr(data, 'lines', None),
}
if kind == Type.CHALLENGE:
return {
'challenge': getattr(data, 'challenge', None),
}
if kind == Type.COMMAND:
return {
'cmmd': getattr(data, 'cmmd', None),
'args': getattr(data, 'args', None),
'raw_cmmd': getattr(data, 'raw_cmmd', None),
}
return {
'lines': getattr(data, 'lines', None),
}
def _read_response(self, lines: 'tuple[bytes, ...]') -> 'Optional[Data_Response]':
"""Read ``lines`` as a single-line or a whole multi-line response.
Args:
lines: Lines of the segment, CRLF excluded.
Returns:
The response, or :obj:`None` if ``lines`` are no response.
"""
first = lines[0]
if len(first) + 2 > POP3_STATUS_MAX or (match := POP3_STATUS.match(first)) is None:
return None
if len(lines) == 1:
sent = None # type: Optional[tuple[bytes, ...]]
elif block_end(lines) == len(lines) - 1:
sent = lines[1:-1]
else:
return None
raw = match.group('text')
try:
text = None if raw is None else raw.decode('utf-8') # type: Optional[str]
except UnicodeDecodeError:
return None
code = None if text is None else POP3_RESP_CODE.match(text)
return Data_Response(
type=Type.RESPONSE,
status=Status(match.group('status').decode('ascii')),
text=text,
code=None if code is None else Enum_ResponseCode(code.group('code')),
lines=sent,
body=None if sent is None else tuple(unstuff(line) for line in sent),
)
def _make_response(self, status: 'Status | str', text: 'Optional[str | bytes | bytearray]',
lines: 'Optional[Iterable[bytes | bytearray]]') -> 'bytes':
"""Make a response.
Args:
status: Status indicator.
text: Text of the status line, :obj:`None` for none.
lines: Lines after the first, :obj:`None` for a single-line response.
Returns:
The response lines, each with its CRLF.
Raises:
ProtocolError: If ``status`` is no status indicator, or the lines
would not read back as made.
"""
if not isinstance(status, str) or status not in Status._value2member_map_: # pylint: disable=protected-access
raise ProtocolError(f'POP3: invalid status indicator: {status!r}')
first = str(Status(status).value).encode('ascii')
if text is not None:
first += b' ' + self._make_text(text)
made = (first,) if lines is None else (first, *self._make_body(lines), b'.')
if self._read_response(made) is None:
raise ProtocolError(f'POP3: invalid response: {made!r}')
return join_lines(made)
def _read_challenge(self, lines: 'tuple[bytes, ...]') -> 'Optional[Data_Challenge]':
"""Read ``lines`` as a server challenge.
Args:
lines: Lines of the segment, CRLF excluded.
Returns:
The challenge, or :obj:`None` if ``lines`` are no challenge.
"""
if len(lines) != 1 or (match := POP3_CHALLENGE.match(lines[0])) is None:
return None
return Data_Challenge(
type=Type.CHALLENGE,
challenge=match.group('challenge').decode('ascii'),
)
def _make_challenge(self, challenge: 'str | bytes | bytearray') -> 'bytes':
"""Make a server challenge.
Args:
challenge: Challenge in Base64.
Returns:
The challenge line, CRLF included.
Raises:
ProtocolError: If the line would not read back as made.
"""
made = (b'+ ' + self._make_text(challenge),)
if self._read_challenge(made) is None:
raise ProtocolError(f'POP3: invalid challenge: {made[0]!r}')
return join_lines(made)
def _read_command(self, lines: 'tuple[bytes, ...]') -> 'Optional[Data_Command]':
"""Read ``lines`` as a command, one line of a keyword and its parameters.
Args:
lines: Lines of the segment, CRLF excluded.
Returns:
The command, or :obj:`None` if ``lines`` are no command.
"""
if len(lines) != 1 or len(lines[0]) + 2 > POP3_COMMAND_MAX \
or (match := POP3_COMMAND.match(lines[0])) is None:
return None
raw_cmmd = match.group('cmmd')
cmmd = Enum_Command(raw_cmmd.decode('ascii'))
encoding = 'utf-8' if cmmd in POP3_UTF8_COMMANDS else 'ascii'
try:
args = tuple(arg.decode(encoding) for arg in match.group('args').split(b' ')[1:])
except UnicodeDecodeError:
return None
return Data_Command(
type=Type.COMMAND,
cmmd=cmmd,
args=args,
raw_cmmd=raw_cmmd,
)
def _make_command(self, cmmd: 'Enum_Command | str',
args: 'Optional[str | bytes | bytearray | Iterable[str | bytes | bytearray]]',
raw_cmmd: 'Optional[bytes]') -> 'bytes':
"""Make a command line.
Args:
cmmd: Command keyword.
args: Parameters, or one parameter; :obj:`None` for none.
raw_cmmd: Keyword as received.
Returns:
The command line, CRLF included.
Raises:
ProtocolError: If ``cmmd`` is not a :class:`str`, if ``args`` is
neither a parameter nor an iterable of them, or if the line
would not read back as made, including as a response.
"""
if not isinstance(cmmd, str):
raise ProtocolError(f'POP3: invalid command: must be a str, not {cmmd!r}')
keyword = cmmd.encode('utf-8', 'replace')
if isinstance(raw_cmmd, bytes) and raw_cmmd.upper() == keyword.upper():
keyword = raw_cmmd
if args is None:
items = () # type: tuple[str | bytes | bytearray, ...]
elif isinstance(args, (str, bytes, bytearray)):
items = (args,)
else:
try:
items = tuple(args)
except TypeError as error:
raise ProtocolError(f'POP3: invalid parameters: must be a str, bytes, bytearray '
f'or an iterable of them, not {args!r}') from error
params = tuple(self._make_text(item) for item in items)
made = (keyword + b''.join(b' ' + param for param in params),)
info = self._read_command(made)
if info is None or info.raw_cmmd != keyword or self._read_response(made) is not None \
or tuple(arg.encode('utf-8') for arg in info.args) != params:
raise ProtocolError(f'POP3: invalid command line: {made[0]!r}')
return join_lines(made)
def _read_tail(self, lines: 'tuple[bytes, ...]') -> 'Optional[Data_Tail]':
"""Read ``lines`` as the rest of a multi-line response.
Args:
lines: Lines of the segment, CRLF excluded.
Returns:
The lines, or :obj:`None` unless the last line, and only the last,
holds a single period.
"""
if block_end(lines) != len(lines) - 1:
return None
sent = lines[:-1]
return Data_Tail(
type=Type.TAIL,
lines=sent,
body=tuple(unstuff(line) for line in sent),
)
def _make_tail(self, lines: 'Iterable[bytes | bytearray]') -> 'bytes':
"""Make the rest of a multi-line response and the line ending it.
Args:
lines: Lines as sent.
Returns:
The lines and the line ending them, each with its CRLF.
Raises:
ProtocolError: If the lines would read back as a response.
"""
made = (*self._make_body(lines), b'.')
if self._read_response(made) is not None:
raise ProtocolError(f'POP3: invalid lines: {made!r} read as a response')
return join_lines(made)
@staticmethod
def _make_text(text: 'str | bytes | bytearray') -> 'bytes':
"""Encode a line's text; :class:`bytes` and a :class:`bytearray` are written verbatim.
Args:
text: Text to encode.
Returns:
The octets of the text, a :obj:`str` encoded as UTF-8.
Raises:
ProtocolError: If ``text`` is of another type, or a :obj:`str`
UTF-8 cannot encode.
"""
if isinstance(text, (bytes, bytearray)):
return bytes(text)
if not isinstance(text, str):
raise ProtocolError(f'POP3: invalid text: must be a str, bytes or bytearray, not {text!r}')
try:
return text.encode('utf-8')
except UnicodeError as error:
raise ProtocolError(f'POP3: cannot encode {text!r} as UTF-8') from error
@staticmethod
def _make_body(lines: 'Iterable[bytes | bytearray]') -> 'tuple[bytes, ...]':
"""Check the lines of a multi-line response after its first.
Args:
lines: Lines as sent.
Returns:
The lines, as :class:`bytes`.
Raises:
ProtocolError: If ``lines`` is not an iterable of :class:`bytes`
and :class:`bytearray`, or a line holds a CRLF or a single
period, which would end the response early.
"""
try:
sent = tuple(bytes(line) if isinstance(line, (bytes, bytearray)) else line for line in lines)
except TypeError as error:
raise ProtocolError(f'POP3: invalid lines: must be an iterable of bytes, not {lines!r}') from error
if not all(isinstance(line, bytes) and b'\r\n' not in line for line in sent) \
or block_end(sent) is not None:
raise ProtocolError(f'POP3: invalid lines: {sent!r}')
return sent