File: HTTPTypedPipelineSetup.swift

package info (click to toggle)
swiftlang 6.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,532 kB
  • sloc: cpp: 9,901,743; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (250 lines) | stat: -rw-r--r-- 10,862 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2023 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
//
//===----------------------------------------------------------------------===//
#if !canImport(Darwin) || swift(>=5.10)
import NIOCore

// MARK: - Server pipeline configuration

/// Configuration for an upgradable HTTP pipeline.
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
public struct NIOUpgradableHTTPServerPipelineConfiguration<UpgradeResult: Sendable> {
    /// Whether to provide assistance handling HTTP clients that pipeline
    /// their requests. Defaults to `true`. If `false`, users will need to handle clients that pipeline themselves.
    public var enablePipelining = true

    /// Whether to provide assistance handling protocol errors (e.g. failure to parse the HTTP
    /// request) by sending 400 errors. Defaults to `true`.
    public var enableErrorHandling = true

    /// Whether to validate outbound response headers to confirm that they are
    /// spec compliant. Defaults to `true`.
    public var enableResponseHeaderValidation = true

    /// The configuration for the ``HTTPResponseEncoder``.
    public var encoderConfiguration = HTTPResponseEncoder.Configuration()

    /// The configuration for the ``NIOTypedHTTPServerUpgradeHandler``.
    public var upgradeConfiguration: NIOTypedHTTPServerUpgradeConfiguration<UpgradeResult>

    /// Initializes a new ``NIOUpgradableHTTPServerPipelineConfiguration`` with default values.
    ///
    /// The current defaults provide the following features:
    /// 1. Assistance handling clients that pipeline HTTP requests.
    /// 2. Assistance handling protocol errors.
    /// 3. Outbound header fields validation to protect against response splitting attacks.
    public init(
        upgradeConfiguration: NIOTypedHTTPServerUpgradeConfiguration<UpgradeResult>
    ) {
        self.upgradeConfiguration = upgradeConfiguration
    }
}

extension ChannelPipeline {
    /// Configure a `ChannelPipeline` for use as an HTTP server.
    ///
    /// - Parameters:
    ///   - configuration: The HTTP pipeline's configuration.
    /// - Returns: An `EventLoopFuture` that will fire when the pipeline is configured. The future contains an `EventLoopFuture`
    /// that is fired once the pipeline has been upgraded or not and contains the `UpgradeResult`.
    @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
    public func configureUpgradableHTTPServerPipeline<UpgradeResult: Sendable>(
        configuration: NIOUpgradableHTTPServerPipelineConfiguration<UpgradeResult>
    ) -> EventLoopFuture<EventLoopFuture<UpgradeResult>> {
        self._configureUpgradableHTTPServerPipeline(
            configuration: configuration
        )
    }

    @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
    private func _configureUpgradableHTTPServerPipeline<UpgradeResult: Sendable>(
        configuration: NIOUpgradableHTTPServerPipelineConfiguration<UpgradeResult>
    ) -> EventLoopFuture<EventLoopFuture<UpgradeResult>> {
        let future: EventLoopFuture<EventLoopFuture<UpgradeResult>>

        if self.eventLoop.inEventLoop {
            let result = Result<EventLoopFuture<UpgradeResult>, Error> {
                try self.syncOperations.configureUpgradableHTTPServerPipeline(
                    configuration: configuration
                )
            }
            future = self.eventLoop.makeCompletedFuture(result)
        } else {
            future = self.eventLoop.submit {
                try self.syncOperations.configureUpgradableHTTPServerPipeline(
                    configuration: configuration
                )
            }
        }

        return future
    }
}

extension ChannelPipeline.SynchronousOperations {
    /// Configure a `ChannelPipeline` for use as an HTTP server.
    ///
    /// - Parameters:
    ///   - configuration: The HTTP pipeline's configuration.
    /// - Returns: An `EventLoopFuture` that is fired once the pipeline has been upgraded or not and contains the `UpgradeResult`.
    @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
    public func configureUpgradableHTTPServerPipeline<UpgradeResult: Sendable>(
        configuration: NIOUpgradableHTTPServerPipelineConfiguration<UpgradeResult>
    ) throws -> EventLoopFuture<UpgradeResult> {
        self.eventLoop.assertInEventLoop()

        let responseEncoder = HTTPResponseEncoder(configuration: configuration.encoderConfiguration)
        let requestDecoder = ByteToMessageHandler(HTTPRequestDecoder(leftOverBytesStrategy: .forwardBytes))

        var extraHTTPHandlers = [RemovableChannelHandler]()
        extraHTTPHandlers.reserveCapacity(4)
        extraHTTPHandlers.append(requestDecoder)

        try self.addHandler(responseEncoder)
        try self.addHandler(requestDecoder)

        if configuration.enablePipelining {
            let pipeliningHandler = HTTPServerPipelineHandler()
            try self.addHandler(pipeliningHandler)
            extraHTTPHandlers.append(pipeliningHandler)
        }

        if configuration.enableResponseHeaderValidation {
            let headerValidationHandler = NIOHTTPResponseHeadersValidator()
            try self.addHandler(headerValidationHandler)
            extraHTTPHandlers.append(headerValidationHandler)
        }

        if configuration.enableErrorHandling {
            let errorHandler = HTTPServerProtocolErrorHandler()
            try self.addHandler(errorHandler)
            extraHTTPHandlers.append(errorHandler)
        }

        let upgrader = NIOTypedHTTPServerUpgradeHandler(
            httpEncoder: responseEncoder,
            extraHTTPHandlers: extraHTTPHandlers,
            upgradeConfiguration: configuration.upgradeConfiguration
        )
        try self.addHandler(upgrader)

        return upgrader.upgradeResultFuture
    }
}

// MARK: - Client pipeline configuration

/// Configuration for an upgradable HTTP pipeline.
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
public struct NIOUpgradableHTTPClientPipelineConfiguration<UpgradeResult: Sendable> {
    /// The strategy to use when dealing with leftover bytes after removing the ``HTTPDecoder`` from the pipeline.
    public var leftOverBytesStrategy = RemoveAfterUpgradeStrategy.dropBytes

    /// Whether to validate outbound response headers to confirm that they are
    /// spec compliant. Defaults to `true`.
    public var enableOutboundHeaderValidation = true

    /// The configuration for the ``HTTPRequestEncoder``.
    public var encoderConfiguration = HTTPRequestEncoder.Configuration()

    /// The configuration for the ``NIOTypedHTTPClientUpgradeHandler``.
    public var upgradeConfiguration: NIOTypedHTTPClientUpgradeConfiguration<UpgradeResult>

    /// Initializes a new ``NIOUpgradableHTTPClientPipelineConfiguration`` with default values.
    ///
    /// The current defaults provide the following features:
    /// 1. Outbound header fields validation to protect against response splitting attacks.
    public init(
        upgradeConfiguration: NIOTypedHTTPClientUpgradeConfiguration<UpgradeResult>
    ) {
        self.upgradeConfiguration = upgradeConfiguration
    }
}

extension ChannelPipeline {
    /// Configure a `ChannelPipeline` for use as an HTTP client.
    ///
    /// - Parameters:
    ///   - configuration: The HTTP pipeline's configuration.
    /// - Returns: An `EventLoopFuture` that will fire when the pipeline is configured. The future contains an `EventLoopFuture`
    /// that is fired once the pipeline has been upgraded or not and contains the `UpgradeResult`.
    @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
    public func configureUpgradableHTTPClientPipeline<UpgradeResult: Sendable>(
        configuration: NIOUpgradableHTTPClientPipelineConfiguration<UpgradeResult>
    ) -> EventLoopFuture<EventLoopFuture<UpgradeResult>> {
        self._configureUpgradableHTTPClientPipeline(configuration: configuration)
    }

    @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
    private func _configureUpgradableHTTPClientPipeline<UpgradeResult: Sendable>(
        configuration: NIOUpgradableHTTPClientPipelineConfiguration<UpgradeResult>
    ) -> EventLoopFuture<EventLoopFuture<UpgradeResult>> {
        let future: EventLoopFuture<EventLoopFuture<UpgradeResult>>

        if self.eventLoop.inEventLoop {
            let result = Result<EventLoopFuture<UpgradeResult>, Error> {
                try self.syncOperations.configureUpgradableHTTPClientPipeline(
                    configuration: configuration
                )
            }
            future = self.eventLoop.makeCompletedFuture(result)
        } else {
            future = self.eventLoop.submit {
                try self.syncOperations.configureUpgradableHTTPClientPipeline(
                    configuration: configuration
                )
            }
        }

        return future
    }
}

extension ChannelPipeline.SynchronousOperations {
    /// Configure a `ChannelPipeline` for use as an HTTP client.
    ///
    /// - Parameters:
    ///   - configuration: The HTTP pipeline's configuration.
    /// - Returns: An `EventLoopFuture` that is fired once the pipeline has been upgraded or not and contains the `UpgradeResult`.
    @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
    public func configureUpgradableHTTPClientPipeline<UpgradeResult: Sendable>(
        configuration: NIOUpgradableHTTPClientPipelineConfiguration<UpgradeResult>
    ) throws -> EventLoopFuture<UpgradeResult> {
        self.eventLoop.assertInEventLoop()

        let requestEncoder = HTTPRequestEncoder(configuration: configuration.encoderConfiguration)
        let responseDecoder = ByteToMessageHandler(HTTPResponseDecoder(leftOverBytesStrategy: configuration.leftOverBytesStrategy))
        var httpHandlers = [RemovableChannelHandler]()
        httpHandlers.reserveCapacity(3)
        httpHandlers.append(requestEncoder)
        httpHandlers.append(responseDecoder)

        try self.addHandler(requestEncoder)
        try self.addHandler(responseDecoder)

        if configuration.enableOutboundHeaderValidation {
            let headerValidationHandler = NIOHTTPRequestHeadersValidator()
            try self.addHandler(headerValidationHandler)
            httpHandlers.append(headerValidationHandler)
        }

        let upgrader = NIOTypedHTTPClientUpgradeHandler(
            httpHandlers: httpHandlers,
            upgradeConfiguration: configuration.upgradeConfiguration
        )
        try self.addHandler(upgrader)

        return upgrader.upgradeResultFuture
    }
}
#endif