mirror of
https://github.com/apple/swift-nio-imap
synced 2026-11-25 04:47:51 +00:00
Internal parser functions throw `ParseFailure` (24 bytes, returned in
registers), so a failed speculative match no longer calls
swift_allocError. Public API keeps untyped throws and the same error
types; the entry points convert back with `unwrapped`.
- Array-form `parseOneOf` takes `ParseAlternative`s, which avoid
reabstraction thunks; a typed-throws closure literal as a
`[SubParser]` element crashes SILGen (6.3, 6.4).
- `try? parseSpaces()` becomes an explicit `catch .mismatch`; no
behavior change, since `parseSpaces` only reports incomplete on empty
input. Its doc comment is corrected to match.
- CommandParser: framing runs outside the incomplete catch; it throws
only `ParserError`.
- Untyped public API called by the grammar (`MailboxPath.init`,
`ModifiedUTF7.decode`) is wrapped: `throw ParseFailure(error)`.
- SynchronizingLiteralParser keeps untyped throws.
Reviewer focus: `ParseFailure` (`init(_:)`, `unwrapped`), the
combinators' catch clauses (`.mismatch`, `.mismatch, .badCommand`),
the entry points in CommandParser and ResponseParser (`catch
.incomplete`, `unwrapped`), `ParseAlternative`.
Hand edits, whole files taken from this commit:
- ParserErrors.swift: `ParseFailure`; typed `decodeUTF8`; doc
comments.
- ParseInput+Combinators.swift: typed `SubParser`, `ParseAlternative`,
catch clauses, 2-/3-way `parseOneOf` on `composite`; otherwise the
same conversion as the grammar.
- ParseInput.swift: `composite` takes `SubParser`; doc comments;
otherwise the same conversion as the grammar.
- CommandParser.swift, ResponseParser.swift: entry points; otherwise
the same conversion as the grammar.
- ParseInputCombinatorTests.swift: `ParseFailure` tests,
`ParseAlternative` call sites; otherwise the same conversion.
- ParseInputHarness.swift: `parseErrorThrown`.
- ResponseText+Tests.swift: `parseErrorThrown` and `#expect(error is
ParserError)` instead of `#expect(throws: ParserError.self)`.
Hand edits inside the script: `HAND` (selectingKeyword doc comment,
the two untyped-API wrappers); `OWN_FRAME`: `parseSearchKey` builds
its 35 alternatives in a nested `alternatives()`, off the recursive
frame; `ParseAlternative` naming and layout (`NAMED_FILES`, `RENAME`,
`ONE_PER_LINE`); `BRACE_BELOW`; `EXPLAIN_DO`; the emitted comments.
The rest is the output of the script below. To reproduce, on the
parent commit (swift-format from Swift 6.4.4):
F=(Sources/NIOIMAPCore/Parser/Grammar/*.swift
Tests/NIOIMAPCoreTests/ParseFixture.swift
Tests/NIOIMAPCoreTests/Grammar/CommandType/{CommandType,TaggedCommand}+Tests.swift
Tests/NIOIMAPCoreTests/Parser/Grammar/GrammarParser+Primitives+Tests.swift
Tests/NIOIMAPCoreTests/Parser/ParseInputTests.swift)
python3 convert_typed_throws.py "${F[@]}" && swift format -i "${F[@]}"
then check out the hand-edit files from this commit.
convert_typed_throws.py:
#!/usr/bin/env python3
# Converts the parser's internals from untyped `throws` to `throws(ParseFailure)`.
#
# Usage: python3 convert_typed_throws.py FILE... (in place), then `swift format -i FILE...`
import re
import sys
TYPED = 'throws(ParseFailure)'
# Public error type -> the ParseFailure case that carries it.
CASES = {
'ParserError': 'mismatch',
'BadCommand': 'badCommand',
'NoForwardProgress': 'noForwardProgress',
'TooMuchRecursion': 'tooMuchRecursion',
'ExceededLiteralSizeLimitError': 'literalSizeExceeded',
'ExceededMaximumMessageAttributesError': 'messageAttributesExceeded',
'ExceededMaximumBodySizeError': 'bodySizeExceeded',
}
TYPES = '|'.join(CASES)
# `ParseAlternative` names: `pN` by default; named after the alternative's suffix in these files
# (`parseSearchKey_older` -> `older`), with these exceptions.
NAMED_FILES = ['+Body.swift', '+Commands.swift', '+Response.swift', '+Search.swift']
RENAME = {
'parseBodyEncoding_quotePrintable': 'quotedPrintable',
'parseBodyEncoding_nil': 'nilEncoding',
'parseSuffix_metadataLongEntries': 'longEntries',
'parseSuffix_metadataMaxSize': 'maxSize',
'parseSuffix_metadataTooMany': 'tooMany',
'parseSuffix_metadataNoPrivate': 'noPrivate',
'parseKnownResponseTextCode': 'known',
}
KEYWORDS = {'nil', 'extension'}
# Alternatives (by the first one) whose array is laid out one per line rather than left to swift-format.
ONE_PER_LINE = {'parseSortCriterion_displayFrom', 'parseSearchReturnData_min', 'parseSearchKey_older'}
# Productions whose alternatives are built in a nested function, off the recursive frame.
OWN_FRAME = {'parseSearchKey'}
# Declarations left to swift-format, which puts `{` on its own line; all others too long for one line
# put each parameter on its own line.
BRACE_BELOW = {'parseCompoundObjectID'}
# Functions in which an annotated `do` gets a comment saying why.
EXPLAIN_DO = {'parseTaggedCommand', 'parseTaggedExtensionComplex_helper'}
LINE_LENGTH = 120
# Hand-written changes: (file, old, new), each matching exactly once.
HAND = [
('GrammarParser.swift', '''\
/// - Throws: `IncompleteMessage` when every byte that has arrived is part of the keyword, since
/// more could still follow; ``ParserError`` when the first byte cannot start one.
''', '''\
/// - Throws: ``ParseFailure/incomplete`` when every byte that has arrived is part of the keyword,
/// since more could still follow; ``ParseFailure/mismatch(_:)`` when the first byte cannot start
/// one.
'''),
('GrammarParser.swift', '''\
/// - Important: `select` should throw ``ParserError`` for an unrecognised keyword — not
/// `IncompleteMessage`, which would make the caller wait for bytes that cannot help. Callers
/// that fall back to another production (`parseFetchAttribute`, say) catch exactly that.
''', '''\
/// Pass an annotated closure: `{ keyword, buffer throws(ParseFailure) in switch keyword { … } }`.
///
/// - Important: `select` should throw ``ParseFailure/mismatch(_:)`` for an unrecognised keyword —
/// not ``ParseFailure/incomplete``, which would make the caller wait for bytes that cannot help.
/// The type can't enforce this. Callers that fall back to another production
/// (`parseFetchAttribute`, say) catch exactly `.mismatch`.
'''),
# Untyped public API called from the grammar: classify its error.
('GrammarParser.swift', '''\
return try ModifiedUTF7.decode(value)
''', '''\
do {
return try ModifiedUTF7.decode(value)
} catch {
throw ParseFailure(error)
}
'''),
('GrammarParser+Mailbox.swift', '''\
return MailboxInfo(
attributes: flags,
path: try .init(name: mailbox, pathSeparator: character),
''', '''\
// `MailboxPath.init(name:pathSeparator:)` is untyped public API (throws `InvalidPathSeparatorError`).
let path: MailboxPath
do {
path = try MailboxPath(name: mailbox, pathSeparator: character)
} catch {
throw ParseFailure(error)
}
return MailboxInfo(
attributes: flags,
path: path,
'''),
]
def closing(src, k):
"""Index just past the bracket matching the one before `k`."""
depth = 1
while depth:
c = src[k]
if c == '"': # skip string literals, which may hold brackets
k += 1
while src[k] != '"':
k += 2 if src[k] == '\\' else 1
elif c in '([{':
depth += 1
elif c in ')]}':
depth -= 1
k += 1
return k
def code_lines(src, fn):
"""Applies `fn` to every line that is not a comment."""
return ''.join(l if l.lstrip().startswith('//') else fn(l) for l in src.splitlines(keepends=True))
def throw_sites(src):
# throw ParserError(hint: L) -> throw .mismatch(L); other labels (dynamicHint:, expectedDigits:) stay.
src = re.sub(r'throw ParserError\((hint:\s*)?', 'throw .mismatch(', src)
src = src.replace('throw IncompleteMessage()', 'throw .incomplete')
# throw X(…) -> throw .case(X(…)) for the payload-carrying cases.
out, i = [], 0
for m in re.finditer(rf'throw ({TYPES})\(', src):
end = closing(src, m.end())
out += [src[i:m.start()], f'throw .{CASES[m.group(1)]}(', src[m.start() + len('throw '):end], ')']
i = end
return ''.join(out) + src[i:]
def catch_clauses(src):
# `catch is A, is B` / `catch let e as A` -> `catch .a, .b` / `catch .a(let e)`; adjacent clauses that
# differ only in type merge: `} catch is A {\n X } catch is B {\n X }` -> `} catch .a, .b {\n X }`.
src = re.sub(rf'catch let (\w+) as ({TYPES})\b', lambda m: f'catch .{CASES[m.group(2)]}(let {m.group(1)})', src)
src = re.sub(rf'catch ((?:is (?:{TYPES})(?:,\s*)?)+)',
lambda m: 'catch ' + ', '.join('.' + CASES[t] for t in re.findall(rf'is ({TYPES})', m.group(1))),
src)
src = re.sub(r'catch (\.\w+(?:, \.\w+)*) \{(\n[^\n]*\n\s*)\} catch (\.\w+) \{\2\}', r'catch \1, \3 {\2}', src)
# Rethrowing what a clause bound re-wraps it: `catch .x(let e) { throw e }` -> `throw .x(e)`.
return re.sub(r'(catch \.(\w+)\(let (\w+)\) \{\s*throw )\3\b', r'\1.\2(\3)', src)
def closures(src):
# Two-parameter closure literals: `{ a, b -> T in` / `{ (a, b) in` gain the annotation.
src = re.sub(r'(\{\s*\(?\w+,\s*\w+\)?)(\s*->[^\n{]*?)?(\s+in\b)',
lambda m: f'{m.group(1)} {TYPED}{m.group(2) or ""}{m.group(3)}', src)
# Closures with typed parameters: `{ (buffer: [UInt8]) -> String in`.
src = re.sub(r'(\{\s*\((?:\w+: [^()]+)\))(\s*->[^\n{]*?\s+in\b)', rf'\1 {TYPED}\2', src)
# `{ try f(buffer: &$0, tracker: $1) }` -> `{ b, t throws(ParseFailure) in try f(buffer: &b, tracker: t) }`
return re.sub(r'\{(\s*)(try [^{}\n]*\$0[^{}\n]*?)(\s*)\}',
lambda m: f'{{ b, t {TYPED} in{m.group(1)}{m.group(2).replace("$0", "b").replace("$1", "t")}{m.group(3)}}}',
src)
def return_type(src, name):
"""The declared result type of `func name(…)` in `src`."""
m = re.search(rf'func {name}\(', src)
end = closing(src, m.end())
return re.match(r'\s*throws[^-{]*->\s*([^{]+?)\s*\{', src[end:]).group(1)
def alternative_name(fn, numbered, i):
if numbered:
return f'p{i}'
name = RENAME.get(fn) or fn.split('_')[-1]
return f'_{name}' if name in KEYWORDS or name[0].isdigit() else name
def array_literal(names, one_per_line):
return '[\n' + ''.join(f' {n},\n' for n in names) + ']' if one_per_line else f'[{", ".join(names)}]'
def rewrite_array_one_of(src, path):
# The array form of parseOneOf takes `ParseAlternative`s, one `let` each (a typed-throws closure
# literal as an array element crashes SILGen):
# return try buffer.parseOneOf([{ try parseX_a(buffer: &$0, tracker: $1) }, self.parseB], tracker: tracker)
# ->
# let p1 = ParseAlternative<T> { b, t throws(ParseFailure) in
# try parseX_a(buffer: &b, tracker: t)
# }
# let b = ParseAlternative<T> { b, t throws(ParseFailure) in
# try self.parseB(buffer: &b, tracker: t)
# }
# return try buffer.parseOneOf([b, p1], tracker: tracker)
numbered = not any(path.endswith(f) for f in NAMED_FILES)
out, i = [], 0
for m in re.finditer(r'(\w+)\.parseOneOf\(\s*\[', src):
line = src.rfind('\n', 0, m.start()) + 1
indent = re.match(r'\s*', src[line:]).group()
close = closing(src, m.end())
tail = re.match(r'\s*,\s*tracker: (\w+)\s*\)', src[close:])
calls = re.findall(r'\{ try (\w+)\(buffer: &\$0, tracker: \$1\) \}', src[m.end():close])
methods = re.findall(r'self\.(\w+),', src[m.end():close])
assert len(calls) + len(methods) == src[m.end():close].count('\n') - 1, src[m.end():close]
t = return_type(src, (calls + methods)[0])
own_frame = calls[0].split('_')[0] in OWN_FRAME
width = LINE_LENGTH - len(indent) - 4 * own_frame
def let(name, call):
short = f'let {name} = ParseAlternative<{t}> {{ b, t {TYPED} in try {call}(buffer: &b, tracker: t) }}\n'
long = f'let {name} = ParseAlternative<{t}> {{ b, t {TYPED} in\n try {call}(buffer: &b, tracker: t)\n}}\n'
return short if len(short) - 1 <= width else long
lets, names = '', []
for k, fn in enumerate(calls, 1):
names.append(alternative_name(fn, numbered, k))
lets += let(names[-1], fn)
assert len(methods) <= 1, methods # the one site lists it first: `[self.parseFlagList, { … }]`
for fn in methods: # `self.parseFlagList` -> `flagList`, first in the array as in the literal
names.insert(0, fn[len('parse')].lower() + fn[len('parse') + 1:])
lets += let(names[0], 'self.' + fn)
# More than one statement now, so an implicit return becomes explicit.
head = re.sub(r'^try ', 'return try ', src[line + len(indent):m.start()])
call = f'{head}{m.group(1)}.parseOneOf'
if own_frame:
body = lets + 'return ' + array_literal(names, True)
stmt = (f'// Built in its own frame: the {len(names)} closure values would otherwise sit in every recursion'
" level's\n// frame (debug builds keep each `let`), and `(` nests this production up to the tracker"
' limit.\n'
f'func alternatives() -> [ParseAlternative<{t}>] {{\n'
+ re.sub(r'^(?=.)', ' ', body, flags=re.M) + '\n}\n'
f'{call}(alternatives(), tracker: {tail.group(1)})')
else:
stmt = f'{lets}{call}({array_literal(names, calls[0] in ONE_PER_LINE)}, tracker: {tail.group(1)})'
out += [src[i:line], re.sub(r'^(?=.)', indent, stmt, flags=re.M)]
i = close + tail.end()
return ''.join(out) + src[i:]
def optional_spaces(src):
return re.sub(r'(\n(\s*))try\? (\w+)\.parseSpaces\(\)',
r'\1// Spaces are optional; incomplete still propagates.\1do { try \3.parseSpaces() } catch .mismatch {}',
src)
def in_closure(src, pos):
"""Whether the innermost closure or function body around `pos` is a closure."""
stack, k = [], 0
while k < pos:
c = src[k]
if src.startswith('//', k):
k = src.index('\n', k)
continue
if c == '"':
k += 1
while src[k] != '"':
k += 2 if src[k] == '\\' else 1
elif c == '{':
stack.append(k)
elif c == '}':
stack.pop()
k += 1
for o in reversed(stack):
if re.match(rf'[^{{}}]*?{re.escape(TYPED)}[^{{}}]*?\s+in\b', src[o + 1:]):
return True
if re.search(rf'\bfunc\b[^{{}}]*$', src[:o]):
return False
return False
def annotate_do(src):
# `do` inside a closure doesn't infer typed throws, so a `catch .mismatch` there needs `do throws(…)`.
out, i = [], 0
for m in re.finditer(r'\n(\s*)do \{', src):
catch = re.match(r'\s*catch (\S)', src[closing(src, m.end()):])
if not (catch and catch.group(1) == '.' and in_closure(src, m.start())):
continue
func = re.findall(r'\n func (\w+)\(', src[:m.start()])[-1] # the enclosing member
why = f"\n{m.group(1)}// `do` inside a closure doesn't infer typed throws; annotate it." if func in EXPLAIN_DO else ''
out += [src[i:m.start()], why, f'\n{m.group(1)}do {TYPED} {{']
i = m.end()
return ''.join(out) + src[i:]
def wrap_declarations(src):
# A declaration too long for one line puts each parameter on its own line.
def wrap(m):
indent, head, params, tail = m.groups()
if len(m.group(0)) <= LINE_LENGTH or re.search(r'func (\w+)', head).group(1) in BRACE_BELOW:
return m.group(0)
parts, depth, start = [], 0, 0
for k, c in enumerate(params):
depth += c in '([<'
depth -= c in ')]>'
if c == ',' and depth == 0:
parts.append(params[start:k].strip())
start = k + 1
parts.append(params[start:].strip())
return f'{indent}{head}(\n' + ''.join(f'{indent} {p},\n' for p in parts)[:-2] + f'\n{indent}) {tail} {{'
return re.sub(rf'^( *)((?:\w+ )*func \w+)\((.*)\) ({re.escape(TYPED)}.*) \{{$', wrap, src, flags=re.M)
def convert_test(src):
# Tests calling typed internals: `errorThrown` -> `parseErrorThrown`, which unwraps the ParseFailure.
# `errorThrown { … } != nil` doesn't look at the type and stays.
src = re.sub(r'\berrorThrown\b(?![^\n]*\} != nil)', 'parseErrorThrown', src)
# Only closures passed to the cursor's combinators need typed throws; fixtures take untyped ones.
src = throw_sites(src)
return re.sub(r'(\.composite\(tracker: [^\n]*?\) )(\{[^{}\n]* in)(?= \}$|$)',
lambda m: m.group(1) + closures(m.group(2)), src, flags=re.M)
for path in sys.argv[1:]:
src = open(path).read()
if '/Tests/' in '/' + path:
open(path, 'w').write(convert_test(src))
continue
for file, old, new in HAND:
if path.endswith('/' + file):
assert src.count(old) == 1, (path, old)
src = src.replace(old, new)
src = code_lines(src, lambda l: l if 'rethrows' in l else re.sub(r'\bthrows\b(?!\()', TYPED, l))
src = re.sub(r'((?<!/)//(?!/).*?)`?IncompleteMessage`?', r'\1`.incomplete`', src)
src = rewrite_array_one_of(src, path)
src = throw_sites(src)
src = catch_clauses(src)
src = closures(src)
src = optional_spaces(src)
src = annotate_do(src)
src = wrap_declarations(src)
open(path, 'w').write(src)
513 lines
22 KiB
Swift
513 lines
22 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the SwiftNIO open source project
|
|
//
|
|
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
|
|
// Licensed under Apache License v2.0
|
|
//
|
|
// See LICENSE.txt for license information
|
|
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
/// Parsing a server response exceeded the maximum allowed message attributes.
|
|
///
|
|
/// Each ``MessageAttribute`` in a FETCH response is counted. If a server sends a FETCH
|
|
/// response with more attributes than allowed, this error is thrown. This is a DoS
|
|
/// protection limit.
|
|
///
|
|
/// - SeeAlso: ``MessageAttribute``, ``ExceededMaximumBodySizeError``
|
|
public struct ExceededMaximumMessageAttributesError: Error {
|
|
/// The actual number of message attributes in the response.
|
|
public var actualCount: Int
|
|
|
|
/// The configured maximum number of attributes allowed.
|
|
public var maximumCount: Int
|
|
|
|
/// Creates a new error with the actual and maximum attribute counts.
|
|
///
|
|
/// - Parameters:
|
|
/// - actualCount: The number of attributes encountered
|
|
/// - maximumCount: The configured limit
|
|
public init(actualCount: Int, maximumCount: Int) {
|
|
self.actualCount = actualCount
|
|
self.maximumCount = maximumCount
|
|
}
|
|
}
|
|
|
|
/// Parsing a server response exceeded the maximum allowed body size.
|
|
///
|
|
/// Server responses can include large message bodies (for example, in FETCH responses).
|
|
/// If a body exceeds the configured maximum size, this error is thrown. This is a
|
|
/// DoS and memory protection limit.
|
|
///
|
|
/// - SeeAlso: ``ExceededMaximumMessageAttributesError``, ``ResponseParser/Options``
|
|
public struct ExceededMaximumBodySizeError: Error {
|
|
/// The actual number of bytes in the body.
|
|
public var actualCount: UInt64
|
|
|
|
/// The configured maximum body size.
|
|
public var maximumCount: UInt64
|
|
|
|
/// Creates a new error with the actual and maximum body sizes.
|
|
///
|
|
/// - Parameters:
|
|
/// - actualCount: The number of body bytes encountered
|
|
/// - maximumCount: The configured limit
|
|
public init(actualCount: UInt64, maximumCount: UInt64) {
|
|
self.actualCount = actualCount
|
|
self.maximumCount = maximumCount
|
|
}
|
|
}
|
|
|
|
/// A parser for IMAP server responses.
|
|
///
|
|
/// `ResponseParser` incrementally parses the stream of bytes sent by an IMAP server,
|
|
/// converting them into ``ResponseOrContinuationRequest`` values (which contain either
|
|
/// a ``Response`` or a ``ContinuationRequest``). It handles all response types defined
|
|
/// by RFC 3501 and supported extensions, including:
|
|
/// - Tagged responses (command completions)
|
|
/// - Untagged responses (unsolicited data, mailbox state changes)
|
|
/// - FETCH responses with streaming support
|
|
/// - Continuation requests for multi-part operations
|
|
///
|
|
/// The parser maintains internal state for handling responses that arrive incomplete
|
|
/// or fragmented across multiple network packets.
|
|
///
|
|
/// ## Usage
|
|
///
|
|
/// ```swift
|
|
/// var parser = ResponseParser()
|
|
/// var buffer = IMAPInputBuffer()
|
|
/// buffer.append(bytesFromTheNetwork)
|
|
/// while let response = try parser.parseResponseStream(buffer: &buffer) {
|
|
/// // Process response
|
|
/// }
|
|
/// ```
|
|
///
|
|
/// - SeeAlso: ``ResponseOrContinuationRequest``, ``Response``, ``ContinuationRequest``, ``Options``,
|
|
/// [RFC 3501 Section 7](https://datatracker.ietf.org/doc/html/rfc3501#section-7) (server responses)
|
|
public struct ResponseParser: Parser, Sendable {
|
|
/// Configuration options for response parsing.
|
|
///
|
|
/// `Options` allows tuning the parser's behavior and limits, particularly for
|
|
/// DoS protection and memory management when dealing with potentially untrusted
|
|
/// server responses.
|
|
public struct Options: Sendable {
|
|
/// The maximum amount of data the parser can buffer at any time.
|
|
///
|
|
/// If the parser's internal buffer exceeds this limit, parsing fails. This
|
|
/// prevents malformed responses from consuming excessive memory.
|
|
/// Defaults to 8192 bytes.
|
|
public var bufferLimit: Int
|
|
|
|
/// The maximum number of message attributes allowed in a single FETCH response.
|
|
///
|
|
/// Each attribute (BODY, FLAGS, ENVELOPE, etc.) in a FETCH response is counted.
|
|
/// Defaults to `Int.max` (effectively unlimited).
|
|
public var messageAttributeLimit: Int
|
|
|
|
/// The maximum size of message body data in a single response.
|
|
///
|
|
/// If a FETCH response includes body data larger than this limit, parsing fails.
|
|
/// Defaults to `UInt64.max` (effectively unlimited).
|
|
public var bodySizeLimit: UInt64
|
|
|
|
/// The maximum size of a single literal in the response.
|
|
///
|
|
/// Literals (data between `{size}` markers) larger than this limit will cause
|
|
/// an error. Defaults to ``IMAPDefaults/literalSizeLimit`` (4096 bytes).
|
|
public var literalSizeLimit: Int
|
|
|
|
/// Optional string interning/caching function for parsed strings.
|
|
///
|
|
/// When provided, every parsed string is passed through this function, which
|
|
/// can return a cached version. This reduces memory usage for responses with
|
|
/// many repeated strings (for example, flag names). Defaults to `nil` (no caching).
|
|
public var parsedStringCache: (@Sendable (String) -> String)?
|
|
|
|
/// Creates new response parser options.
|
|
///
|
|
/// - Parameters:
|
|
/// - bufferLimit: Maximum buffered bytes. Defaults to 8192.
|
|
/// - messageAttributeLimit: Maximum FETCH attributes. Defaults to Int.max.
|
|
/// - bodySizeLimit: Maximum body size. Defaults to UInt64.max.
|
|
/// - literalSizeLimit: Maximum literal size. Defaults to 4096 bytes.
|
|
/// - parsedStringCache: Optional string caching function. Defaults to nil.
|
|
public init(
|
|
bufferLimit: Int = 8_192,
|
|
messageAttributeLimit: Int = .max,
|
|
bodySizeLimit: UInt64 = .max,
|
|
literalSizeLimit: Int = IMAPDefaults.literalSizeLimit,
|
|
parsedStringCache: (@Sendable (String) -> String)? = nil
|
|
) {
|
|
self.bufferLimit = bufferLimit
|
|
self.messageAttributeLimit = messageAttributeLimit
|
|
self.bodySizeLimit = bodySizeLimit
|
|
self.literalSizeLimit = literalSizeLimit
|
|
self.parsedStringCache = parsedStringCache
|
|
}
|
|
}
|
|
|
|
enum AttributeState: Hashable, Sendable {
|
|
case head
|
|
case attribute
|
|
case separator
|
|
}
|
|
|
|
enum ResponseState: Hashable, Sendable {
|
|
case fetchOrNormal
|
|
case fetchMiddle(attributeCount: Int)
|
|
}
|
|
|
|
enum Mode: Hashable, Sendable {
|
|
case response(ResponseState)
|
|
case streamingQuoted(attributeCount: Int)
|
|
case attributeBytes(Int, attributeCount: Int)
|
|
}
|
|
|
|
let parser: GrammarParser
|
|
let bufferLimit: Int
|
|
let messageAttributeLimit: Int
|
|
let bodySizeLimit: UInt64
|
|
private var mode: Mode
|
|
/// Newline kind of the last successfully parsed response.
|
|
private var lastResponseNewlineEnding: ParseInput.Newline?
|
|
|
|
/// Creates a new `ResponseParser` with configuration options.
|
|
///
|
|
/// - Parameter options: Configuration for buffer limits, size restrictions, and
|
|
/// optional string caching. Defaults to standard limits suitable for most servers.
|
|
///
|
|
/// - SeeAlso: ``Options``
|
|
public init(
|
|
options: Options = Options()
|
|
) {
|
|
self.bufferLimit = options.bufferLimit
|
|
self.mode = .response(.fetchOrNormal)
|
|
self.messageAttributeLimit = options.messageAttributeLimit
|
|
self.parser = GrammarParser(
|
|
literalSizeLimit: options.literalSizeLimit,
|
|
parsedStringCache: options.parsedStringCache
|
|
)
|
|
self.bodySizeLimit = options.bodySizeLimit
|
|
self.lastResponseNewlineEnding = nil
|
|
}
|
|
|
|
/// Parses a server response from incoming bytes.
|
|
///
|
|
/// Incrementally consumes bytes from the buffer and returns parsed responses.
|
|
/// The parser maintains state across calls, so it can handle responses that arrive
|
|
/// fragmented across multiple network packets.
|
|
///
|
|
/// Returns `nil` when more data is needed. Throws an error if:
|
|
/// - The buffer exceeds ``Options/bufferLimit``
|
|
/// - A literal exceeds ``Options/literalSizeLimit``
|
|
/// - A FETCH response has too many attributes (exceeds ``Options/messageAttributeLimit``)
|
|
/// - A body exceeds ``Options/bodySizeLimit``
|
|
/// - The response violates IMAP syntax
|
|
/// - UTF-8 validation fails
|
|
///
|
|
/// - Parameter inputBytes: The received bytes. Whatever the parser consumes is discarded from the
|
|
/// front, so the same buffer is passed again as more arrives.
|
|
///
|
|
/// - Returns: A ``ResponseOrContinuationRequest`` if a complete response element is parsed,
|
|
/// or `nil` if more data is needed.
|
|
///
|
|
/// - Throws: ``ParserError`` for syntax errors, ``ExceededMaximumMessageAttributesError``
|
|
/// for attribute limit violations, ``ExceededMaximumBodySizeError`` for body size violations,
|
|
/// ``TooMuchRecursion`` for overly nested structures, ``NoForwardProgress`` if parsing stopped
|
|
/// consuming input.
|
|
///
|
|
/// - Important: `.fetch(.streamingEnd)` consumes no bytes, and is never followed by another result
|
|
/// that does not. A caller driving this in its own loop, rather than through `IMAPClientHandler`,
|
|
/// should stop when results keep coming without the buffer shrinking: that is what
|
|
/// `IMAPClientHandler` does, and it is the guard against a parser bug spinning forever.
|
|
///
|
|
/// - SeeAlso: ``ResponseOrContinuationRequest``, ``Options``,
|
|
/// [RFC 3501 Section 7](https://datatracker.ietf.org/doc/html/rfc3501#section-7)
|
|
public mutating func parseResponseStream(
|
|
buffer inputBytes: inout IMAPInputBuffer
|
|
) throws -> ResponseOrContinuationRequest? {
|
|
let tracker = StackTracker.makeNewDefault
|
|
// Whatever the parser consumed is discarded on *every* exit path, a throw included, which is
|
|
// what `parse` does: the streaming modes legitimately make progress and then report that they
|
|
// need more bytes, and `skipLF` below consumes a byte outside any backtracking scope.
|
|
return try inputBytes.parse { input in
|
|
// Incomplete input is handled here, unboxed; anything else leaves as its public error type.
|
|
do throws(ParseFailure) {
|
|
switch self.mode {
|
|
case .response(let state):
|
|
// Handle orphaned CR/LF from split CRLF where previous buffer ended with CR-only:
|
|
if self.lastResponseNewlineEnding == .cr, input.skipLF() {
|
|
// Did consume complete CR-LF pair:
|
|
self.lastResponseNewlineEnding = .crlf
|
|
}
|
|
|
|
let result = try self.parseResponseAndNewline(
|
|
state: state,
|
|
buffer: &input,
|
|
tracker: tracker
|
|
)
|
|
self.lastResponseNewlineEnding = result.newline
|
|
return result.response
|
|
case .attributeBytes(let remaining, attributeCount: let attributeCount):
|
|
// Handle orphaned LF from a literal header's CRLF split across buffers. Only the
|
|
// first byte after the header can be that LF. Any other is part of the literal.
|
|
if self.lastResponseNewlineEnding == .cr, !input.isEmpty {
|
|
input.skipLF()
|
|
self.lastResponseNewlineEnding = nil
|
|
}
|
|
return .response(
|
|
try self.parseBytes(
|
|
buffer: &input,
|
|
tracker: tracker,
|
|
remaining: remaining,
|
|
attributeCount: attributeCount
|
|
)
|
|
)
|
|
case .streamingQuoted(attributeCount: let attributeCount):
|
|
return .response(try self.parseQuotedBytes(buffer: &input, attributeCount: attributeCount))
|
|
}
|
|
} catch .incomplete {
|
|
return nil
|
|
} catch {
|
|
throw error.unwrapped
|
|
}
|
|
}
|
|
}
|
|
|
|
private mutating func moveStateMachine<Return>(expected: Mode, next: Mode, returnValue: Return) -> Return {
|
|
if case expected = self.mode {
|
|
self.mode = next
|
|
return returnValue
|
|
} else {
|
|
fatalError("Unexpected state \(self.mode)")
|
|
}
|
|
}
|
|
|
|
private mutating func moveStateMachine(expected: Mode, next: Mode) {
|
|
self.moveStateMachine(expected: expected, next: next, returnValue: ())
|
|
}
|
|
}
|
|
|
|
// MARK: - Parse responses
|
|
|
|
extension ResponseParser {
|
|
struct ResponseAndNewline {
|
|
var response: ResponseOrContinuationRequest
|
|
var newline: ParseInput.Newline?
|
|
}
|
|
|
|
private mutating func parseResponseAndNewline(
|
|
state: ResponseState,
|
|
buffer: inout ParseInput,
|
|
tracker: StackTracker
|
|
) throws(ParseFailure) -> ResponseAndNewline {
|
|
let response = try parseResponse(
|
|
state: state,
|
|
buffer: &buffer,
|
|
tracker: tracker
|
|
)
|
|
return ResponseAndNewline(
|
|
response: response,
|
|
newline: buffer.terminatingNewline
|
|
)
|
|
}
|
|
|
|
private mutating func parseResponse(
|
|
state: ResponseState,
|
|
buffer: inout ParseInput,
|
|
tracker: StackTracker
|
|
) throws(ParseFailure) -> ResponseOrContinuationRequest {
|
|
enum _Response: Hashable {
|
|
case untaggedResponse(ResponsePayload)
|
|
case fetchResponse(GrammarParser._FetchResponse)
|
|
}
|
|
|
|
func parseResponse_fetch(buffer: inout ParseInput, tracker: StackTracker) throws(ParseFailure) -> _Response {
|
|
switch state {
|
|
case .fetchOrNormal:
|
|
return .fetchResponse(try self.parser.parseFetchResponseStart(buffer: &buffer, tracker: tracker))
|
|
case .fetchMiddle:
|
|
return .fetchResponse(try self.parser.parseFetchResponse(buffer: &buffer, tracker: tracker))
|
|
}
|
|
}
|
|
|
|
func parseResponse_normal(buffer: inout ParseInput, tracker: StackTracker) throws(ParseFailure) -> _Response {
|
|
let response = try self.parser.parseResponseData(buffer: &buffer, tracker: tracker)
|
|
return .untaggedResponse(response)
|
|
}
|
|
|
|
return try buffer.composite(tracker: tracker) { buffer, tracker throws(ParseFailure) in
|
|
// Spaces are optional; incomplete still propagates.
|
|
do throws(ParseFailure) { try buffer.parseSpaces() } catch .mismatch {}
|
|
do throws(ParseFailure) {
|
|
let response = try buffer.parseOneOf(
|
|
{ b, t throws(ParseFailure) in try parseResponse_fetch(buffer: &b, tracker: t) },
|
|
{ b, t throws(ParseFailure) in try parseResponse_normal(buffer: &b, tracker: t) },
|
|
tracker: tracker
|
|
)
|
|
switch response {
|
|
case .fetchResponse(.start(let num)):
|
|
self.moveStateMachine(
|
|
expected: .response(.fetchOrNormal),
|
|
next: .response(.fetchMiddle(attributeCount: 0))
|
|
)
|
|
return .response(.fetch(.start(num)))
|
|
case .fetchResponse(.startUID(let num)):
|
|
self.moveStateMachine(
|
|
expected: .response(.fetchOrNormal),
|
|
next: .response(.fetchMiddle(attributeCount: 0))
|
|
)
|
|
return .response(.fetch(.startUID(num)))
|
|
case .fetchResponse(.literalStreamingBegin(kind: let kind, byteCount: let size)):
|
|
try self.guardStreamingSizeLimit(size: size)
|
|
let attributeCount = try self.guardFetchMiddleAttributeCount()
|
|
self.moveStateMachine(
|
|
expected: .response(.fetchMiddle(attributeCount: attributeCount)),
|
|
next: .attributeBytes(size, attributeCount: attributeCount + 1)
|
|
)
|
|
return .response(.fetch(.streamingBegin(kind: kind, byteCount: size)))
|
|
|
|
case .fetchResponse(.quotedStreamingBegin(kind: let kind, byteCount: let size)):
|
|
try self.guardStreamingSizeLimit(size: size)
|
|
let attributeCount = try self.guardFetchMiddleAttributeCount()
|
|
self.moveStateMachine(
|
|
expected: .response(.fetchMiddle(attributeCount: attributeCount)),
|
|
next: .streamingQuoted(attributeCount: attributeCount + 1)
|
|
)
|
|
return .response(.fetch(.streamingBegin(kind: kind, byteCount: size)))
|
|
|
|
case .fetchResponse(.finish):
|
|
let attributeCount = try self.guardFetchMiddleAttributeCount()
|
|
self.moveStateMachine(
|
|
expected: .response(.fetchMiddle(attributeCount: attributeCount)),
|
|
next: .response(.fetchOrNormal)
|
|
)
|
|
return .response(.fetch(.finish))
|
|
|
|
case .untaggedResponse(let payload):
|
|
return .response(.untagged(payload))
|
|
|
|
case .fetchResponse(.simpleAttribute(let att)):
|
|
let attributeCount = try self.guardFetchMiddleAttributeCount()
|
|
self.moveStateMachine(
|
|
expected: .response(.fetchMiddle(attributeCount: attributeCount)),
|
|
next: .response(.fetchMiddle(attributeCount: attributeCount + 1))
|
|
)
|
|
return .response(.fetch(.simpleAttribute(att)))
|
|
}
|
|
} catch .mismatch {
|
|
return try self._parseResponse(buffer: &buffer, tracker: tracker)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Validates that the attribute count is within the allowed limit, and returns it.
|
|
private func guardFetchMiddleAttributeCount() throws(ParseFailure) -> Int {
|
|
guard case .response(.fetchMiddle(attributeCount: let attributeCount)) = self.mode else {
|
|
preconditionFailure("We should be in fetch middle: \(self.mode)")
|
|
}
|
|
guard attributeCount < self.messageAttributeLimit else {
|
|
throw .messageAttributesExceeded(
|
|
ExceededMaximumMessageAttributesError(
|
|
actualCount: attributeCount,
|
|
maximumCount: self.messageAttributeLimit
|
|
)
|
|
)
|
|
}
|
|
return attributeCount
|
|
}
|
|
|
|
private func guardStreamingSizeLimit(size: Int) throws(ParseFailure) {
|
|
guard size < self.bodySizeLimit else {
|
|
throw .bodySizeExceeded(
|
|
ExceededMaximumBodySizeError(
|
|
actualCount: UInt64(exactly: size) ?? 0,
|
|
maximumCount: self.bodySizeLimit
|
|
)
|
|
)
|
|
}
|
|
}
|
|
|
|
private func _parseResponse(
|
|
buffer: inout ParseInput,
|
|
tracker: StackTracker
|
|
) throws(ParseFailure) -> ResponseOrContinuationRequest {
|
|
func parseResponse_continuation(
|
|
buffer: inout ParseInput,
|
|
tracker: StackTracker
|
|
) throws(ParseFailure) -> ResponseOrContinuationRequest {
|
|
.continuationRequest(try self.parser.parseContinuationRequest(buffer: &buffer, tracker: tracker))
|
|
}
|
|
|
|
func parseResponse_tagged(
|
|
buffer: inout ParseInput,
|
|
tracker: StackTracker
|
|
) throws(ParseFailure) -> ResponseOrContinuationRequest {
|
|
.response(.tagged(try self.parser.parseTaggedResponse(buffer: &buffer, tracker: tracker)))
|
|
}
|
|
|
|
let continuation = ParseAlternative<ResponseOrContinuationRequest> { b, t throws(ParseFailure) in
|
|
try parseResponse_continuation(buffer: &b, tracker: t)
|
|
}
|
|
let tagged = ParseAlternative<ResponseOrContinuationRequest> { b, t throws(ParseFailure) in
|
|
try parseResponse_tagged(buffer: &b, tracker: t)
|
|
}
|
|
return try buffer.parseOneOf([continuation, tagged], tracker: tracker)
|
|
}
|
|
}
|
|
|
|
// MARK: - Parse bytes
|
|
|
|
extension ResponseParser {
|
|
/// Extracts the next run of a streamed literal. If more bytes are present than are required only
|
|
/// those that are required are extracted, and if fewer have arrived then what there is comes back
|
|
/// and the rest follows on a later call.
|
|
/// - parameter buffer: The cursor from which bytes should be extracted.
|
|
/// - returns: A `.streamingBytes` response carrying the extracted run, or `.streamingEnd`.
|
|
private mutating func parseBytes(
|
|
buffer: inout ParseInput,
|
|
tracker: StackTracker,
|
|
remaining: Int,
|
|
attributeCount: Int
|
|
) throws(ParseFailure) -> Response {
|
|
guard remaining == 0 else {
|
|
let bytes = try buffer.extractBuffer(
|
|
upTo: remaining
|
|
)
|
|
let leftToRead = remaining - bytes.count
|
|
assert(leftToRead >= 0, "\(leftToRead) is negative")
|
|
|
|
return self.moveStateMachine(
|
|
expected: .attributeBytes(remaining, attributeCount: attributeCount),
|
|
next: .attributeBytes(leftToRead, attributeCount: attributeCount),
|
|
returnValue: .fetch(.streamingBytes(bytes))
|
|
)
|
|
}
|
|
return self.moveStateMachine(
|
|
expected: .attributeBytes(remaining, attributeCount: attributeCount),
|
|
// we've finished parsing an attribute here so increment the count
|
|
next: .response(.fetchMiddle(attributeCount: attributeCount + 1)),
|
|
returnValue: .fetch(.streamingEnd)
|
|
)
|
|
}
|
|
|
|
private mutating func parseQuotedBytes(
|
|
buffer: inout ParseInput,
|
|
attributeCount: Int
|
|
) throws(ParseFailure) -> Response {
|
|
let quoted = try self.parser.parseQuoted(buffer: &buffer, tracker: .makeNewDefault)
|
|
return self.moveStateMachine(
|
|
expected: .streamingQuoted(attributeCount: attributeCount),
|
|
next: .attributeBytes(0, attributeCount: attributeCount),
|
|
// `parseQuoted` unescapes into a fresh array when the string contains escapes, and it is
|
|
// bounded by `lineLengthLimit` either way, so these bytes are owned rather than referenced.
|
|
returnValue: .fetch(.streamingBytes(IMAPBuffer(quoted)))
|
|
)
|
|
}
|
|
}
|