mirror of
https://github.com/apple/swift-nio-imap
synced 2026-11-29 05:24:23 +00:00
`PL.f(…, buffer: &b, tracker: t)` becomes `b.f(…)`, the spelling
ParseInput's primitives and combinators use, so that swapping the cursor
later touches only primitives. Bare grammar functions passed as values
become `{ try f(buffer: &$0, tracker: $1) }`.
Behavior unchanged except recursion accounting: leaf primitives
(matchFixed, parseSpaces, readByte, ...) no longer spend a frame of the
caller's StackTracker, so input at the depth limit can nest one to three
levels deeper. This is permanent, not a shim artifact: ParseInput's
leaves take no tracker. At the end of the stack SEARCH nesting depth 90
parses and 91 throws TooMuchRecursion (searchNestingDepthBoundary).
While the shim exists, matchNewline gets a fresh 100-frame budget.
ParseBuffer+CursorMethods.swift (hand-written, temporary) forwards the
new spellings to ParserLibrary; the rest is the output of the script
below. To reproduce, on the parent commit:
F=(Sources/NIOIMAPCore/Parser/Grammar/*.swift
Sources/NIOIMAPCore/Parser/{Command,Response}Parser.swift)
python3 rewrite_grammar.py $F && swift format -i $F
rewrite_grammar.py:
#!/usr/bin/env python3
# Rewrites ParserLibrary calls (`PL.f(…, buffer: &b, tracker: t)`) into cursor methods (`b.f(…)`),
# the shape ParseInput's primitives and combinators have.
#
# Usage: python3 rewrite_grammar.py FILE... (in place), then `swift format -i FILE...`
import re
import sys
LIT = r'"(?:[^"\\]|\\.)*"' # a string literal
B = r'buffer:\s*&(\w+)' # the cursor argument; its name becomes the receiver
T = r'tracker:\s*([\w.]+)' # the tracker argument
RULES = [
# Primitives that take no tracker. Their arguments are kept; `buffer:` and `tracker:` go.
(rf'PL\.parseFixedString\((\s*)({LIT}|\w+)((?:,\s*\w+:\s*[\w.]+)*),\s*{B},\s*{T}\s*\)', r'\4.matchFixed(\1\2\3)'),
(rf'PL\.parseFixedByte\(\s*([^,()]+),\s*{B},\s*{T}\s*\)', r'\2.matchByte(\1)'),
(rf'PL\.parseSpaces\(\s*{B},\s*{T}\s*\)', r'\1.parseSpaces()'),
(rf'PL\.parseNewline\(\s*{B},\s*{T}\s*\)', r'\1.matchNewline()'),
(rf'PL\.parseByte\(\s*{B},\s*{T}\s*\)', r'\1.readByte()'),
(rf'PL\.parseBytes\((\s*){B},\s*{T},\s*length:', r'\2.extractBytes(\1length:'),
(rf'PL\.parseBytes\((\s*){B},\s*{T},\s*upTo:', r'\2.extractBuffer(\1upTo:'),
(rf'PL\.(parse(?:Zero|One)OrMoreCharacters)\(\s*{B},\s*{T}\s*\)', r'\2.\1'),
(rf'PL\.(parse(?:Zero|One)OrMoreCharacters)\((\s*){B},\s*{T},\s*', r'\3.\1(\2'),
# `parser: PL.parseSpaces` as a value: spaces take no tracker, so it needs a closure.
(r'parser:\s*PL\.parseSpaces\b', r'parser: { input, _ in try input.parseSpaces() }'),
# Combinators keep their tracker; only `buffer:` moves to the receiver.
(rf'(?:PL|ParserLibrary)\.(composite|parseOptional|parseZeroOrMore|parseOneOrMore|parseUnsignedInteger|parseUnsignedInt64)\((\s*){B},\s*',
r'\3.\1(\2'),
(r'(?:ParserLibrary|PL)\.parseBufferAsUTF8\(', r'decodeUTF8('),
# The cursor takes enums where ParserLibrary took Bools.
(r'\bcaseSensitive:\s*true\b', 'caseSensitivity: .caseSensitive'),
(r'\bcaseSensitive:\s*false\b', 'caseSensitivity: .caseInsensitive'),
(r'\ballowLeadingSpaces:\s*true\b', 'leadingSpaces: .allowed'),
(r'\ballowLeadingSpaces:\s*false\b', 'leadingSpaces: .rejected'),
(r'\ballowLeadingZeros:\s*true\b', 'leadingZeros: .allowed'),
(r'\ballowLeadingZeros:\s*false\b', 'leadingZeros: .rejected'),
]
# Two call sites the hand-written code spells with a trailing closure rather than `parser:`.
TRAILING = ['parseByteRange_length', 'parseQuotaLimit']
# Grammar functions passed as values become closures, `{ try parseX(buffer: &$0, tracker: $1) }`: a
# local function over a non-escapable cursor cannot be a function value before Swift 6.4. `self.`
# method references stay as they are, and so does `parse2Digit`, which the hand-written code never
# wrapped.
KEEP = {'parse2Digit'}
def wrap(name):
return name if name in KEEP else f'{{ try {name}(buffer: &$0, tracker: $1) }}'
def closing(src, k):
"""Index just past the bracket matching the one before `k`."""
depth = 1
while depth:
c = src[k]
if c in '([{':
depth += 1
elif c in ')]}':
depth -= 1
k += 1
return k
def depth0(src, end):
"""Whether `src[end]` is outside every bracket opened in `src[:end]`."""
depth = 0
for c in src[:end]:
depth += c in '([{'
depth -= c in ')]}'
return depth == 0
def rewrite_one_of(src):
# PL.parseOneOf(a, b, buffer: &x, tracker: t) -> x.parseOneOf(a, b, tracker: t), wrapping bare
# `parseX` alternatives as above.
out, i = [], 0
while (j := src.find('PL.parseOneOf(', i)) >= 0:
k = j + len('PL.parseOneOf(')
m = closing(src, k)
args = src[k:m - 1]
arg = next(a for a in re.finditer(r'(\s*)buffer:\s*&(\w+),', args) if depth0(args, a.start()))
args = args[:arg.start()] + args[arg.end():]
args = re.sub(r'(?<=[(\[,])(\s*)(parse\w+)(?=\s*[,)\]])', lambda a: a.group(1) + wrap(a.group(2)), '(' + args)[1:]
out += [src[i:j], f'{arg.group(2)}.parseOneOf(', args, ')']
i = m
return ''.join(out) + src[i:]
for path in sys.argv[1:]:
src = open(path).read()
for pattern, replacement in RULES:
src = re.sub(pattern, replacement, src)
src = rewrite_one_of(src)
for name in TRAILING:
src = re.sub(rf',\s*parser:\s*{name}\s*\)', f') {{ try {name}(buffer: &$0, tracker: $1) }}', src)
src = re.sub(r'(parser:\s*)(parse\w+)\b(?!\()', lambda m: m.group(1) + wrap(m.group(2)), src)
open(path, 'w').write(src)
464 lines
20 KiB
Swift
464 lines
20 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
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
import struct NIO.ByteBuffer
|
|
|
|
/// A command stream part with synchronizing literal information.
|
|
///
|
|
/// When parsing client commands, the parser must handle synchronizing literals (RFC 3501 Section 4.3).
|
|
/// With synchronizing literals, the client sends the literal size, waits for a `+` continuation,
|
|
/// then sends the literal data. This struct wraps a ``CommandStreamPart`` with metadata about
|
|
/// how many synchronizing literals it contains.
|
|
///
|
|
/// When ``numberOfSynchronisingLiterals`` is greater than 0, the parser expects the server
|
|
/// to send that many `+` continuation requests before this command is complete.
|
|
///
|
|
/// - SeeAlso: ``CommandStreamPart``, [RFC 3501 Section 4.3.3](https://datatracker.ietf.org/doc/html/rfc3501#section-4.3.3)
|
|
public struct SynchronizedCommand: Hashable, Sendable {
|
|
/// The number of synchronising literals contained in the corresponding command.
|
|
///
|
|
/// When this is greater than 0, the server must send that many continuation
|
|
/// requests (`+` responses) to allow the client to send each literal's data.
|
|
/// Each synchronizing literal (format `{size}`) requires a `+` response before
|
|
/// the literal data is sent.
|
|
public var numberOfSynchronisingLiterals: Int
|
|
|
|
/// A command to be sent to a server.
|
|
///
|
|
/// The actual ``CommandStreamPart`` (or part of a command in streaming mode).
|
|
/// May be `nil` if only continuation data is being sent.
|
|
public var commandPart: CommandStreamPart?
|
|
|
|
/// Creates a new `SynchronizedCommand`.
|
|
///
|
|
/// - Parameters:
|
|
/// - commandPart: A ``CommandStreamPart``, if any. Defaults to `nil`.
|
|
/// - numberOfSynchronisingLiterals: How many synchronising literals are in the command.
|
|
/// Defaults to 0.
|
|
public init(_ commandPart: CommandStreamPart? = nil, numberOfSynchronisingLiterals: Int = 0) {
|
|
self.commandPart = commandPart
|
|
self.numberOfSynchronisingLiterals = numberOfSynchronisingLiterals
|
|
}
|
|
}
|
|
|
|
/// A parser for IMAP commands sent from a client to a server.
|
|
///
|
|
/// `CommandParser` incrementally parses the stream of bytes sent by an IMAP client,
|
|
/// converting them into ``CommandStreamPart`` structures that represent complete commands
|
|
/// or parts of commands (in the case of streaming operations like `APPEND` or `CATENATE`).
|
|
///
|
|
/// The parser handles:
|
|
/// - Regular commands (``Command``)
|
|
/// - Streaming commands (`APPEND` with literal data)
|
|
/// - Multi-part commands (`CATENATE`)
|
|
/// - IDLE command lifecycle
|
|
/// - Synchronizing literals (RFC 3501 Section 4.3) where the server sends `+` before literal data
|
|
///
|
|
/// The parser maintains internal state to track incomplete parsing operations and can process
|
|
/// incomplete input, returning `nil` until enough bytes are available for a complete element.
|
|
///
|
|
/// The parser expects correctly framed input, such as `FramingParser` provides. For example,
|
|
/// it doesn't skip an LF orphaned by a CRLF split across reads.
|
|
///
|
|
/// ## Usage
|
|
///
|
|
/// ```swift
|
|
/// var parser = CommandParser()
|
|
/// var buffer = ByteBuffer(bytes: clientData)
|
|
/// while let syncedCommand = try parser.parseCommandStream(buffer: &buffer) {
|
|
/// if syncedCommand.numberOfSynchronisingLiterals > 0 {
|
|
/// // Wait for continuation requests and responses
|
|
/// }
|
|
/// if let part = syncedCommand.commandPart {
|
|
/// // Process the command
|
|
/// }
|
|
/// }
|
|
/// ```
|
|
///
|
|
/// - SeeAlso: ``SynchronizedCommand``, ``CommandStreamPart``,
|
|
/// [RFC 3501 Section 5](https://datatracker.ietf.org/doc/html/rfc3501#section-5) (commands)
|
|
public struct CommandParser: Parser, Sendable {
|
|
enum Mode: Hashable, Sendable {
|
|
case lines
|
|
case idle
|
|
/// An `AUTHENTICATE` command has been parsed and we expect either the client's base64
|
|
/// challenge response(s) or the next ordinary command once authentication completes.
|
|
case expectingAuthenticationResponse
|
|
case waitingForMessage
|
|
case streamingBytes(Int)
|
|
case streamingEnd
|
|
case waitingForCatenatePart(seenPreviousPart: Bool)
|
|
case streamingCatenateBytes(Int)
|
|
case streamingCatenateEnd
|
|
|
|
var isStreamingAppend: Bool {
|
|
guard case .streamingBytes = self else {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
}
|
|
|
|
/// The context in which a command line is being parsed, controlling which inputs
|
|
/// ``parseCommandOrAppend(in:buffer:tracker:)`` accepts in addition to tagged commands
|
|
/// and `APPEND`.
|
|
private enum CommandLineContext {
|
|
/// Ordinary command parsing (corresponds to `Mode.lines`). Only tagged commands and
|
|
/// `APPEND` are valid; a bare CRLF or an unsolicited base64 line is a parse error.
|
|
case standard
|
|
/// An `AUTHENTICATE` exchange is in progress (corresponds to
|
|
/// `Mode.expectingAuthenticationResponse`), so a base64 challenge response is additionally
|
|
/// accepted — e.g. for multi-round SASL mechanisms such as `GSSAPI`.
|
|
case authenticating
|
|
}
|
|
|
|
let parser: GrammarParser
|
|
|
|
/// The maximum number of bytes that can be buffered at any time.
|
|
///
|
|
/// When the parser accumulates more than this limit, an error is thrown.
|
|
/// Serves as DoS protection against malicious or malformed input.
|
|
/// Defaults to ``IMAPDefaults/lineLengthLimit`` (8192 bytes).
|
|
public let bufferLimit: Int
|
|
|
|
/// The maximum size of a single literal (data between `{size}` markers).
|
|
///
|
|
/// Serves as DoS protection against excessively large literal data.
|
|
/// Defaults to ``IMAPDefaults/literalSizeLimit`` (4096 bytes).
|
|
public var literalSizeLimit: Int { parser.literalSizeLimit }
|
|
private(set) var mode: Mode = .lines
|
|
private var synchronisingLiteralParser = SynchronizingLiteralParser()
|
|
|
|
/// Creates a new `CommandParser` with configurable buffer limits.
|
|
///
|
|
/// The buffer limits serve as DoS protection, preventing malicious or malformed input
|
|
/// from consuming excessive memory or processing time.
|
|
///
|
|
/// - Parameters:
|
|
/// - bufferLimit: The maximum number of bytes that can be buffered at any time.
|
|
/// If the parser accumulates more than this, an error is thrown. Defaults to
|
|
/// ``IMAPDefaults/lineLengthLimit`` (8192 bytes).
|
|
/// - literalSizeLimit: The maximum size of a single literal (data between `{size}` markers).
|
|
/// Defaults to ``IMAPDefaults/literalSizeLimit`` (4096 bytes).
|
|
///
|
|
/// - Throws: Errors during parsing if limits are exceeded or parsing fails.
|
|
///
|
|
/// - SeeAlso: ``parseCommandStream(buffer:)``
|
|
public init(bufferLimit: Int = IMAPDefaults.lineLengthLimit, literalSizeLimit: Int = IMAPDefaults.literalSizeLimit)
|
|
{
|
|
self.bufferLimit = bufferLimit
|
|
self.parser = GrammarParser(literalSizeLimit: literalSizeLimit)
|
|
}
|
|
|
|
/// Parses a given `ByteBuffer` into command stream parts.
|
|
///
|
|
/// Incrementally consumes bytes from the buffer and returns parsed command parts.
|
|
/// The parser maintains state across calls, so a command may arrive in multiple
|
|
/// reads. The input must be correctly framed, for example by `FramingParser`: a CRLF
|
|
/// split across reads is not supported.
|
|
///
|
|
/// Returns `nil` when more data is needed. Throws an error if:
|
|
/// - The buffer exceeds ``bufferLimit``
|
|
/// - A literal exceeds ``literalSizeLimit``
|
|
/// - The input violates IMAP command syntax
|
|
/// - UTF-8 validation fails
|
|
///
|
|
/// - Parameter buffer: A `ByteBuffer` with incoming data. The parser consumes
|
|
/// bytes from the front as it parses them.
|
|
///
|
|
/// - Returns: A ``SynchronizedCommand`` if a complete element is parsed, or `nil`
|
|
/// if more data is needed.
|
|
///
|
|
/// - Throws: ``ParserError`` for syntax errors, ``BadCommand`` for tagged command
|
|
/// parse failures, ``TooMuchRecursion`` for overly nested structures.
|
|
///
|
|
/// - SeeAlso: ``SynchronizedCommand``, [RFC 3501 Section 5](https://datatracker.ietf.org/doc/html/rfc3501#section-5)
|
|
public mutating func parseCommandStream(buffer: inout ByteBuffer) throws -> SynchronizedCommand? {
|
|
guard buffer.readableBytes > 0 else {
|
|
return nil
|
|
}
|
|
|
|
let save = buffer
|
|
let framingResult = try self.synchronisingLiteralParser.parseContinuationsNecessary(buffer)
|
|
var actuallyVisible = ParseBuffer(
|
|
buffer.getSlice(at: buffer.readerIndex, length: framingResult.maximumValidBytes)!
|
|
)
|
|
|
|
func parseCommand() throws -> CommandStreamPart? {
|
|
do {
|
|
guard
|
|
let command = try self.parseCommandStream0(
|
|
buffer: &actuallyVisible,
|
|
tracker: .makeNewDefault
|
|
)
|
|
else {
|
|
assert(
|
|
framingResult.maximumValidBytes == actuallyVisible.readableBytes,
|
|
"parser consumed bytes on nil: readableBytes before parse: \(framingResult.maximumValidBytes), buffer: \(actuallyVisible)"
|
|
)
|
|
return nil
|
|
}
|
|
// We need to discard the bytes we consumed from the real buffer.
|
|
let consumedBytes = framingResult.maximumValidBytes - actuallyVisible.readableBytes
|
|
buffer.moveReaderIndex(forwardBy: consumedBytes)
|
|
|
|
assert(
|
|
buffer.writerIndex == save.writerIndex,
|
|
"the writer index of the buffer moved whilst parsing which is not supported: \(buffer), \(save)"
|
|
)
|
|
assert(
|
|
consumedBytes >= 0,
|
|
"allegedly, we consumed a negative amount of bytes: \(consumedBytes)"
|
|
)
|
|
self.synchronisingLiteralParser.consumed(consumedBytes)
|
|
assert(
|
|
consumedBytes <= framingResult.maximumValidBytes,
|
|
"We consumed \(consumedBytes) which is more than the framing parser thought are maximally "
|
|
+ "valid: \(framingResult), \(self.synchronisingLiteralParser)"
|
|
)
|
|
return command
|
|
} catch is IncompleteMessage {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
if let command = try parseCommand() {
|
|
return SynchronizedCommand(command, numberOfSynchronisingLiterals: framingResult.synchronizingLiteralCount)
|
|
} else if framingResult.synchronizingLiteralCount > 0 {
|
|
return SynchronizedCommand(numberOfSynchronisingLiterals: framingResult.synchronizingLiteralCount)
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
private mutating func parseCommandStream0(
|
|
buffer: inout ParseBuffer,
|
|
tracker: StackTracker
|
|
) throws -> CommandStreamPart? {
|
|
try buffer.composite(tracker: tracker) { buffer, tracker in
|
|
switch self.mode {
|
|
case .idle:
|
|
return try self.handleIdle(buffer: &buffer, tracker: tracker)
|
|
case .lines:
|
|
return try self.handleLines(buffer: &buffer, tracker: tracker)
|
|
case .expectingAuthenticationResponse:
|
|
return try self.handleAuthentication(buffer: &buffer, tracker: tracker)
|
|
case .waitingForMessage:
|
|
return try self.handleWaitingForMessage(buffer: &buffer, tracker: tracker)
|
|
case .streamingBytes(let remaining):
|
|
return try self.handleStreamingBytes(buffer: &buffer, tracker: tracker, remaining: remaining)
|
|
case .streamingEnd:
|
|
return try self.handleStreamingEnd(buffer: &buffer, tracker: tracker)
|
|
case .waitingForCatenatePart(seenPreviousPart: let seenPreviousPart):
|
|
return try self.handleCatenatePart(
|
|
expectPrecedingSpace: seenPreviousPart,
|
|
buffer: &buffer,
|
|
tracker: tracker
|
|
)
|
|
case .streamingCatenateBytes(let remaining):
|
|
return try self.handleStreamingCatenateBytes(buffer: &buffer, tracker: tracker, remaining: remaining)
|
|
case .streamingCatenateEnd:
|
|
return try self.handleStreamingCatenateEnd(buffer: &buffer, tracker: tracker)
|
|
}
|
|
}
|
|
}
|
|
|
|
private mutating func handleStreamingBytes(
|
|
buffer: inout ParseBuffer,
|
|
tracker: StackTracker,
|
|
remaining: Int
|
|
) throws -> CommandStreamPart {
|
|
assert(self.mode.isStreamingAppend)
|
|
let bytes = try buffer.extractBuffer(upTo: remaining)
|
|
|
|
assert(bytes.readableBytes <= remaining)
|
|
if bytes.readableBytes == remaining {
|
|
self.mode = .streamingEnd
|
|
} else {
|
|
self.mode = .streamingBytes(remaining - bytes.readableBytes)
|
|
}
|
|
return .append(.messageBytes(bytes))
|
|
}
|
|
|
|
private mutating func handleLines(buffer: inout ParseBuffer, tracker: StackTracker) throws -> CommandStreamPart {
|
|
// In `.lines` mode there is no `AUTHENTICATE` in progress, so a bare CRLF / unsolicited
|
|
// base64 line must be rejected rather than misclassified as a continuation response.
|
|
try self.parseCommandOrAppend(in: .standard, buffer: &buffer, tracker: tracker)
|
|
}
|
|
|
|
/// Parses while an `AUTHENTICATE` exchange is in progress.
|
|
///
|
|
/// In addition to ordinary commands and `APPEND`, the client may send one or more base64
|
|
/// challenge responses (multi-round SASL, e.g. `GSSAPI`). The parser leaves this mode only
|
|
/// once an ordinary command or `APPEND` is parsed, since it never sees the server's tagged
|
|
/// completion response.
|
|
private mutating func handleAuthentication(
|
|
buffer: inout ParseBuffer,
|
|
tracker: StackTracker
|
|
) throws -> CommandStreamPart {
|
|
try self.parseCommandOrAppend(in: .authenticating, buffer: &buffer, tracker: tracker)
|
|
}
|
|
|
|
/// Shared implementation for `.lines` and `.expectingAuthenticationResponse` modes.
|
|
///
|
|
/// Both contexts accept a tagged command or an `APPEND`; only `.authenticating` additionally
|
|
/// accepts a base64 continuation response. `parseCommand` is tried first and a tagged command
|
|
/// requires `tag SP …` while a base64 line contains no space, so there is no ambiguity between
|
|
/// the two.
|
|
private mutating func parseCommandOrAppend(
|
|
in context: CommandLineContext,
|
|
buffer: inout ParseBuffer,
|
|
tracker: StackTracker
|
|
) throws -> CommandStreamPart {
|
|
func parseCommand(buffer: inout ParseBuffer, tracker: StackTracker) throws -> CommandStreamPart {
|
|
let command = try self.parser.parseTaggedCommand(buffer: &buffer, tracker: tracker)
|
|
try buffer.matchNewline()
|
|
switch command.command {
|
|
case .idleStart:
|
|
self.mode = .idle
|
|
case .authenticate:
|
|
// Expect the client's base64 challenge response(s) until authentication completes.
|
|
self.mode = .expectingAuthenticationResponse
|
|
default:
|
|
// Any other command exits a preceding `AUTHENTICATE` exchange. This is a harmless
|
|
// no-op when we are already in `.lines`.
|
|
self.mode = .lines
|
|
}
|
|
return .tagged(command)
|
|
}
|
|
|
|
func parseAppend(buffer: inout ParseBuffer, tracker: StackTracker) throws -> CommandStreamPart {
|
|
let appendCommand = try self.parser.parseAppend(buffer: &buffer, tracker: tracker)
|
|
self.mode = .waitingForMessage
|
|
return appendCommand
|
|
}
|
|
|
|
func parseAuthenticationChallengeResponse(
|
|
buffer: inout ParseBuffer,
|
|
tracker: StackTracker
|
|
) throws -> CommandStreamPart {
|
|
let authenticationChallengeResponse = try self.parser.parseBase64(buffer: &buffer, tracker: tracker)
|
|
try buffer.matchNewline()
|
|
// Stay in `.expectingAuthenticationResponse` to support multi-round SASL exchanges.
|
|
return .continuationResponse(authenticationChallengeResponse)
|
|
}
|
|
|
|
switch context {
|
|
case .standard:
|
|
return try buffer.parseOneOf(
|
|
{ try parseCommand(buffer: &$0, tracker: $1) },
|
|
{ try parseAppend(buffer: &$0, tracker: $1) },
|
|
tracker: tracker
|
|
)
|
|
case .authenticating:
|
|
return try buffer.parseOneOf(
|
|
{ try parseCommand(buffer: &$0, tracker: $1) },
|
|
{ try parseAppend(buffer: &$0, tracker: $1) },
|
|
{ try parseAuthenticationChallengeResponse(buffer: &$0, tracker: $1) },
|
|
tracker: tracker
|
|
)
|
|
}
|
|
}
|
|
|
|
private mutating func handleWaitingForMessage(
|
|
buffer: inout ParseBuffer,
|
|
tracker: StackTracker
|
|
) throws -> CommandStreamPart {
|
|
do {
|
|
let command = try self.parser.parseAppendOrCatenateMessage(buffer: &buffer, tracker: tracker)
|
|
|
|
switch command {
|
|
case .append(let message):
|
|
self.mode = .streamingBytes(message.data.byteCount)
|
|
return .append(.beginMessage(message: message))
|
|
case .catenate(let options):
|
|
self.mode = .waitingForCatenatePart(seenPreviousPart: false)
|
|
return .append(.beginCatenate(options: options))
|
|
}
|
|
} catch is ParserError {
|
|
let save = buffer
|
|
do {
|
|
try buffer.matchNewline()
|
|
self.mode = .lines
|
|
return .append(.finish)
|
|
} catch {
|
|
buffer = save
|
|
throw error
|
|
}
|
|
}
|
|
}
|
|
|
|
private mutating func handleStreamingEnd(
|
|
buffer: inout ParseBuffer,
|
|
tracker: StackTracker
|
|
) throws -> CommandStreamPart {
|
|
self.mode = .waitingForMessage
|
|
return .append(.endMessage)
|
|
}
|
|
|
|
private mutating func handleIdle(buffer: inout ParseBuffer, tracker: StackTracker) throws -> CommandStreamPart {
|
|
try self.parser.parseIdleDone(buffer: &buffer, tracker: tracker)
|
|
self.mode = .lines
|
|
return .idleDone
|
|
}
|
|
|
|
private mutating func handleCatenatePart(
|
|
expectPrecedingSpace: Bool,
|
|
buffer: inout ParseBuffer,
|
|
tracker: StackTracker
|
|
) throws -> CommandStreamPart {
|
|
let result = try self.parser.parseCatenatePart(
|
|
expectPrecedingSpace: expectPrecedingSpace,
|
|
buffer: &buffer,
|
|
tracker: tracker
|
|
)
|
|
switch result {
|
|
case .url(let url):
|
|
self.mode = .waitingForCatenatePart(seenPreviousPart: true)
|
|
return .append(.catenateURL(url))
|
|
case .text(let length):
|
|
self.mode = .streamingCatenateBytes(length)
|
|
return .append(.catenateData(.begin(size: length)))
|
|
case .end:
|
|
self.mode = .waitingForMessage
|
|
return .append(.endCatenate)
|
|
}
|
|
}
|
|
|
|
private mutating func handleStreamingCatenateBytes(
|
|
buffer: inout ParseBuffer,
|
|
tracker: StackTracker,
|
|
remaining: Int
|
|
) throws -> CommandStreamPart {
|
|
let bytes = try buffer.extractBuffer(upTo: remaining)
|
|
|
|
assert(bytes.readableBytes <= remaining)
|
|
if bytes.readableBytes == remaining {
|
|
self.mode = .streamingCatenateEnd
|
|
} else {
|
|
self.mode = .streamingCatenateBytes(remaining - bytes.readableBytes)
|
|
}
|
|
|
|
return .append(.catenateData(.bytes(bytes)))
|
|
}
|
|
|
|
private mutating func handleStreamingCatenateEnd(
|
|
buffer: inout ParseBuffer,
|
|
tracker: StackTracker
|
|
) throws -> CommandStreamPart {
|
|
self.mode = .waitingForCatenatePart(seenPreviousPart: true)
|
|
return .append(.catenateData(.end))
|
|
}
|
|
}
|