|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the AsyncHTTPClient open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2021 Apple Inc. and the AsyncHTTPClient project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +import NIO |
| 16 | +import NIOHTTP1 |
| 17 | + |
| 18 | +final class HTTP1ProxyConnectHandler: ChannelDuplexHandler, RemovableChannelHandler { |
| 19 | + typealias OutboundIn = Never |
| 20 | + typealias OutboundOut = HTTPClientRequestPart |
| 21 | + typealias InboundIn = HTTPClientResponsePart |
| 22 | + |
| 23 | + enum State { |
| 24 | + // transitions to `.connectSent` or `.failed` |
| 25 | + case initialized |
| 26 | + // transitions to `.headReceived` or `.failed` |
| 27 | + case connectSent(Scheduled<Void>) |
| 28 | + // transitions to `.completed` or `.failed` |
| 29 | + case headReceived(Scheduled<Void>) |
| 30 | + // final error state |
| 31 | + case failed(Error) |
| 32 | + // final success state |
| 33 | + case completed |
| 34 | + } |
| 35 | + |
| 36 | + private var state: State = .initialized |
| 37 | + |
| 38 | + private let targetHost: String |
| 39 | + private let targetPort: Int |
| 40 | + private let proxyAuthorization: HTTPClient.Authorization? |
| 41 | + private let deadline: NIODeadline |
| 42 | + |
| 43 | + private var proxyEstablishedPromise: EventLoopPromise<Void>? |
| 44 | + var proxyEstablishedFuture: EventLoopFuture<Void>? { |
| 45 | + return self.proxyEstablishedPromise?.futureResult |
| 46 | + } |
| 47 | + |
| 48 | + init(targetHost: String, |
| 49 | + targetPort: Int, |
| 50 | + proxyAuthorization: HTTPClient.Authorization?, |
| 51 | + deadline: NIODeadline) { |
| 52 | + self.targetHost = targetHost |
| 53 | + self.targetPort = targetPort |
| 54 | + self.proxyAuthorization = proxyAuthorization |
| 55 | + self.deadline = deadline |
| 56 | + } |
| 57 | + |
| 58 | + func handlerAdded(context: ChannelHandlerContext) { |
| 59 | + self.proxyEstablishedPromise = context.eventLoop.makePromise(of: Void.self) |
| 60 | + |
| 61 | + self.sendConnect(context: context) |
| 62 | + } |
| 63 | + |
| 64 | + func handlerRemoved(context: ChannelHandlerContext) { |
| 65 | + switch self.state { |
| 66 | + case .failed, .completed: |
| 67 | + break |
| 68 | + case .initialized, .connectSent, .headReceived: |
| 69 | + struct NoResult: Error {} |
| 70 | + self.state = .failed(NoResult()) |
| 71 | + self.proxyEstablishedPromise?.fail(NoResult()) |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + func channelActive(context: ChannelHandlerContext) { |
| 76 | + self.sendConnect(context: context) |
| 77 | + } |
| 78 | + |
| 79 | + func channelInactive(context: ChannelHandlerContext) { |
| 80 | + switch self.state { |
| 81 | + case .initialized: |
| 82 | + preconditionFailure("How can we receive a channelInactive before a channelActive?") |
| 83 | + case .connectSent(let timeout), .headReceived(let timeout): |
| 84 | + timeout.cancel() |
| 85 | + self.failWithError(HTTPClientError.remoteConnectionClosed, context: context, closeConnection: false) |
| 86 | + |
| 87 | + case .failed, .completed: |
| 88 | + break |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { |
| 93 | + preconditionFailure("We don't support outgoing traffic during HTTP Proxy update.") |
| 94 | + } |
| 95 | + |
| 96 | + func channelRead(context: ChannelHandlerContext, data: NIOAny) { |
| 97 | + switch self.unwrapInboundIn(data) { |
| 98 | + case .head(let head): |
| 99 | + self.handleHTTPHeadReceived(head, context: context) |
| 100 | + case .body: |
| 101 | + self.handleHTTPBodyReceived(context: context) |
| 102 | + case .end: |
| 103 | + self.handleHTTPEndReceived(context: context) |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + private func sendConnect(context: ChannelHandlerContext) { |
| 108 | + guard case .initialized = self.state else { |
| 109 | + // we might run into this handler twice, once in handlerAdded and once in channelActive. |
| 110 | + return |
| 111 | + } |
| 112 | + |
| 113 | + let timeout = context.eventLoop.scheduleTask(deadline: self.deadline) { |
| 114 | + switch self.state { |
| 115 | + case .initialized: |
| 116 | + preconditionFailure("How can we have a scheduled timeout, if the connection is not even up?") |
| 117 | + |
| 118 | + case .connectSent, .headReceived: |
| 119 | + self.failWithError(HTTPClientError.httpProxyHandshakeTimeout, context: context) |
| 120 | + |
| 121 | + case .failed, .completed: |
| 122 | + break |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + self.state = .connectSent(timeout) |
| 127 | + |
| 128 | + var head = HTTPRequestHead( |
| 129 | + version: .init(major: 1, minor: 1), |
| 130 | + method: .CONNECT, |
| 131 | + uri: "\(self.targetHost):\(self.targetPort)" |
| 132 | + ) |
| 133 | + if let authorization = self.proxyAuthorization { |
| 134 | + head.headers.replaceOrAdd(name: "proxy-authorization", value: authorization.headerValue) |
| 135 | + } |
| 136 | + context.write(self.wrapOutboundOut(.head(head)), promise: nil) |
| 137 | + context.write(self.wrapOutboundOut(.end(nil)), promise: nil) |
| 138 | + context.flush() |
| 139 | + } |
| 140 | + |
| 141 | + private func handleHTTPHeadReceived(_ head: HTTPResponseHead, context: ChannelHandlerContext) { |
| 142 | + guard case .connectSent(let scheduled) = self.state else { |
| 143 | + preconditionFailure("HTTPDecoder should throw an error, if we have not send a request") |
| 144 | + } |
| 145 | + |
| 146 | + switch head.status.code { |
| 147 | + case 200..<300: |
| 148 | + // Any 2xx (Successful) response indicates that the sender (and all |
| 149 | + // inbound proxies) will switch to tunnel mode immediately after the |
| 150 | + // blank line that concludes the successful response's header section |
| 151 | + self.state = .headReceived(scheduled) |
| 152 | + case 407: |
| 153 | + self.failWithError(HTTPClientError.proxyAuthenticationRequired, context: context) |
| 154 | + |
| 155 | + default: |
| 156 | + // Any response other than a successful response indicates that the tunnel |
| 157 | + // has not yet been formed and that the connection remains governed by HTTP. |
| 158 | + self.failWithError(HTTPClientError.invalidProxyResponse, context: context) |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + private func handleHTTPBodyReceived(context: ChannelHandlerContext) { |
| 163 | + switch self.state { |
| 164 | + case .headReceived(let timeout): |
| 165 | + timeout.cancel() |
| 166 | + // we don't expect a body |
| 167 | + self.failWithError(HTTPClientError.invalidProxyResponse, context: context) |
| 168 | + case .failed: |
| 169 | + // ran into an error before... ignore this one |
| 170 | + break |
| 171 | + case .completed, .connectSent, .initialized: |
| 172 | + preconditionFailure("Invalid state: \(self.state)") |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + private func handleHTTPEndReceived(context: ChannelHandlerContext) { |
| 177 | + switch self.state { |
| 178 | + case .headReceived(let timeout): |
| 179 | + timeout.cancel() |
| 180 | + self.state = .completed |
| 181 | + self.proxyEstablishedPromise?.succeed(()) |
| 182 | + |
| 183 | + case .failed: |
| 184 | + // ran into an error before... ignore this one |
| 185 | + break |
| 186 | + case .initialized, .connectSent, .completed: |
| 187 | + preconditionFailure("Invalid state: \(self.state)") |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + private func failWithError(_ error: Error, context: ChannelHandlerContext, closeConnection: Bool = true) { |
| 192 | + self.state = .failed(error) |
| 193 | + self.proxyEstablishedPromise?.fail(error) |
| 194 | + context.fireErrorCaught(error) |
| 195 | + if closeConnection { |
| 196 | + context.close(mode: .all, promise: nil) |
| 197 | + } |
| 198 | + } |
| 199 | +} |
0 commit comments