-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathendpoint.nim
More file actions
276 lines (226 loc) · 8.64 KB
/
Copy pathendpoint.nim
File metadata and controls
276 lines (226 loc) · 8.64 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
# SPDX-License-Identifier: Apache-2.0 OR MIT
# Copyright (c) Status Research & Development GmbH
import chronos, chronicles, results
import ./[errors, connection, tlsconfig, datagram, connectionmanager, lsquic_ffi]
import ./context/[server, client, context, io]
type
QuicEndpointCapability* = enum
CanListen
CanDial
QuicEndpointCapabilities* = set[QuicEndpointCapability]
QuicEndpoint* = ref object of RootObj
tlsConfig: TLSConfig
capabilities: QuicEndpointCapabilities
serverContext: ServerContext
clientContext: ClientContext
connman: ConnectionManager
udp: DatagramTransport
stopped: bool
const CloseWait: Duration = 300.milliseconds
proc createServerContext(
tlsConfig: TLSConfig, fd: cint
): ServerContext {.raises: [QuicError].} =
var context = ServerContext.new(tlsConfig).valueOr:
raise newException(QuicError, error)
context.fd = fd
context
proc createClientContext(
tlsConfig: TLSConfig, fd: cint
): ClientContext {.raises: [QuicError].} =
var context = ClientContext.new(tlsConfig).valueOr:
raise newException(QuicError, error)
context.fd = fd
context
proc scidLen(endpoint: QuicEndpoint): cuint {.raises: [].} =
if not endpoint.serverContext.isNil and
endpoint.serverContext.settings.es_scid_len != 0:
return endpoint.serverContext.settings.es_scid_len
if not endpoint.clientContext.isNil and
endpoint.clientContext.settings.es_scid_len != 0:
return endpoint.clientContext.settings.es_scid_len
LSQUIC_DF_SCID_LEN.cuint
proc packetDcid(
endpoint: QuicEndpoint, packet: seq[byte], cid: var CidKey
): bool {.raises: [].} =
if packet.len == 0:
return false
var cidLen: uint8
let offset = lsquic_dcid_from_packet(
unsafeAddr packet[0], packet.len.csize_t, endpoint.scidLen(), addr cidLen
)
if offset < 0:
return false
let start = offset.int
if cidLen == 0 or cidLen.int > MAX_CID_LEN or start + cidLen.int > packet.len:
return false
cid = CidKey(len: cidLen)
for i in 0 ..< cidLen.int:
cid.bytes[i] = packet[start + i]
true
func isIetfInitial(packet: seq[byte]): bool {.raises: [].} =
if packet.len == 0:
return false
(packet[0] and 0xC0'u8) == 0xC0'u8 and (packet[0] and 0x30'u8) == 0
proc receiveDatagram(
endpoint: QuicEndpoint, data: seq[byte], local, remote: TransportAddress
) {.raises: [].} =
if endpoint.isNil or endpoint.stopped:
return
let
hasClientContext = not endpoint.clientContext.isNil
hasServerContext = not endpoint.serverContext.isNil
var cid: CidKey
if endpoint.packetDcid(data, cid):
if hasClientContext and endpoint.clientContext.ownsCid(cid):
trace "Routing datagram to client context", cid
endpoint.clientContext.receive(Datagram(data: data), local, remote)
return
if hasServerContext and endpoint.serverContext.ownsCid(cid):
trace "Routing datagram to server context", cid
endpoint.serverContext.receive(Datagram(data: data), local, remote)
return
if hasClientContext and not hasServerContext:
endpoint.clientContext.receive(Datagram(data: data), local, remote)
return
if hasServerContext and not hasClientContext:
endpoint.serverContext.receive(Datagram(data: data), local, remote)
return
if hasServerContext and data.isIetfInitial():
trace "Routing initial datagram with unknown CID to server context",
bytes = data.len, local, remote
endpoint.serverContext.receive(Datagram(data: data), local, remote)
return
trace "Dropping datagram with unknown CID", bytes = data.len, local, remote
proc receiveFromUdp(
endpoint: QuicEndpoint, udp: DatagramTransport, remote: TransportAddress
) {.raises: [].} =
try:
endpoint.receiveDatagram(udp.getMessage(), udp.localAddress(), remote)
except TransportError as e:
warn "Could not read received datagram", errorMsg = e.msg
proc createUdp(
endpoint: QuicEndpoint, address: TransportAddress
): DatagramTransport {.raises: [QuicError, TransportOsError].} =
proc onReceive(
udp: DatagramTransport, remote: TransportAddress
) {.async: (raises: []).} =
endpoint.receiveFromUdp(udp, remote)
case address.family
of AddressFamily.IPv4:
newDatagramTransport(onReceive, local = address)
of AddressFamily.IPv6:
newDatagramTransport6(onReceive, local = address)
else:
raise newException(QuicError, "only IPv4/IPv6 address is supported")
proc createUdp(
endpoint: QuicEndpoint, family: AddressFamily
): DatagramTransport {.raises: [QuicError, TransportOsError].} =
proc onReceive(
udp: DatagramTransport, remote: TransportAddress
) {.async: (raises: []).} =
endpoint.receiveFromUdp(udp, remote)
case family
of AddressFamily.IPv4:
newDatagramTransport(onReceive)
of AddressFamily.IPv6:
newDatagramTransport6(onReceive)
else:
raise newException(QuicError, "endpoint supports only IPv4/IPv6 address")
proc new*(
_: type QuicEndpoint,
tlsConfig: TLSConfig,
address: TransportAddress,
capabilities: QuicEndpointCapabilities = {CanListen, CanDial},
): QuicEndpoint {.raises: [QuicConfigError, QuicError, TransportOsError].} =
if CanListen in capabilities and tlsConfig.certificate.len == 0:
raise newException(QuicConfigError, "tlsConfig does not contain a certificate")
var endpoint = QuicEndpoint(
tlsConfig: tlsConfig, capabilities: capabilities, connman: ConnectionManager.new()
)
endpoint.udp = endpoint.createUdp(address)
if CanListen in capabilities:
endpoint.serverContext = createServerContext(tlsConfig, cint(endpoint.udp.fd))
endpoint
proc new*(
_: type QuicEndpoint, tlsConfig: TLSConfig, family: AddressFamily
): QuicEndpoint {.raises: [QuicError, TransportOsError].} =
var endpoint = QuicEndpoint(
tlsConfig: tlsConfig, capabilities: {CanDial}, connman: ConnectionManager.new()
)
endpoint.udp = endpoint.createUdp(family)
endpoint
proc ensureClientContext(
endpoint: QuicEndpoint
): ClientContext {.raises: [QuicError].} =
if CanDial notin endpoint.capabilities:
raise newException(QuicError, "endpoint is not dial-capable")
if endpoint.clientContext.isNil:
endpoint.clientContext =
createClientContext(endpoint.tlsConfig, cint(endpoint.udp.fd))
endpoint.clientContext
proc waitForIncoming(
endpoint: QuicEndpoint
): Future[QuicConnection] {.async: (raises: [CancelledError]).} =
await endpoint.serverContext.incoming.get()
proc accept*(
endpoint: QuicEndpoint
): Future[Connection] {.async: (raises: [CancelledError, TransportError]).} =
if CanListen notin endpoint.capabilities:
raise newException(TransportError, "endpoint is not listen-capable")
if endpoint.stopped or endpoint.serverContext.isNil:
raise newException(TransportError, "endpoint is stopped")
while true:
let
incomingFut = endpoint.waitForIncoming()
closedFut = endpoint.connman.closed
raceFut = await race(closedFut, incomingFut)
if raceFut == closedFut:
await incomingFut.cancelAndWait()
raise newException(TransportError, "endpoint is stopped")
let quicConn = await incomingFut
if quicConn.lsquicConn.isNil:
debug "Dropping already closed incoming connection"
continue
let conn = newIncomingConnection(endpoint.serverContext, quicConn)
endpoint.connman.addConnection(conn)
return conn
proc dial*(
endpoint: QuicEndpoint, address: TransportAddress
): Future[Connection] {.
async: (raises: [CancelledError, QuicError, DialError, TransportOsError])
.} =
let ctx = endpoint.ensureClientContext()
let connection = newOutgoingConnection(ctx, endpoint.udp.localAddress(), address)
endpoint.connman.addConnection(connection)
var connected = false
try:
await connection.dial()
connected = true
finally:
if not connected:
endpoint.connman.removeConnection(connection)
connection
proc localAddress*(
endpoint: QuicEndpoint
): TransportAddress {.raises: [TransportOsError].} =
endpoint.udp.localAddress()
proc datagramTransport*(endpoint: QuicEndpoint): DatagramTransport {.raises: [].} =
endpoint.udp
proc stop*(endpoint: QuicEndpoint) {.async: (raises: [CancelledError]).} =
if endpoint.stopped:
return
endpoint.stopped = true
await noCancel endpoint.connman.stop()
# Politely wait before closing udp so connection close packets can be sent.
await noCancel sleepAsync(CloseWait)
if not endpoint.clientContext.isNil:
endpoint.clientContext.stop()
if not endpoint.serverContext.isNil:
endpoint.serverContext.stop()
await noCancel endpoint.udp.closeWait()
if not endpoint.clientContext.isNil:
endpoint.clientContext.destroy()
endpoint.clientContext = nil
if not endpoint.serverContext.isNil:
endpoint.serverContext.destroy()
endpoint.serverContext = nil