Commit Graph
18 Commits
Author SHA1 Message Date
Daniel Eggert 0156608080 Drop ClientStateMachine's unused allocator; keep drain check in release
The allocator is no longer read since commands encode into an
IMAPOutputBuffer. The drained-context check was a precondition before
the sink change made it an assert.
2026-11-24 09:48:19 +09:00
Daniel Eggert 3cd39758d4 Use [UInt8] for small model fields
Small fields (mailbox names, atoms, quoted strings, envelope fields,
base64, URLs, the authentication challenge, catenateURL, ...) become
[UInt8]. The four raw-payload cases stay ByteBuffer until "Make payload
cases IMAPBuffer".

The grammar's string productions return [UInt8]. The parser still runs
on ParseBuffer, so its cursor methods copy out of the ByteBuffer for now.

Review focus: the model files' encoders and ModifiedUTF7 on arrays.

Updates IMAPTool and the IMAPCommands catenate-URL wrapper.

Public API breaks:
- ~38 public declarations ByteBuffer -> [UInt8].
- ModifiedUTF7.EncodingRoundtripError.buffer -> .bytes.
- Response.authenticationChallenge and ContinuationRequest.data are
  [UInt8]; an empty challenge is [].

Internal: writeBufferAsBase64 -> writeBytesAsBase64; the ByteBuffer
writeIMAPString overload is gone.
2026-11-24 09:47:33 +09:00
Daniel Eggert cbbce83ab6 Encode into an EncoderOutputBuffer sink
EncodeBuffer appends to `any EncoderOutputBuffer` (IMAPOutputBuffer by
default) instead of holding a ByteBuffer. Chunks come out as
IMAPBufferList; the handlers write one buffer per payload via
makeOutboundBuffers(). CommandEncoder is deleted: it kept only the first
chunk of a synchronizing literal and had no users but its own test.
nextChunk() caps a chunk at 64 regions, coalescing the tail, whatever
the sink returned, so no sink (a caller's own included) has to.

EncodeBuffer stages writes under 256 bytes inline and appends them to
the sink in one call: one existential call per ~256 bytes, not per
write. It flushes before every hand-out and before any direct sink
append (writeBytes(IMAPBuffer), larger writes), so payloads still reach
the sink by reference and in order. Conformers see batched appends;
byteCount may lag until a hand-out (documented on EncoderOutputBuffer).
Per-write cost therefore no longer separates the two sinks, so the
docs choosing IMAPOutputBuffer over ByteBufferOutput (ByteBufferOutput's,
EncoderOutputBuffer's, IMAPOutputBuffer's, the handlers') rest on the
hand-out instead.

Review focus: totalWritten / handedOut and absolute stop points in
nextChunk() (an off-by-one deadlocks the protocol, see
EncodeBufferSinkTests), the staging flush points, and
IMAPClientHandler.writeChunk's promise handling across several writes.

The CLI example's round-trip handler compares all chunks via the public
nextChunk() (it compared only the first) and drops its SPI import.

Public API breaks:
- CommandEncodeBuffer / ResponseEncodeBuffer: `init(buffer:…)` ->
  `init(sink: = IMAPOutputBuffer(), …)`; no longer Sendable.
- EncodeBuffer.Chunk.bytes and ResponseEncodeBuffer.readBytes() are
  IMAPBufferList.
- EncodeBuffer.writeBytes takes a Collection; writeBytes(IMAPBuffer) added;
  writeBuffer(inout ByteBuffer) removed.
- EncodeBuffer (SPI) is no longer Sendable; == / hash compare the pending
  bytes.

Public API addition: CommandEncodeBuffer.nextChunk() -> Chunk?, with
Chunk { bytes, nextStep } and NextStep { proceed,
awaitContinuationRequest }, so a client with its own transport needs no
SPI. nextStep awaits whenever a chunk ends at a synchronizing literal
header, also at the last byte written (APPEND .beginMessage,
.catenateData(.begin)), where the SPI Chunk.waitForContinuation says no
wait. ClientStateMachine uses it and imports no NIOIMAPCore SPI.

Behavior change: an APPEND part that ends in a literal the APPEND flow
doesn't expect (zero-length, e.g. an empty mailbox with quoted strings
off) waits for `+` before the next part instead of running ahead; its
write promise completes after the `+`.

Examples/PerformanceTester (IMAPDispatchClient) does not build from here
until "Measure IMAPDispatchClient against either library".

Temporary: EncodeBuffer+ByteBufferShim.swift keeps an internal
writeBuffer(inout ByteBuffer) for the model types that still hold one.
2026-11-24 09:47:33 +09:00
Daniel Eggert a102446eed Send APPEND arguments that need a literal
ClientStateMachine sent the first chunk of each APPEND part and dropped
the rest. A part holding a synchronizing literal before its end lost
everything after the literal header and didn't wait for `+` (RFC 3501
§4.3, §7.5): a mailbox like "å" became `A1 APPEND {2}\r\n {5}\r\n`; a
CATENATE URL over 70 bytes became `URL {90}\r\n)`; the next `+` threw
UnexpectedContinuationRequest. Also on main.

New state appendingLiteral holds the part's remaining chunks until `+`.
A tagged response while waiting fails the part's promise with the
UnexpectedResponse, as for other literals; channel close fails it.

Behavior change: such parts are sent whole, after `+`; their write
promise completes once the last chunk is written.

If the APPEND completes while a part waits for `+` (unreachable today:
`.finish` has no literal), throw UnexpectedResponse rather than rely on
an assert compiled out in release.
2026-11-20 12:49:16 +01:00
Daniel Eggert 4606da62d2 Validate response text, command tags and namespace delimiters (#866)
* Reject invalid response text when writing

`.no(.init(text: "No mailbox x\r\n* BYE pwned"))` was written verbatim,
injecting an untagged response; likewise tagged, BYE, PREAUTH and
continuation responses.

RFC 9051: `text = 1*(TEXT-CHAR / UTF8-2 / UTF8-3 / UTF8-4)`. `writeText`
now asserts no NUL, CR or LF. Empty stays valid. The parser now accepts
UTF-8 text.

* Add Command.Tag for command and response tags

`TaggedCommand(tag: "A1 NOOP\r\nA2 DELETE INBOX\r\nA3", command: .noop)`
was written verbatim, injecting a command; likewise `APPEND` start.
`TaggedResponse(tag: "* BYE x\r\nA1", …)` injected a response.

RFC 3501: `tag = 1*<any ASTRING-CHAR except "+">`. New `Command.Tag`
replaces the `String` in `TaggedCommand`, `TaggedResponse`, `Response`,
`CommandStreamPart`, `AppendCommand`, `BadCommand` and NIOIMAP's state
machine errors; `init?(_:)` validates, literals trap. The parser already
enforces the production. IMAPCommands converts its numeric tags.

* Validate and escape namespace delimiters

`NamespaceDescription(string: "x", char: "\r\n", …)` wrote a raw CRLF
inside `"…"`, injecting a response. `"\""` encoded as `"""`, and `"\\"`
as `"\"` (unterminated); non-ASCII was accepted.

RFC 2342: `DQUOTE QUOTED-CHAR DQUOTE / nil`. `init(string:delimiter:
responseExtensions:)` (was `char:`) throws `InvalidDelimiterError` for
non-ASCII, CR, LF, NUL; the delimiter is stored as a byte, read-only.
Quoted-specials are escaped on write and parsed when escaped.

* Gate a capturing exit test on Swift 6.3
2026-11-04 17:41:52 +00:00
AnthonyandDaniel Eggert d456d32908 Accept the responses a server may send during IDLE (#855)
Co-authored-by: Daniel Eggert <deggert@apple.com>
2026-10-13 17:08:26 +02:00
Daniel Eggert 983e0f1aff InvalidCommandForState error may leak PII (#828) 2026-06-02 16:37:19 +01:00
Daniel Eggert abfc170ff1 Only parse continuation responses while an AUTHENTICATE is in progress (#827) 2026-06-01 14:13:22 -04:00
Daniel Eggert efc0bfe244 Allow receiving untagged responses while appending (#799) 2025-06-11 13:52:48 -04:00
Daniel Eggert 1b27cae1b4 Fix client handler encoding options (#786) 2025-04-11 17:33:25 +02:00
Daniel Eggert 851c3f89b6 Workaround for IMAPClientHandler and APPEND (#785) 2025-04-11 17:01:26 +02:00
Franz Busch 2cd1c5582a [CI] Adopt GitHub Actions (#775)
* [CI] Adopt GitHub Actions

# Motivation

We want to adopt GitHub actions in all of our Swift repositories to replace our current Jenkins CI.

# Modification

This PR adopts the reusable workflows from NIO and the swiftlang organization to ensure soundness and test coverage. Additionally, this PR enables a sematic label check and adds a `release.yml` to make releasing this package easy.

# Result

Modern CI and release flow.
2024-10-30 13:24:35 +00:00
David Evans 8ac6696b3c Implement encoding logging mode for redaction (#678)
Resolves #662

Command/Response Encoder can be configured using loggingMode. If turned on then user-sensitive strings won't be encoding, but any metadata will.

For example, 1 LOGIN username password becomes 1 LOGIN "" "", thereby hiding the user's information.
2022-01-26 15:50:12 -08:00
David Evans 59a57ee70b New client state machine (#610)
The client state machine has now been fully rewritten, and encapsulates the miniature state machines implemented in previous PRs.

I've extracted the state machine from IMAPClientHandler and moved it into ClientStateMachine, hence all the code deletion.

The state machine receives a command, response, or continuation request from the IMAPClientHandler and returns an array of Chunk/EventLoopPromise pairs that the client handler should then write to the network.

Also we didn't previously queue Append commands like we did for others, however it's now become apparent that all commands types should be queued, so we do that now.

A lot of tests have been added to make sure everything works.

Note that a lot of sendCommand tests have been deleted as we now precondition on user errors instead of throwing.
2021-09-10 13:45:11 +01:00
David Evans 79657fd985 Track command tags and restrict potential concurrent commands. (#596)
In most cases in IMAP it's possible to allow multiple commands to run concurrently. However, in some cases this would lead to undefined behaviour.

In particular, when appending, append is the only command that can be sent/active, as for authenticating, and obviously IDLE.

This PR implements that by tracking the outgoing tags, and the incoming tagged responses.
2021-07-30 11:04:15 +01:00
David Evans 9484279fe6 Add Append support to new client state machine (#595)
Identical pattern to that used for IDLE and AUTHENTICATE. The main ClientStateMachine detects the append command being sent, and switches state to contain a sub-machine that is dedicated to validating the lifecycle of an append command.

We support "standard" message appends, as well as catenation, and continuation requests for both.
2021-07-28 17:18:53 +01:00
David Evans d49bbc1968 New state machine authentication flow (#587)
Add support for authentication to the new client state machine, with a typical workflow test, and a test to show that attempting to send another command while authenticating will result in an error.
2021-07-20 13:30:40 +01:00
David Evans d7db35c768 New state machine with boilerplate for IDLE command (#586)
NOTE: The many defaults used when switching over things is just because this is an example. If we're happy with how this looks, I'll remove them and handle properly.

This is a basic demonstrative implementation of the new client state machine that shows how the IDLE command is supported.

For an idle state to be established, the client needs to send the idleStart command, and the server needs to respond with a continuationRequest, at which point the state is idle.
2021-07-19 14:58:44 +01:00