mirror of
https://github.com/apple/swift-nio-imap
synced 2026-11-27 05:04:23 +00:00
* Validate percent-encoded IMAP URL components
`EncodedMailbox(mailbox: "x] x\r\n* BYE")` was written verbatim inside
the bare URL of `[REFERRAL …]`, injecting a response; likewise
`EncodedUser`, `EncodedAuthenticationType`, `EncodedSearch`,
`EncodedSection`.
RFC 5092: `enc-user`/`enc-auth-type = 1*achar`, `enc-mailbox`/
`enc-search`/`enc-section = 1*bchar`. Each type's public `var` and
labelled init become `init?(_:)`, literals trap, `String.init` reads.
One helper validates by character class and `pct-encoded` triplet, and
uppercases hex digits as the parser does, so values round-trip.
* Validate URLAUTH tokens
`EncodedAuthenticatedURL(data: "x\r\n* BYE")` was written verbatim at the
end of a URLAUTH URL, injecting a response.
RFC 4467: `enc-urlauth = 32*HEXDIG`. `init(data:)` and the public `var`
become `init?(_:)`; literals trap; `String.init` reads. The parser read
exactly 32 digits, so longer tokens didn't round-trip; it now reads all.
* Add IMAPServer.Host and keep IP-literal brackets
`IMAPServer(host: "h] x\r\n* BYE")` was written verbatim in the bare URL
of `[REFERRAL …]`, injecting a response. `imap://[::1]/` parsed as host
`::1` and re-encoded as `imap://::1/`. A negative port encoded as `:-1`.
RFC 3986: `host = IP-literal / IPv4address / reg-name`. New nested
`IMAPServer.Host` replaces the `String`: `init?(_:)` validates IPv6,
IPvFuture and reg-name (IPv4 is a subset), literals trap. The parser
keeps the brackets, accepts all of reg-name, and validates via `init?`;
its unreachable IPv4 branch is gone. `port` is now `UInt16?`.
* Don't parenthesize URLFETCH responses
`.urlFetch([.init(url: "url", data: nil)])` encoded as
`URLFETCH("url" NIL)`, which our parser rejects.
RFC 4467: `urlfetch-data = "URLFETCH" 1*(SP url-full SP nstring)`. Write
each pair after a space, unparenthesized. Fix fixtures that enshrined
the old output.
* Remove dead URL and date writers
`writeAuthIMAPURLRump`, `writeAuthIMAPURLFull`, `writeRelativeIMAPURL`,
`writeURLFetchType`, `writeInternetMessageDate` and
`writeListSelectBaseOptionQuoted` had no callers outside their own
encode tests, nor did the writers only they reached
(`writeAuthenticatedURL(NetworkMessagePath)`, `writeNetworkPath`,
`writeAbsoluteMessagePath`, `writeIUIDOnly`,
`writeURLMessageSectionOnly`, `writeMessagePathByteRangeOnly`). Delete
them and those tests; parse tests stay.
* Keep a section's trailing slash unless a partial follows
`imap://h/INBOX/;UID=1/;SECTION=1/` parsed with section `1`, so
`EncodedSection("1/")` didn't round-trip: the parser dropped the `/`
even when no `;PARTIAL=` followed it. Drop it only when one does.
* Reject `*` as a URL authentication type
`.type("*")` encoded as `;AUTH=*`, which parses as `.any`; `.type("*x")`
failed to parse, since `*` matched first.
RFC 5092: `iauth = ";AUTH=" ( "*" / enc-auth-type )`. `init?(_:)`
rejects `*`; the parser tries the longer `enc-auth-type` first.
136 lines
5.0 KiB
Swift
136 lines
5.0 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 percent-encoded mailbox name for use in IMAP URLs.
|
|
///
|
|
/// IMAP URLs include mailbox names as part of the URL path. When a mailbox name contains
|
|
/// characters that are not allowed in URLs (such as spaces, special characters, or non-ASCII
|
|
/// characters), the name must be percent-encoded using UTF-8 followed by hexadecimal encoding
|
|
/// (RFC 2192, RFC 3986).
|
|
///
|
|
/// Wraps a percent-encoded mailbox name for use in URL construction. The encoded
|
|
/// string contains only ASCII-safe characters and can be safely included in IMAP URL syntax.
|
|
///
|
|
/// ### Example
|
|
///
|
|
/// A mailbox named "Draft Messages" would be percent-encoded as "Draft%20Messages".
|
|
/// In an IMAP URL:
|
|
/// ```
|
|
/// imap://user@example.com/Draft%20Messages/;uid=20
|
|
/// ```
|
|
///
|
|
/// Wrapped as:
|
|
/// ```
|
|
/// NetworkMessagePath(
|
|
/// server: IMAPServer(...),
|
|
/// messagePath: MessagePath(
|
|
/// mailboxReference: MailboxUIDValidity(
|
|
/// encodedMailbox: "Draft%20Messages",
|
|
/// ...
|
|
/// ),
|
|
/// ...
|
|
/// )
|
|
/// )
|
|
/// ```
|
|
///
|
|
/// ## Related types
|
|
///
|
|
/// See ``MailboxUIDValidity`` for mailbox references with UID validity values, and
|
|
/// ``MessagePath`` for the complete message location specification in URLs.
|
|
///
|
|
/// ## Validity
|
|
///
|
|
/// The value is written to the wire verbatim, so anything that isn't an `enc-mailbox` is rejected:
|
|
///
|
|
/// - ``init(_:)`` returns `nil`. Use it for a value derived from input.
|
|
/// - ``init(stringLiteral:)`` traps. A literal is written by the programmer, so an invalid one is a
|
|
/// bug to be caught on first run rather than handled.
|
|
///
|
|
/// - SeeAlso: [RFC 2192](https://datatracker.ietf.org/doc/html/rfc2192) - IMAP URL Scheme
|
|
/// - SeeAlso: [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986) - URI Generic Syntax (percent-encoding)
|
|
public struct EncodedMailbox: Hashable, Sendable {
|
|
let stringValue: String
|
|
|
|
/// Creates a value from a percent-encoded string, if the string is a valid `enc-mailbox`.
|
|
///
|
|
/// Hex digits in `pct-encoded` triplets are uppercased, for example `%c3` becomes `%C3`.
|
|
///
|
|
/// A string literal resolves to ``init(stringLiteral:)`` instead, which traps rather than
|
|
/// returning `nil`.
|
|
///
|
|
/// - parameter stringValue: The percent-encoded string, for example `Draft%20Messages`.
|
|
/// - returns: A new value, or `nil` if `stringValue` is not a valid `enc-mailbox`.
|
|
public init?(_ stringValue: String) {
|
|
guard let normalized = Self.normalized(stringValue) else { return nil }
|
|
self.stringValue = normalized
|
|
}
|
|
|
|
init(unchecked stringValue: String) {
|
|
assert(Self.normalized(stringValue) == stringValue)
|
|
self.stringValue = stringValue
|
|
}
|
|
|
|
/// The given string with uppercased `pct-encoded` hex digits, if it is an `enc-mailbox`
|
|
/// ([RFC 5092 Section 11](https://datatracker.ietf.org/doc/html/rfc5092#section-11)):
|
|
/// ```
|
|
/// enc-mailbox = 1*bchar
|
|
/// ```
|
|
/// See ``URLCharacterClass/bchar``.
|
|
static func normalized(_ string: String) -> String? {
|
|
string.validatedAndNormalizedURLComponent(.bchar)
|
|
}
|
|
}
|
|
|
|
extension String {
|
|
/// Creates a `String` from an ``EncodedMailbox``, still percent-encoded.
|
|
///
|
|
/// - parameter other: The value to convert.
|
|
public init(_ other: EncodedMailbox) {
|
|
self = other.stringValue
|
|
}
|
|
}
|
|
|
|
extension EncodedMailbox: ExpressibleByStringLiteral {
|
|
/// Creates a value from a percent-encoded string literal.
|
|
///
|
|
/// A literal is written by the programmer, so an invalid one is a bug to be caught on first
|
|
/// run rather than handled. Use ``init(_:)`` for anything else.
|
|
///
|
|
/// - parameter value: The string literal.
|
|
/// - Precondition: `value` is a valid `enc-mailbox`; this traps if it isn't.
|
|
public init(stringLiteral value: String) {
|
|
guard let normalized = Self.normalized(value) else {
|
|
preconditionFailure("Invalid encoded mailbox: \(String(reflecting: value))")
|
|
}
|
|
self.init(unchecked: normalized)
|
|
}
|
|
}
|
|
|
|
extension EncodedMailbox {
|
|
/// This value without its trailing `/`, which the URL grammar claims for what follows, e.g.
|
|
/// `INBOX/` → `INBOX`; `nil` if there is no trailing `/` or nothing would remain.
|
|
func removingTrailingSlash() -> Self? {
|
|
guard self.stringValue.utf8.count > 1, self.stringValue.utf8.last == UInt8(ascii: "/") else { return nil }
|
|
return Self(unchecked: String(self.stringValue.dropLast()))
|
|
}
|
|
}
|
|
|
|
extension EncodeBuffer {
|
|
@discardableResult mutating func writeEncodedMailbox(_ type: EncodedMailbox) -> Int {
|
|
self.writeString(type.stringValue)
|
|
}
|
|
}
|