forked from apple/swift-nio-http3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTP3ToHTTPCodecs.swift
More file actions
453 lines (413 loc) · 17 KB
/
Copy pathHTTP3ToHTTPCodecs.swift
File metadata and controls
453 lines (413 loc) · 17 KB
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2026 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
//
//===----------------------------------------------------------------------===//
public import HTTP3
package import HTTPTypes
public import NIOCore
public import NIOHTTPTypes
package protocol HTTPMessagePart {
static func head(fields: [HTTPField]) throws(HTTP3Error) -> Self
static func body(buffer: ByteBuffer) -> Self
static func end(trailers: [HTTPField]) throws(HTTP3Error) -> Self
static func end() -> Self
}
struct HTTP3FieldError: Error, CustomStringConvertible {
let description: String
}
private func invalidHeadersError(message: String, location: HTTP3Error.SourceLocation) -> HTTP3Error {
let cause = HTTP3FieldError(description: message)
return HTTP3Error(
code: .malformedMessage,
message: "Invalid headers",
cause: cause,
errorCode: .H3_MESSAGE_ERROR,
location: location
)
}
extension HTTPRequestPart: HTTPMessagePart {
package static func head(fields: [HTTPField]) throws(HTTP3Error) -> HTTPRequestPart {
let request: HTTPRequest
do {
request = try HTTPRequest(parsed: fields)
} catch {
throw HTTP3Error(
code: .malformedMessage,
message: "Invalid headers",
cause: error,
errorCode: .H3_MESSAGE_ERROR,
location: .here()
)
}
if let te = request.headerFields[.te] {
if te != "trailers" {
throw invalidHeadersError(message: "te field must contain trailers if present", location: .here())
}
}
if request.headerFields.contains(.transferEncoding) {
throw invalidHeadersError(message: "transfer-encoding field must not be present", location: .here())
}
let scheme = request.scheme
let path = request.path
let authority = request.authority
let host = request.headerFields[.init(parsed: "host")!]
if request.method != .connect {
// All HTTP/3 requests MUST include exactly one value for the :method, :scheme, and :path pseudo-header fields, unless the request is a CONNECT request
guard let scheme else {
throw invalidHeadersError(message: "Missing scheme", location: .here())
}
guard let path else {
throw invalidHeadersError(message: "Missing path", location: .here())
}
// If the :scheme pseudo-header field identifies a scheme that has a mandatory authority component (including "http" and "https"), the request MUST contain either an :authority pseudo-header field or a Host header field
if scheme == "https" || scheme == "http" {
guard host != nil || authority != nil else {
throw invalidHeadersError(message: "Missing host and authority", location: .here())
}
}
// If these fields are present, they MUST NOT be empty
if let host, host.isEmpty {
throw invalidHeadersError(message: "host field is empty", location: .here())
}
if let authority, authority.isEmpty {
throw invalidHeadersError(message: "authority field is empty", location: .here())
}
// If both fields are present, they MUST contain the same value
if let host, let authority {
guard host == authority else {
throw invalidHeadersError(message: "Mismatched authority and host", location: .here())
}
}
// The path pseudo-header field MUST NOT be empty for "http" or "https" URIs
if scheme == "https" || scheme == "http" {
guard !path.isEmpty else {
throw invalidHeadersError(message: "Path field is empty", location: .here())
}
}
} else {
// A CONNECT request MUST be constructed as follows:
// - The :method pseudo-header field is set to "CONNECT"
// - The :scheme and :path pseudo-header fields are omitted
// - TODO: The :authority pseudo-header field contains the host and port to connect to (equivalent to the authority-form of the request-target of CONNECT requests; see Section 7.1 of [HTTP]).
guard scheme == nil && path == nil else {
throw invalidHeadersError(message: "CONNECT request must not contain path or scheme", location: .here())
}
guard authority != nil else {
throw invalidHeadersError(message: "CONNECT request must contain authority", location: .here())
}
}
return .head(request)
}
package static func body(buffer: ByteBuffer) -> HTTPRequestPart {
.body(buffer)
}
package static func end(trailers: [HTTPField]) throws(HTTP3Error) -> HTTPRequestPart {
if trailers.isEmpty {
return .end(nil)
} else {
do {
return try .end(HTTPFields(parsedTrailerFields: trailers))
} catch {
throw HTTP3Error(
code: .malformedMessage,
message: "Invalid trailers",
cause: error,
errorCode: .H3_MESSAGE_ERROR,
location: .here()
)
}
}
}
package static func end() -> HTTPRequestPart {
.end(nil)
}
}
extension HTTPResponsePart: HTTPMessagePart {
package static func head(fields: [HTTPField]) throws(HTTP3Error) -> HTTPResponsePart {
let response: HTTPResponse
do {
response = try HTTPResponse(parsed: fields)
} catch {
throw HTTP3Error(
code: .malformedMessage,
message: "Invalid headers",
cause: error,
errorCode: .H3_MESSAGE_ERROR,
location: .here()
)
}
if response.headerFields.contains(.te) {
throw invalidHeadersError(message: "te field must not be present", location: .here())
}
if response.headerFields.contains(.transferEncoding) {
throw invalidHeadersError(message: "transfer-encoding field must not be present", location: .here())
}
return .head(response)
}
package static func body(buffer: ByteBuffer) -> HTTPResponsePart {
.body(buffer)
}
package static func end(trailers: [HTTPField]) throws(HTTP3Error) -> HTTPResponsePart {
if trailers.isEmpty {
return .end(nil)
} else {
do {
return try .end(HTTPFields(parsedTrailerFields: trailers))
} catch {
throw HTTP3Error(
code: .malformedMessage,
message: "Invalid trailers",
cause: error,
errorCode: .H3_MESSAGE_ERROR,
location: .here()
)
}
}
}
package static func end() -> HTTPResponsePart {
.end(nil)
}
}
/// Process HTTP3Frames into HTTPMessageParts.
/// Use this to convert incoming frames into message parts.
package struct HTTPMessageParsingStateMachine<Part: HTTPMessagePart> {
enum State {
case awaitingHeaders
case awaitingBodyOrTrailers
case messageComplete
case failed
}
private var state = State.awaitingHeaders
package init() {}
package enum ProcessFrameAction {
case returnPart(Part)
case emitError(HTTP3Error)
}
package mutating func processFrame(frame: HTTP3Frame) -> ProcessFrameAction? {
switch self.state {
case .failed:
return .none
case .awaitingHeaders:
switch frame {
case .headers(let headers):
do {
let part = try Part.head(fields: headers.fields)
if headers.representsInterimResponse {
// Multiple interim (1xx) responses can precede the final response; remain in the same state to
// accept further interim responses or the final response. We can only reach this branch on the
// response parsing side.
self.state = .awaitingHeaders
} else {
self.state = .awaitingBodyOrTrailers
}
return .returnPart(part)
} catch {
self.state = .failed
return .emitError(error)
}
case .data, .cancelPush, .settings, .maxPushID, .pushPromise, .goaway:
// This should not happen because the stream state machine shouldn't allow a bad frame to get here
fatalError("Unexpected frame")
}
case .awaitingBodyOrTrailers:
switch frame {
case .headers(let headers):
// If the incoming frame is of type 'headers', it must be the trailers
do {
let part = try Part.end(trailers: headers.fields)
self.state = .messageComplete
return .returnPart(part)
} catch {
self.state = .failed
return .emitError(error)
}
// Any number of data frames is fine. State stays as-is
case .data(let payload):
return .returnPart(.body(buffer: payload.payload))
case .cancelPush, .settings, .maxPushID, .pushPromise, .goaway:
// This should not happen because the stream state machine shouldn't allow a bad frame to get here
fatalError("Unexpected frame")
}
case .messageComplete:
// This should not happen because the stream state machine shouldn't allow a bad frame to get here
fatalError("More frames received after trailers")
}
}
package enum InputClosedAction {
case returnPart(Part)
}
package mutating func inputClosed() -> InputClosedAction? {
switch self.state {
case .awaitingHeaders:
self.state = .messageComplete
return .returnPart(.end())
case .awaitingBodyOrTrailers:
self.state = .messageComplete
return .returnPart(.end())
case .failed:
return .none
case .messageComplete:
// If we processed trailers, that means we sent an end, so don't send another one
return .none
}
}
}
/// Use this on clients to write `HTTPRequestPart` and receive `HTTPResponsePart`.
public final class HTTP3ToHTTPClientCodec: ChannelDuplexHandler {
public typealias InboundIn = HTTP3Frame
public typealias InboundOut = HTTPResponsePart
public typealias OutboundIn = HTTPRequestPart
public typealias OutboundOut = HTTP3Frame
private var readState: HTTPMessageParsingStateMachine<HTTPResponsePart> = .init()
public init() {}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let frame = self.unwrapInboundIn(data)
let action = self.readState.processFrame(frame: frame)
switch action {
case .returnPart(let part):
context.fireChannelRead(wrapInboundOut(part))
case .emitError(let error):
context.fireErrorCaught(error)
case .none:
break
}
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
let part = unwrapOutboundIn(data)
switch part {
case .head(let request):
var fields = [HTTPField]()
fields.reserveCapacity(request.headerFields.count + 5)
fields.append(request.pseudoHeaderFields.method)
if let scheme = request.pseudoHeaderFields.scheme {
fields.append(scheme)
}
if let authority = request.pseudoHeaderFields.authority {
fields.append(authority)
}
if let path = request.pseudoHeaderFields.path {
fields.append(path)
}
if let extendedConnectProtocol = request.pseudoHeaderFields.extendedConnectProtocol {
fields.append(extendedConnectProtocol)
}
for field in request.headerFields {
fields.append(field)
}
let frame = HTTP3Frame.headers(fields)
context.write(wrapOutboundOut(frame), promise: promise)
case .body(let data):
let frame = HTTP3Frame.data(data)
context.write(wrapOutboundOut(frame), promise: promise)
case .end(let trailers):
if let trailers {
var fields = [HTTPField]()
fields.reserveCapacity(trailers.count)
for field in trailers {
fields.append(field)
}
let frame = HTTP3Frame.headers(fields)
context.write(wrapOutboundOut(frame), promise: nil)
context.close(mode: .output, promise: promise)
} else {
// No trailers, just close
context.close(mode: .output, promise: promise)
}
}
}
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
guard event as? ChannelEvent == ChannelEvent.inputClosed else {
context.fireUserInboundEventTriggered(event)
return
}
let action = self.readState.inputClosed()
switch action {
case .returnPart(let part):
context.fireChannelRead(self.wrapInboundOut(part))
context.fireChannelReadComplete()
case .none:
break
}
context.fireUserInboundEventTriggered(event)
}
}
@available(*, unavailable)
extension HTTP3ToHTTPClientCodec: Sendable {}
/// Use this on servers to receive `HTTPRequestPart` and write `HTTPResponsePart`.
public final class HTTP3ToHTTPServerCodec: ChannelDuplexHandler {
public typealias InboundIn = HTTP3Frame
public typealias InboundOut = HTTPRequestPart
public typealias OutboundIn = HTTPResponsePart
public typealias OutboundOut = HTTP3Frame
private var readState: HTTPMessageParsingStateMachine<HTTPRequestPart> = .init()
public init() {}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let frame = self.unwrapInboundIn(data)
let action = self.readState.processFrame(frame: frame)
switch action {
case .returnPart(let part):
context.fireChannelRead(wrapInboundOut(part))
case .emitError(let error):
context.fireErrorCaught(error)
case .none:
break
}
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
let part = unwrapOutboundIn(data)
switch part {
case .head(let request):
var fields = [HTTPField]()
fields.reserveCapacity(request.headerFields.count + 1)
fields.append(request.pseudoHeaderFields.status)
for field in request.headerFields {
fields.append(field)
}
let frame = HTTP3Frame.headers(fields)
context.write(wrapOutboundOut(frame), promise: promise)
case .body(let data):
let frame = HTTP3Frame.data(data)
context.write(wrapOutboundOut(frame), promise: promise)
case .end(let trailers):
if let trailers {
var fields = [HTTPField]()
fields.reserveCapacity(trailers.count)
for field in trailers {
fields.append(field)
}
let frame = HTTP3Frame.headers(fields)
context.write(wrapOutboundOut(frame), promise: nil)
context.close(mode: .output, promise: promise)
} else {
// No trailers, just close
context.close(mode: .output, promise: promise)
}
}
}
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
guard event as? ChannelEvent == ChannelEvent.inputClosed else {
context.fireUserInboundEventTriggered(event)
return
}
let action = self.readState.inputClosed()
switch action {
case .returnPart(let part):
context.fireChannelRead(self.wrapInboundOut(part))
context.fireChannelReadComplete()
case .none:
break
}
context.fireUserInboundEventTriggered(event)
}
}
@available(*, unavailable)
extension HTTP3ToHTTPServerCodec: Sendable {}