mirror of
https://github.com/apple/swift-nio-imap
synced 2026-11-27 05:04:23 +00:00
* Document UseAttribute * Document URLRumpMechanism * Document URLFetchData * Document UAuthMechanism * Document StoreModifier * Document SortData * Document SequenceMatchData * Document QResyncParameter * Document SelectParameter * Document SectionSpecifier * Document SectionSpecifier.Part * Document SectionSpecifier.Kind * Document ResponseEncodingOptions * Document ResponseEncodeBuffer * Document EncodeBuffer * Document EncodeBuffer.Chunk * Document EncodeBuffer more. * Document CommandEncodeBuffer * Document ParserError * Document ResponseParser * Document CommandParser * Document SynchronisingLiteralParser * Remove public where it isn't needed * Document write CommandStream * Document write TaggedCommand * Remove public from write functions * Document FetchAttribute * Document top-level Capability * Documents Capability subtypes * Document FullDateTime * Document FullDate * Document FullTime * Document ContinuationRequest * Document ListSelectOptions * Document ResponseOrContinuationRequest * Document Response * Document FetchResponse * Document StreamingKind * Document ResponseText * Document ResponseTextCode * Document TaggedResponse * Document TaggedResponseState * Remove docs * Document UntaggedStatus * Document ScopeOption * Document ReturnOption * Document IServer * Document InitialClientResponse * Document AttributeFlag * Document UIDValidity * Document UIDSet * Document UID * Document EncodedAuthenticationType * Document EncodedMailbox * Document EncodedSearch * Document EncodedSection * Document EncodedURLAuth * Document EncodedUser * Document ResponseCodeAppend * Document ResponsePayload * Document SequenceNumber * Document OptionValueComp * Document QuotaLimit * Document QuotaResource * Document OptionVendorTag * Document IPartial and remove IPartialOnly * Document QuotaRoot * Document ESearchResponse * Document SearchCorrelator * Document Address * Document UIDRange * Document IUID * Document SearchModificationSequence * Document SearchModificationSequenceExtension * Document SearchReturnData * Document SearchReturnDataExtension * Document SearchReturnOption * Document SearchReturnOptionExtension * Document SequenceRange * Document SequenceRangeSet * Fix compile * Document SequenceSet * Document ParameterValue * Define TaggedExtension * Document AuthIMAPURL * Document AuthIMAPURLFull * Document AuthIMAPURLRump * Document ChangedSinceModifier * Document UnchangedSinceModifier * Document CreateParameter * Document EntryValue * Document Expire * Document FetchModifier * Document FetchModificationResponse * Document IAbsolutePath * Document IAuth * Document ICommand * Document IMailboxReference * Document MetadataValue * Document IMAPURL * Document MetadataOption * Document MetadataResponse * Document RelativeIMAPURL * Document INetworkPath * Document MechanismBase64 * Document IMessageList * Document IMessageOrPartial * Document IMessagePart * Document IPathQuery * Document ISection * Document IRelativePath * Document IUAVerifier * Document IURLAuthRump * Document IURLAuthRump * Document IUserInfo * Fix missing documentation * Document CommandEncoder * Fix sanity * Update CommandDecoder.swift * PR reviews
103 lines
3.9 KiB
Swift
103 lines
3.9 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 NIO
|
|
|
|
/// To be used by a IMAP client implementation.
|
|
public final class IMAPClientHandler: ChannelDuplexHandler {
|
|
/// Should receive a raw buffer in, after any TLS.
|
|
public typealias InboundIn = ByteBuffer
|
|
|
|
/// Converts a `ByteBuffer` into a `Response` by sending data through a parser.
|
|
public typealias InboundOut = Response
|
|
|
|
/// Commands are encoding into a ByteBuffer to send to a server.
|
|
public typealias OutboundIn = CommandStream
|
|
|
|
/// After encoding the bytes may be sent further through the channel to, for example, a TLS handler.
|
|
public typealias OutboundOut = ByteBuffer
|
|
|
|
private let decoder: NIOSingleStepByteToMessageProcessor<ResponseDecoder>
|
|
private var bufferedWrites: MarkedCircularBuffer<(EncodeBuffer, EventLoopPromise<Void>?)> =
|
|
MarkedCircularBuffer(initialCapacity: 4)
|
|
|
|
public struct UnexpectedContinuationRequest: Error {}
|
|
|
|
public init() {
|
|
self.decoder = NIOSingleStepByteToMessageProcessor(ResponseDecoder(), maximumBufferSize: 1_000)
|
|
}
|
|
|
|
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
|
let data = self.unwrapInboundIn(data)
|
|
do {
|
|
try self.decoder.process(buffer: data) { response in
|
|
switch response {
|
|
case .continuationRequest:
|
|
self.writeNextChunks(context: context)
|
|
case .response(let response):
|
|
context.fireChannelRead(self.wrapInboundOut(response))
|
|
}
|
|
}
|
|
} catch {
|
|
context.fireErrorCaught(error)
|
|
}
|
|
}
|
|
|
|
private func writeNextChunks(context: ChannelHandlerContext) {
|
|
guard self.bufferedWrites.hasMark else {
|
|
// This is very odd, that's a continuation request that we didn't expect.
|
|
context.fireErrorCaught(UnexpectedContinuationRequest())
|
|
return
|
|
}
|
|
defer {
|
|
// Note, we can `flush` here because this is already flushed (or else the we wouldn't have a mark).
|
|
context.flush()
|
|
}
|
|
repeat {
|
|
let next = self.bufferedWrites[self.bufferedWrites.startIndex].0.nextChunk()
|
|
|
|
if next.waitForContinuation {
|
|
context.write(self.wrapOutboundOut(next.bytes), promise: nil)
|
|
return
|
|
} else {
|
|
let promise = self.bufferedWrites.removeFirst().1
|
|
context.write(self.wrapOutboundOut(next.bytes), promise: promise)
|
|
}
|
|
} while self.bufferedWrites.hasMark
|
|
}
|
|
|
|
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
|
|
let command = self.unwrapOutboundIn(data)
|
|
var encoder = CommandEncodeBuffer(buffer: context.channel.allocator.buffer(capacity: 1024), capabilities: [])
|
|
encoder.writeCommandStream(command)
|
|
if self.bufferedWrites.isEmpty {
|
|
let next = encoder.buffer.nextChunk()
|
|
|
|
if next.waitForContinuation {
|
|
context.write(self.wrapOutboundOut(next.bytes), promise: nil)
|
|
// fall through to append below
|
|
} else {
|
|
context.write(self.wrapOutboundOut(next.bytes), promise: promise)
|
|
return
|
|
}
|
|
}
|
|
self.bufferedWrites.append((encoder.buffer, promise))
|
|
}
|
|
|
|
public func flush(context: ChannelHandlerContext) {
|
|
self.bufferedWrites.mark()
|
|
context.flush()
|
|
}
|
|
}
|