Files
swift-nio-imap/Sources/NIOIMAPCore/Parser/ParserErrors.swift
Daniel Eggert 1993d6177b Throw NoForwardProgress when parsing stops consuming
A parser bug that stops consuming input used to spin forever on peer
bytes: extractBytes looped with take == 0 once the cursor invariant
broke, the repetition combinators looped on an element that matched
empty, and IMAPInputProcessor looped on a decoder returning messages
without consuming. Each now throws the new public NoForwardProgress
(public init, so a decoder driver outside the library can throw it as
IMAPInputProcessor does), which no backtracking point treats as "did
not match":

- extractBytes throws when the head is empty but bytes remain; the
  scans stop when advancing their walker consumes nothing. Both also
  assertionFailure, and a debug-only check in advance compares what it
  consumed against what was visible before, so tests trap at the bug.
- forEachRepetition backs every repetition combinator and the search
  sources list; the other hand-written grammar loops check progress per
  iteration (requireProgress).
- IMAPInputProcessor allows 4 messages in a row without progress; the
  parsers emit at most 2 (commands) and 1 (responses), pinned by tests
  that run the real decoders.

Catch sites that took any error for a mismatch now catch ParserError
only, or let NoForwardProgress through: mailbox list flags, the body
and section fallbacks, and the run-away literal check. (#885 already
narrowed the tagged extension catches.)

Behavior changes: those loops now report a list cut short by the end of
the input as IncompleteMessage instead of returning what they had. Mostly
not observable through the stream parsers, which retry; a flag list
split mid-flag gets a split-at-every-byte case. The stream parser docs
tell callers who drive them directly to bound results without progress,
as the handlers do.

Reviewer focus: the catch sites, and the limit's reasoning in
IMAPInputProcessor.maximumMessagesWithoutProgress.
2026-11-25 21:19:43 +09:00

155 lines
6.6 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
//
//===----------------------------------------------------------------------===//
/// Decodes `bytes` as UTF-8.
///
/// A free function rather than a `String` initialiser because it throws a ``ParserError`` carrying the
/// source location that asked for the decode, which is what the grammar wants and what a general-purpose
/// initialiser has no business reporting.
///
/// - Throws: ``ParserError`` when `bytes` are not valid UTF-8.
func decodeUTF8(
_ bytes: some Collection<UInt8>,
file: StaticString = (#fileID),
line: Int = #line
) throws -> String {
guard let string = String(validatingUTF8Bytes: bytes) else {
throw ParserError.invalidUTF8(file: file, line: line)
}
return string
}
/// The parser needs more bytes before it can decide.
///
/// Thrown, rather than returned, because it can arise anywhere in the grammar; the entry points turn
/// it back into "no message yet".
struct IncompleteMessage: Error {
internal init() {}
}
/// Parsing a tagged command failed. Includes the tag of the invalid command, and the parsing error.
///
/// When the server receives a command from a client, it includes a tag for correlation.
/// If the command line cannot be parsed, this error includes both the tag (so the server
/// can send back a properly-tagged error response) and details about what went wrong.
///
/// - SeeAlso: ``ParserError``, [RFC 3501 Section 6.1](https://datatracker.ietf.org/doc/html/rfc3501#section-6.1)
public struct BadCommand: Error {
/// The tag of the bad command.
///
/// Allows the server to send a properly-tagged error response to the client,
/// maintaining IMAP's request/response correlation even when the command is malformed.
public var commandTag: Command.Tag
/// Why parsing failed.
///
/// Contains a human-readable hint about the parsing error and source location information.
public var parserError: ParserError
}
/// An error occurred when parsing an IMAP command or response.
///
/// `ParserError` is thrown when the IMAP protocol parser encounters bytes that cannot be
/// interpreted according to the IMAP grammar (RFC 3501 or extensions). Common causes include:
/// - Invalid UTF-8 sequences in string fields
/// - Malformed protocol syntax (for example, unexpected characters or missing required elements)
/// - Non-conforming protocol elements
///
/// The ``hint`` field provides a developer-friendly description of what went wrong.
/// The internal file and line information is useful for debugging parser issues.
///
/// - SeeAlso: [RFC 3501 Section 4](https://datatracker.ietf.org/doc/html/rfc3501#section-4) (grammar)
public struct ParserError: Error {
static func invalidUTF8(file: StaticString = (#fileID), line: Int = #line) -> Self {
ParserError(hint: "Invalid UTF8", file: file, line: line)
}
/// If possible, a description of the error and why it occurred.
///
/// Describes the parsing failure in human-readable terms, such as
/// "Invalid UTF8", "Missing CRLF", "Unexpected character", etc. It's intended
/// for logging and debugging purposes.
///
/// - Note: These errors are thrown as part of ordinary control flow — `parseOneOf` throws one
/// for every alternative that doesn't match — so the hint must not be built by string
/// interpolation on any path that is taken often. A plain literal costs nothing; an
/// interpolation heap-allocates as soon as the result exceeds 15 UTF-8 bytes.
public var hint: String
/// `StaticString` rather than `String`: `#fileID` is longer than the 15-byte small-string limit,
/// so a `String` here would heap-allocate and retain on *every* throw, hint or no hint.
var file: StaticString
var line: Int
init(hint: String = "Unknown", file: StaticString = (#fileID), line: Int = #line) {
self.hint = hint
self.file = file
self.line = line
}
}
/// Signals that a protocol message was too complex and required excessive recursive parsing.
///
/// IMAP protocol elements can nest (for example, nested parenthesized lists in BODYSTRUCTURE),
/// and parsing uses recursion to handle this. To prevent stack overflow attacks,
/// the parser enforces a maximum recursion depth. If this limit is exceeded, this error
/// is thrown.
///
/// A safety limit to prevent malicious or extremely unusual protocol messages
/// from causing a stack overflow.
///
/// - SeeAlso: [RFC 3501 Section 4.3](https://datatracker.ietf.org/doc/html/rfc3501#section-4.3) (protocol syntax)
public struct TooMuchRecursion: Error {
/// The maximum number of recursive calls when parsing data before throwing an error.
///
/// The parser maintains a recursion depth counter and throws this error when the
/// depth would exceed this limit. This prevents stack overflow from deeply nested
/// protocol structures.
///
/// Currently fixed at compile-time and not configurable at runtime.
public var limit: Int
init(limit: Int) {
self.limit = limit
}
}
/// Signals that parsing stopped consuming input while it would otherwise have kept going.
///
/// Parsing that produces results without consuming bytes would produce them forever. Rather than spin,
/// the parser throws this, and the connection should be closed: no valid input causes it, so it means
/// either a parser bug or input crafted to find one.
///
/// Unlike ``ParserError`` it is never taken to mean "this alternative did not match", so no
/// backtracking point absorbs it.
public struct NoForwardProgress: Error {
/// `StaticString`: `#fileID` exceeds the small-string limit, so a `String` would allocate on the throw.
var file: StaticString
var line: Int
/// Creates the error, recording where the check that fired is.
///
/// - Parameters:
/// - file: The file of the check. Defaults to the caller's.
/// - line: The line of the check. Defaults to the caller's.
public init(file: StaticString = #fileID, line: Int = #line) {
self.file = file
self.line = line
}
}
extension NoForwardProgress: CustomStringConvertible {
/// Names the check that fired, which is what a log of this error is for.
public var description: String { "NoForwardProgress at \(file):\(line)" }
}