forked from swift-server/async-http-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtils.swift
287 lines (258 loc) · 12.8 KB
/
Utils.swift
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
//===----------------------------------------------------------------------===//
//
// This source file is part of the AsyncHTTPClient open source project
//
// Copyright (c) 2018-2020 Apple Inc. and the AsyncHTTPClient project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
#if canImport(Network)
import Network
#endif
import Logging
import NIO
import NIOHTTP1
import NIOHTTPCompression
import NIOSSL
import NIOTransportServices
internal extension String {
var isIPAddress: Bool {
var ipv4Addr = in_addr()
var ipv6Addr = in6_addr()
return self.withCString { ptr in
inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
}
}
}
public final class HTTPClientCopyingDelegate: HTTPClientResponseDelegate {
public typealias Response = Void
let chunkHandler: (ByteBuffer) -> EventLoopFuture<Void>
public init(chunkHandler: @escaping (ByteBuffer) -> EventLoopFuture<Void>) {
self.chunkHandler = chunkHandler
}
public func didReceiveBodyPart(task: HTTPClient.Task<Void>, _ buffer: ByteBuffer) -> EventLoopFuture<Void> {
return self.chunkHandler(buffer)
}
public func didFinishRequest(task: HTTPClient.Task<Void>) throws {
return ()
}
}
extension NIOClientTCPBootstrap {
static func makeHTTP1Channel(destination: ConnectionPool.Key,
eventLoop: EventLoop,
configuration: HTTPClient.Configuration,
sslContextCache: SSLContextCache,
preference: HTTPClient.EventLoopPreference,
logger: Logger) -> EventLoopFuture<Channel> {
let channelEventLoop = preference.bestEventLoop ?? eventLoop
let key = destination
let requiresTLS = key.scheme.requiresTLS
let sslContext: EventLoopFuture<NIOSSLContext?>
if key.scheme.requiresTLS, configuration.proxy != nil {
// If we use a proxy & also require TLS, then we always use NIOSSL (and not Network.framework TLS because
// it can't be added later) and therefore require a `NIOSSLContext`.
// In this case, `makeAndConfigureBootstrap` will not create another `NIOSSLContext`.
//
// Note that TLS proxies are not supported at the moment. This means that we will always speak
// plaintext to the proxy but we do support sending HTTPS traffic through the proxy.
sslContext = sslContextCache.sslContext(tlsConfiguration: configuration.tlsConfiguration ?? .forClient(),
eventLoop: eventLoop,
logger: logger).map { $0 }
} else {
sslContext = eventLoop.makeSucceededFuture(nil)
}
let bootstrap = NIOClientTCPBootstrap.makeAndConfigureBootstrap(on: channelEventLoop,
host: key.host,
port: key.port,
requiresTLS: requiresTLS,
configuration: configuration,
sslContextCache: sslContextCache,
logger: logger)
return bootstrap.flatMap { bootstrap -> EventLoopFuture<Channel> in
let channel: EventLoopFuture<Channel>
switch key.scheme {
case .http, .https:
let address = HTTPClient.resolveAddress(host: key.host, port: key.port, proxy: configuration.proxy)
channel = bootstrap.connect(host: address.host, port: address.port)
case .unix, .http_unix, .https_unix:
channel = bootstrap.connect(unixDomainSocketPath: key.unixPath)
}
return channel.flatMap { channel -> EventLoopFuture<(Channel, NIOSSLContext?)> in
sslContext.map { sslContext -> (Channel, NIOSSLContext?) in
(channel, sslContext)
}
}.flatMap { channel, sslContext in
configureChannelPipeline(channel,
isNIOTS: bootstrap.isNIOTS,
sslContext: sslContext,
configuration: configuration,
key: key)
}.flatMapErrorThrowing { error in
if bootstrap.isNIOTS {
throw HTTPClient.NWErrorHandler.translateError(error)
} else {
throw error
}
}
}
}
/// Creates and configures a bootstrap given the `eventLoop`, if TLS/a proxy is being used.
private static func makeAndConfigureBootstrap(
on eventLoop: EventLoop,
host: String,
port: Int,
requiresTLS: Bool,
configuration: HTTPClient.Configuration,
sslContextCache: SSLContextCache,
logger: Logger
) -> EventLoopFuture<NIOClientTCPBootstrap> {
return self.makeBestBootstrap(host: host,
eventLoop: eventLoop,
requiresTLS: requiresTLS,
sslContextCache: sslContextCache,
tlsConfiguration: configuration.tlsConfiguration ?? .forClient(),
useProxy: configuration.proxy != nil,
logger: logger)
.map { bootstrap -> NIOClientTCPBootstrap in
var bootstrap = bootstrap
if let timeout = configuration.timeout.connect {
bootstrap = bootstrap.connectTimeout(timeout)
}
// Don't enable TLS if we have a proxy, this will be enabled later on (outside of this method).
if requiresTLS, configuration.proxy == nil {
bootstrap = bootstrap.enableTLS()
}
return bootstrap.channelInitializer { channel in
do {
if let proxy = configuration.proxy {
switch proxy.type {
case .http:
try channel.pipeline.syncAddHTTPProxyHandler(host: host,
port: port,
authorization: proxy.authorization)
case .socks:
try channel.pipeline.syncAddSOCKSProxyHandler(host: host, port: port)
}
} else if requiresTLS {
// We only add the handshake verifier if we need TLS and we're not going through a proxy.
// If we're going through a proxy we add it later (outside of this method).
let completionPromise = channel.eventLoop.makePromise(of: Void.self)
try channel.pipeline.syncOperations.addHandler(TLSEventsHandler(completionPromise: completionPromise),
name: TLSEventsHandler.handlerName)
}
return channel.eventLoop.makeSucceededVoidFuture()
} catch {
return channel.eventLoop.makeFailedFuture(error)
}
}
}
}
/// Creates the best-suited bootstrap given an `EventLoop` and pairs it with an appropriate TLS provider.
private static func makeBestBootstrap(
host: String,
eventLoop: EventLoop,
requiresTLS: Bool,
sslContextCache: SSLContextCache,
tlsConfiguration: TLSConfiguration,
useProxy: Bool,
logger: Logger
) -> EventLoopFuture<NIOClientTCPBootstrap> {
#if canImport(Network)
// if eventLoop is compatible with NIOTransportServices create a NIOTSConnectionBootstrap
if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *), let tsBootstrap = NIOTSConnectionBootstrap(validatingGroup: eventLoop) {
// create NIOClientTCPBootstrap with NIOTS TLS provider
return tlsConfiguration.getNWProtocolTLSOptions(on: eventLoop)
.map { parameters in
let tlsProvider = NIOTSClientTLSProvider(tlsOptions: parameters)
return NIOClientTCPBootstrap(tsBootstrap, tls: tlsProvider)
}
}
#endif
if let clientBootstrap = ClientBootstrap(validatingGroup: eventLoop) {
// If there is a proxy don't create TLS provider as it will be added at a later point.
if !requiresTLS || useProxy {
return eventLoop.makeSucceededFuture(NIOClientTCPBootstrap(clientBootstrap,
tls: NIOInsecureNoTLS()))
} else {
return sslContextCache.sslContext(tlsConfiguration: tlsConfiguration,
eventLoop: eventLoop,
logger: logger)
.flatMapThrowing { sslContext in
let hostname = (host.isIPAddress || host.isEmpty) ? nil : host
let tlsProvider = try NIOSSLClientTLSProvider<ClientBootstrap>(context: sslContext, serverHostname: hostname)
return NIOClientTCPBootstrap(clientBootstrap, tls: tlsProvider)
}
}
}
preconditionFailure("Cannot create bootstrap for event loop \(eventLoop)")
}
}
private func configureChannelPipeline(_ channel: Channel,
isNIOTS: Bool,
sslContext: NIOSSLContext?,
configuration: HTTPClient.Configuration,
key: ConnectionPool.Key) -> EventLoopFuture<Channel> {
let requiresTLS = key.scheme.requiresTLS
let handshakeFuture: EventLoopFuture<Void>
if requiresTLS, configuration.proxy != nil {
let handshakePromise = channel.eventLoop.makePromise(of: Void.self)
channel.pipeline.syncAddLateSSLHandlerIfNeeded(for: key,
sslContext: sslContext!,
handshakePromise: handshakePromise)
handshakeFuture = handshakePromise.futureResult
} else if requiresTLS {
do {
handshakeFuture = try channel.pipeline.syncOperations.handler(type: TLSEventsHandler.self).completionPromise.futureResult
} catch {
return channel.eventLoop.makeFailedFuture(error)
}
} else {
handshakeFuture = channel.eventLoop.makeSucceededVoidFuture()
}
return handshakeFuture.flatMapThrowing {
let syncOperations = channel.pipeline.syncOperations
// If we got here and we had a TLSEventsHandler in the pipeline, we can remove it ow.
if requiresTLS {
channel.pipeline.removeHandler(name: TLSEventsHandler.handlerName, promise: nil)
}
try syncOperations.addHTTPClientHandlers(leftOverBytesStrategy: .forwardBytes)
if isNIOTS {
try syncOperations.addHandler(HTTPClient.NWErrorHandler(), position: .first)
}
switch configuration.decompression {
case .disabled:
()
case .enabled(let limit):
let decompressHandler = NIOHTTPResponseDecompressor(limit: limit)
try syncOperations.addHandler(decompressHandler)
}
return channel
}
}
extension Connection {
func removeHandler<Handler: RemovableChannelHandler>(_ type: Handler.Type) -> EventLoopFuture<Void> {
return self.channel.pipeline.handler(type: type).flatMap { handler in
self.channel.pipeline.removeHandler(handler)
}.recover { _ in }
}
}
extension NIOClientTCPBootstrap {
var isNIOTS: Bool {
#if canImport(Network)
if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
return self.underlyingBootstrap is NIOTSConnectionBootstrap
} else {
return false
}
#else
return false
#endif
}
}