Files
swift-nio-imap/Sources/NIOIMAPCore/ByteBuffer+WriteLiteral.swift
Daniel Eggert ded4ff7245 Validate atom-shaped types at construction (#864)
* Reject invalid URLAUTH mechanisms

`.resetKey(mailbox: .inbox, mechanisms: [.init("X\r\nA2 DELETE INBOX")])`
was written verbatim, injecting a command into RESETKEY / GENURLAUTH.

RFC 4467: `mechanism = "INTERNAL" / 1*(ALPHA / DIGIT / "-" / ".")`.
`init(_:)` becomes `init?(_:)`; literals trap on invalid input. The
parser already enforces the production.

* Reject invalid mailbox attributes

`MailboxInfo.Attribute("\\X)\r\n* BYE")` was written verbatim, injecting
an untagged response into LIST. It also feeds CREATE … USE via
`UseAttribute(_:)`.

RFC 3501: `mbx-list-flag` is `"\" atom` in every branch. `init(_:)`
becomes `init?(_:)`; literals trap on invalid input. Constants become
`static let` literals; storage is `let`. Fix the `String.init` doc,
which claimed lowercase storage.

* Reject invalid use attributes

`UseAttribute("\\All))\r\nA2 DELETE INBOX\r\nA3 NOOP ((")` was written
verbatim, injecting a command into CREATE … (USE (…)). It also feeds
`GmailLabel(useAttribute:)`.

RFC 6154: `use-attr-ext = "\" atom`. `init(_:)` becomes `init?(_:)`;
literals trap on invalid input. `init(_: MailboxInfo.Attribute)` stays
non-failable: same production. Fix docs that claimed lowercase storage.

* Reject invalid attribute flags

`AttributeFlag("x\" all 1\r\nA2 DELETE INBOX\r\nA3 NOOP \"")` was
written verbatim inside SEARCH MODSEQ "/flags/…", injecting a command.

RFC 7162: `attr-flag = "\\" atom / atom`, where `"\\"` is two literal
backslashes (the stored form is already escaped). `init(_:)` becomes
`init?(_:)`, validating after lowercasing; literals trap on invalid
input. Fix docs that claimed casing is preserved.

* Add FilterName for SEARCH FILTER

`.filter("x\r\nA2 DELETE INBOX")` was written verbatim, injecting a
command into SEARCH.

RFC 5466: `filter-name = 1*<any ATOM-CHAR except "/">`. New `FilterName`
type replaces the `String` payload of `SearchKey.filter`; `init?(_:)`
validates, literals trap on invalid input.

* Reject invalid compression kinds

`.compress(.init("DEFLATE\r\nA2 DELETE INBOX"))` was written verbatim,
injecting a command after COMPRESS.

RFC 4978: `algorithm = "DEFLATE"`, an atom. `init(_:)` becomes
`init?(_:)`, validating after uppercasing; literals trap on invalid
input. Add `String.init(_:)`.

* Reject invalid capabilities

`Capability("X\r\nA2 DELETE INBOX")` was written verbatim, injecting a
command into ENABLE, or (`"X\r\n* OK [ALERT] hi"`) a response into
CAPABILITY / ENABLED. Same for the kinds a capability is built from,
e.g. `.context(.init("X\r\n…"))`.

RFC 3501: `capability = ("AUTH=" auth-type) / atom`. `init(_:)` becomes
`init?(_:)` for `Capability` and each kind (kinds validate after
uppercasing); literals trap on invalid input. Storage is `let`. Add
`String.init(_:)` for the kinds.

* Add validated LIST option tag types

`.standard("X)\r\nA2 DELETE INBOX\r\nA3 LIST (")` was written verbatim,
injecting a command into LIST select/return options. Same for
`.vendor(KeyValue<String, String>)`.

RFC 5258: `option-standard-tag = atom`, `option-vendor-tag =
vendor-token "-" atom`. New `OptionExtensionKind.Standard` and
`.Vendor` replace the payloads; `init?(_:)` validates, literals trap.
`Vendor` stores `ACME-SORT` and derives `token` / `name`.

* Add CharacterSetName for SEARCH, SORT, and BADCHARSET

`.sort(…, charset: "UTF-8 ALL\r\nA2 DELETE INBOX\r\nA3 SEARCH", …)` was
written verbatim, injecting a command into SORT / SEARCH / ESEARCH.
`.badCharset(["a)] x\r\n* BYE"])` injected a response. Quoted names
also didn't round-trip: `"a b"` parsed, then encoded bare.

RFC 3501: `charset = atom / quoted`. New `CharacterSetName` replaces
`String`; valid = non-empty `TEXT-CHAR`. Written as an atom where it is
one (`CHARSET UTF-8` unchanged), quoted otherwise, never a literal. The
parser rejects quoted names it couldn't write back.

* Assert keyword validity when writing a flag keyword

`writeFlagKeyword` wrote verbatim with no check. `writeAtom` would be
wrong: Gmail keywords contain `]`, which no atom does. Assert the
keyword's own production instead; test that a `]` keyword encodes.

* Hoist a #require the compiler flagged as redundant
2026-11-04 17:41:52 +00:00

291 lines
13 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//===----------------------------------------------------------------------===//
//
// 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
import struct OrderedCollections.OrderedDictionary
extension EncodeBuffer {
/// Writes an IMAP `string` type as defined by the grammar in RFC 3501.
/// The function will decide to use either `quoted` or `literal` syntax based
/// upon what bytes `string` contains, and what encoding types are supported
/// by the encoding options on `self`.
/// - parameters:
/// - string: The string to write.
/// - returns: The number of bytes written.
@discardableResult mutating func writeIMAPString(_ string: String) -> Int {
self.writeIMAPString(string.utf8)
}
/// Writes an IMAP `string` type as defined by the grammar in RFC 3501.
/// The function will decide to use either `quoted` or `literal` syntax based
/// upon what bytes `buffer` contains, and what encoding types are supported.
/// - parameters:
/// - buffer: The buffer to write.
/// - returns: The number of bytes written.
@discardableResult mutating func writeIMAPString(_ buffer: ByteBuffer) -> Int {
self.writeIMAPString(buffer.readableBytesView)
}
/// Writes an IMAP `string` type as defined by the grammar in RFC 3501.
/// The function will decide to use either `quoted` or `literal` syntax based
/// upon what bytes `buffer` contains, and what encoding types are supported.
/// - parameters:
/// - buffer: The buffer to write.
/// - returns: The number of bytes written.
@discardableResult mutating func writeIMAPString<T: Collection>(_ bytes: T) -> Int where T.Element == UInt8 {
guard !self.loggingMode else {
return self.writeIMAPStringLoggingMode(bytes)
}
switch stringEncoding(for: bytes) {
case .quotedString:
return writeQuotedIMAPString(bytes)
case .serverLiteral:
return writeString("{\(bytes.count)}\r\n") + writeBytes(bytes)
case .clientSynchronizingLiteral:
return writeString("{\(bytes.count)}\r\n") + markStopPoint() + writeBytes(bytes)
case .clientNonSynchronizingLiteral:
return writeString("{\(bytes.count)+}\r\n") + writeBytes(bytes)
}
}
/// Writes `bytes` as `quoted`, escaping `\` and `"`.
///
/// - Precondition: Every byte is a `TEXT-CHAR`; no check is made.
mutating func writeQuotedIMAPString<T: Collection>(_ bytes: T) -> Int where T.Element == UInt8 {
guard !loggingMode else {
return self.buffer.writeString("[\(Array(bytes).count) bytes]")
}
var c = writeString(#"""#)
for byte in bytes {
switch byte {
case 0x5c:
c += self.buffer.writeBytes([0x5c, 0x5c])
case 0x22:
c += self.buffer.writeBytes([0x5c, 0x22])
default:
c += self.buffer.writeBytes(CollectionOfOne(byte))
}
}
c += writeString(#"""#)
return c
}
private mutating func writeIMAPStringLoggingMode<T: Collection>(_ bytes: T) -> Int where T.Element == UInt8 {
switch stringEncoding(for: bytes) {
case .quotedString:
return writeString(#""∅""#)
case .serverLiteral:
return writeString("{\(bytes.count)}\r\n∅")
case .clientSynchronizingLiteral:
return writeString("{\(bytes.count)}\r\n") + markStopPoint() + writeString("∅")
case .clientNonSynchronizingLiteral:
return writeString("{\(bytes.count)+}\r\n∅")
}
}
fileprivate enum StringEncoding {
/// `"foo bar"`
case quotedString
/// `{7}CRLFfoo bar` (from server to client)
case serverLiteral
/// `{7}CRLF` + `foo bar`
case clientSynchronizingLiteral
/// `{7+}CRLFfoo bar`
case clientNonSynchronizingLiteral
}
private func stringEncoding<T: Collection>(for bytes: T) -> StringEncoding where T.Element == UInt8 {
switch mode {
case .client(options: let options):
if options.useQuotedString, shouldUseQuotedString(for: bytes) {
return .quotedString
} else if options.useNonSynchronizingLiteralPlus {
return .clientNonSynchronizingLiteral
} else if options.useNonSynchronizingLiteralMinus, bytes.count <= 4096 {
return .clientNonSynchronizingLiteral
} else {
return .clientSynchronizingLiteral
}
case .server(_, options: let options):
guard options.useQuotedString, shouldUseQuotedString(for: bytes) else {
return .serverLiteral
}
return .quotedString
}
}
private func shouldUseQuotedString<T: Collection>(for bytes: T) -> Bool where T.Element == UInt8 {
// If more than 70 bytes, always use a literal:
guard bytes.count <= 70 else { return false }
// We’ll allow anything ASCII that’s not a control characters.
// But `\` and `"` will need quoting. If there are too many of those,
// fall back to using a literal. We also don't allow non-ASCII
// UTF8, because the test would be very convoluted (we only
// see bytes here).
var escapeCount = 0
return bytes.allSatisfy {
guard 0x20 <= $0 && $0 <= 0x7e else { return false }
guard $0 != 0x5c && $0 != 0x22 else {
escapeCount += 1
return escapeCount < 6
}
return true
}
}
/// Encodes the given bytes as a Base64 collection, and then writes to `self.`
/// - parameters:
/// - buffer: The `ByteBuffer` to encoded and write.
/// - returns: The number of bytes written.
@discardableResult mutating func writeBufferAsBase64(_ buffer: ByteBuffer) -> Int {
let encoded = Base64.encodeBytes(bytes: buffer.readableBytesView)
return self.writeBytes(encoded)
}
/// Writes a collection of bytes in the `literal8` syntax defined in RFC 3516.
/// Allows the `null` byte `\0` to be written.
/// - parameters:
/// - bytes: The raw bytes to write to `self`.
/// - returns: The number of bytes written.
@discardableResult mutating func writeLiteral8<T: Collection>(_ bytes: T) -> Int where T.Element == UInt8 {
let length = "~{\(bytes.count)}\r\n"
return
self.writeString(length) + self.markStopPoint() + self.writeBytes(bytes)
}
/// Writes the string `"NIL"` to self.
/// - returns: The number of bytes written, always 3.
@discardableResult mutating func writeNil() -> Int {
self.writeString("NIL")
}
/// Writes a single space to `self`
/// - returns: The number of bytes written, always 1.
@discardableResult mutating func writeSpace() -> Int {
self.writeString(" ")
}
/// Writes the given `collection` as an IMAP array to self using the given `closure` for every element in the collection.
/// - parameters:
/// - array: The elements to write to `self`.
/// - prefix: A string to write before anything else, including the parenthesis. This will only be written if `array` has 1 or more elements. Defaults to "".
/// - separator: A string to write between each element, defaults to "".
/// - suffix: A string to write after anything else, including the parenthesis. This will only be written if `array` has 1 or more elements. Defaults to "".
/// - parenthesis: Writes `(` immediately before the first element, and `)` immediately after the last. Enabled by default.
/// - writer: The closure to call for each element that writes the element.
/// - returns: The number of bytes written.
@discardableResult mutating func writeArray<C, T>(
_ collection: C,
prefix: String = "",
separator: String = " ",
suffix: String = "",
parenthesis: Bool = true,
_ writer: (T, inout EncodeBuffer) -> Int
) -> Int where C: RandomAccessCollection, C.Element == T {
// TODO: This should probably check
// collection.count != 0
// such that an empty collection gets encoded as "()".
self.write(if: collection.count > 0) {
self.writeString(prefix)
}
+ self.write(if: parenthesis) { () -> Int in
self.writeString("(")
}
+ collection.enumerated().reduce(0) { (size, row) in
let (i, element) = row
return
size + writer(element, &self)
+ self.write(if: i < collection.count - 1) { () -> Int in
self.writeString(separator)
}
}
+ self.write(if: parenthesis) { () -> Int in
self.writeString(")")
}
+ self.write(if: collection.count > 0) {
self.writeString(suffix)
}
}
/// Writes the given `OrderedDictionary<Key, Value>` as an IMAP array to self using the given `closure` for every element in the collection.
/// - parameters:
/// - values: The elements to write to `self`.
/// - prefix: A string to write before anything else, including the parenthesis. This will only be written if `array` has 1 or more elements. Defaults to "".
/// - separator: A string to write between each element, defaults to "".
/// - suffix: A string to write after anything else, including the parenthesis. This will only be written if `array` has 1 or more elements. Defaults to "".
/// - parenthesis: Writes `(` immediately before the first element, and `)` immediately after the last. Enabled by default.
/// - writer: The closure to call for each element that writes the element.
/// - returns: The number of bytes written.
@discardableResult mutating func writeOrderedDictionary<K, V>(
_ values: OrderedDictionary<K, V>,
prefix: String = "",
separator: String = " ",
suffix: String = "",
parenthesis: Bool = true,
_ writer: (KeyValue<K, V>, inout EncodeBuffer) -> Int
) -> Int {
// TODO: This should probably check
// collection.count != 0
// such that an empty collection gets encoded as "()".
self.write(if: values.count > 0) {
self.writeString(prefix)
}
+ self.write(if: parenthesis) { () -> Int in
self.writeString("(")
}
+ values.enumerated().reduce(0) { (size, row) in
let (i, element) = row
return
size + writer(.init(key: element.0, value: element.1), &self)
+ self.write(if: i < values.count - 1) { () -> Int in
self.writeString(separator)
}
}
+ self.write(if: parenthesis) { () -> Int in
self.writeString(")")
}
+ self.write(if: values.count > 0) {
self.writeString(suffix)
}
}
/// Writes to self using a closure if the given `value` is non-`nil`. This allows for chaining together writes
/// when attempting to perform composite writes and return the total number of bytes written.
/// - parameters:
/// - value: The optional field to evaluate.
/// - writer: The closure to invoke if `value` is non-`nil`. If `value` exists then it is passed as
/// the only argument to this closure.
/// - returns: The number of bytes written.
@discardableResult func writeIfExists<T>(_ value: T?, _ writer: (inout T) -> Int) -> Int {
guard var value = value else {
return 0
}
return writer(&value)
}
/// Writes to self using a closure if a condition is met. This allows for chaining together writes
/// when attempting to perform composite writes and return the total number of bytes written.
/// - parameters:
/// - condition: The condition to evaluate, if `true` then `writer` will be invoked.
/// - writer: The closure to invoke if `condition` is met.
/// - returns: The number of bytes written.
@discardableResult func write(if condition: Bool, _ writer: () -> Int) -> Int {
guard condition else {
return 0
}
return writer()
}
}