forked from vapor/mysql-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMySQLConnectionHandler.swift
378 lines (347 loc) · 14.1 KB
/
MySQLConnectionHandler.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
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
import NIOSSL
internal struct MySQLCommandContext {
var handler: MySQLCommand
var promise: EventLoopPromise<Void>
}
final class MySQLConnectionHandler: ChannelDuplexHandler {
typealias InboundIn = MySQLPacket
typealias OutboundIn = MySQLCommandContext
typealias OutboundOut = MySQLPacket
enum State {
case handshake(HandshakeState)
case authenticating(AuthenticationState)
case commandPhase
}
struct HandshakeState {
let username: String
let database: String
let password: String?
let tlsConfiguration: TLSConfiguration?
let done: EventLoopPromise<Void>
}
struct AuthenticationState {
var authPluginName: String
var password: String?
var isTLS: Bool
var done: EventLoopPromise<Void>
}
enum CommandState {
case ready
case busy
}
let logger: Logger
var state: State
var serverCapabilities: MySQLProtocol.CapabilityFlags?
var queue: CircularBuffer<MySQLCommandContext>
let sequence: MySQLPacketSequence
var commandState: CommandState
init(logger: Logger, state: State, sequence: MySQLPacketSequence) {
self.logger = logger
self.state = state
self.queue = .init()
self.sequence = sequence
self.commandState = .ready
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
var packet = self.unwrapInboundIn(data)
switch self.state {
case .handshake(let state):
do {
try self.handleHandshake(context: context, packet: &packet, state: state)
} catch {
state.done.fail(error)
}
case .authenticating(let state):
do {
try self.handleAuthentication(context: context, packet: &packet, state: state)
} catch {
state.done.fail(error)
}
case .commandPhase:
if let current = self.queue.first {
do {
let commandState = try current.handler.handle(packet: &packet, capabilities: self.serverCapabilities!)
self.handleCommandState(context: context, commandState)
} catch {
self.queue.removeFirst()
self.commandState = .ready
current.promise.fail(error)
self.sendEnqueuedCommandIfReady(context: context)
}
} else {
assertionFailure("unhandled packet: \(packet.payload.debugDescription)")
}
}
}
func handleHandshake(context: ChannelHandlerContext, packet: inout MySQLPacket, state: HandshakeState) throws {
let handshakeRequest = try packet.decode(MySQLProtocol.HandshakeV10.self, capabilities: [])
self.logger.trace("Handling MySQL handshake \(handshakeRequest)")
assert(handshakeRequest.capabilities.contains(.CLIENT_PROTOCOL_41), "Client protocol 4.1 required")
self.serverCapabilities = handshakeRequest.capabilities
if let tlsConfiguration = state.tlsConfiguration, handshakeRequest.capabilities.contains(.CLIENT_SSL) {
var capabilities = MySQLProtocol.CapabilityFlags.clientDefault
capabilities.insert(.CLIENT_SSL)
let sslRequest = MySQLProtocol.SSLRequest(
capabilities: capabilities,
maxPacketSize: 0,
characterSet: .utf8mb4
)
let promise = context.channel.eventLoop.makePromise(of: Void.self)
try context.write(self.wrapOutboundOut(.encode(sslRequest, capabilities: [])), promise: promise)
context.flush()
let sslContext = try NIOSSLContext(configuration: tlsConfiguration)
let handler = try NIOSSLClientHandler(context: sslContext, serverHostname: nil)
promise.futureResult.flatMap {
return context.channel.pipeline.addHandler(handler, position: .first).flatMapThrowing {
try self.writeHandshakeResponse(context: context, handshakeRequest: handshakeRequest, state: state, isTLS: true)
}
}.whenFailure { error in
state.done.fail(error)
}
} else {
try self.writeHandshakeResponse(context: context, handshakeRequest: handshakeRequest, state: state, isTLS: false)
}
}
func writeHandshakeResponse(
context: ChannelHandlerContext,
handshakeRequest: MySQLProtocol.HandshakeV10,
state: HandshakeState,
isTLS: Bool
) throws {
struct SemanticVersion {
let major: Int
let minor: Int
let patch: Int
init?<S>(string: S)
where S: StringProtocol
{
let parts = string.split(separator: ".")
guard parts.count == 3 else {
return nil
}
guard let major = Int(parts[0]), let minor = Int(parts[1]), let patch = Int(parts[2]) else {
return nil
}
self.major = major
self.minor = minor
self.patch = patch
}
}
let versionString = handshakeRequest.serverVersion.split(separator: "-")[0]
if let version = SemanticVersion(string: versionString) {
if !handshakeRequest.serverVersion.contains("MariaDB") {
switch (version.major, version.minor) {
case (8..., _):
// >= 8.0
break
case (5..., 7...):
// >= 5.7
break
default:
self.logger.error("Unsupported MySQL version: \(handshakeRequest.serverVersion)")
self.logger.info("MySQL 5.7 or higher is required")
}
}
} else {
self.logger.error("Unrecognized MySQL version: \(handshakeRequest.serverVersion)")
}
guard handshakeRequest.capabilities.contains(.CLIENT_SECURE_CONNECTION) else {
throw MySQLError.unsupportedServer(message: "Pre-4.1 auth protocol is not supported or safe.")
}
guard let authPluginName = handshakeRequest.authPluginName else {
throw MySQLError.unsupportedAuthPlugin(name: "<none>")
}
var password = ByteBufferAllocator().buffer(capacity: 0)
if let passwordString = state.password {
password.writeString(passwordString)
}
self.logger.trace("Writing handshake response with auth plugin: \(authPluginName) tls: \(isTLS)")
let hash: ByteBuffer
switch authPluginName {
case "caching_sha2_password":
let seed = handshakeRequest.authPluginData
hash = xor(sha256(password), sha256(sha256(sha256(password)), seed))
case "mysql_native_password":
var copy = handshakeRequest.authPluginData
guard let salt = copy.readSlice(length: 20) else {
throw MySQLError.protocolError
}
hash = xor(sha1(salt, sha1(sha1(password))), sha1(password))
default:
throw MySQLError.unsupportedAuthPlugin(name: authPluginName)
}
self.state = .authenticating(.init(
authPluginName: authPluginName,
password: state.password,
isTLS: isTLS,
done: state.done
))
let res = MySQLPacket.HandshakeResponse41(
capabilities: .clientDefault,
maxPacketSize: 0,
characterSet: .utf8mb4,
username: state.username,
authResponse: hash,
database: state.database,
authPluginName: authPluginName
)
try context.write(self.wrapOutboundOut(.encode(res, capabilities: self.serverCapabilities!)), promise: nil)
context.flush()
}
func handleAuthentication(
context: ChannelHandlerContext,
packet: inout MySQLPacket,
state: AuthenticationState
) throws {
switch state.authPluginName {
case "caching_sha2_password":
guard !packet.isOK else {
self.state = .commandPhase
state.done.succeed(())
return
}
guard !packet.isError else {
let err = try packet.decode(MySQLProtocol.ERR_Packet.self, capabilities: self.serverCapabilities!)
throw MySQLError.server(err)
}
guard let status = packet.payload.readInteger(endianness: .little, as: UInt8.self) else {
throw MySQLError.protocolError
}
switch status {
case 0x01:
guard let name = packet.payload.readInteger(endianness: .little, as: UInt8.self) else {
throw MySQLError.protocolError
}
switch name {
case 0x04:
guard state.isTLS else {
throw MySQLError.secureConnectionRequired
}
var payload = ByteBufferAllocator().buffer(capacity: 0)
payload.writeNullTerminatedString(state.password ?? "")
context.write(self.wrapOutboundOut(MySQLPacket(payload: payload)), promise: nil)
context.flush()
default:
throw MySQLError.protocolError
}
default:
throw MySQLError.protocolError
}
case "mysql_native_password":
guard !packet.isError else {
let error = try packet.decode(MySQLProtocol.ERR_Packet.self, capabilities: self.serverCapabilities!)
throw MySQLError.server(error)
}
guard packet.isOK else {
throw MySQLError.protocolError
}
self.state = .commandPhase
state.done.succeed(())
default:
throw MySQLError.unsupportedAuthPlugin(name: state.authPluginName)
}
}
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
let command = self.unwrapOutboundIn(data)
self.queue.append(command)
self.sendEnqueuedCommandIfReady(context: context)
promise?.succeed(())
}
func sendEnqueuedCommandIfReady(context: ChannelHandlerContext) {
guard case .ready = self.commandState else {
return
}
guard let command = self.queue.first else {
return
}
self.commandState = .busy
// send initial
do {
self.sequence.current = nil
let commandState = try command.handler.activate(capabilities: self.serverCapabilities!)
self.handleCommandState(context: context, commandState)
} catch {
self.queue.removeFirst()
self.commandState = .ready
command.promise.fail(error)
self.sendEnqueuedCommandIfReady(context: context)
}
}
func handleCommandState(context: ChannelHandlerContext, _ commandState: MySQLCommandState) {
if commandState.resetSequence {
self.sequence.reset()
}
if !commandState.response.isEmpty {
for packet in commandState.response {
context.write(self.wrapOutboundOut(packet), promise: nil)
}
context.flush()
}
if commandState.done {
let current = self.queue.removeFirst()
self.commandState = .ready
if let error = commandState.error {
current.promise.fail(error)
} else {
current.promise.succeed(())
}
self.sendEnqueuedCommandIfReady(context: context)
}
}
func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) {
do {
try self._close(context: context, mode: mode, promise: promise)
} catch {
self.errorCaught(context: context, error: error)
}
}
private func _close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) throws {
self.sequence.reset()
let quit = MySQLProtocol.COM_QUIT()
try context.write(self.wrapOutboundOut(.encode(quit, capabilities: self.serverCapabilities!)), promise: nil)
context.flush()
if let promise = promise {
// we need to do some error mapping here, so create a new promise
let p = context.eventLoop.makePromise(of: Void.self)
// forward the close request with our new promise
context.close(mode: mode, promise: p)
// forward close future results based on whether
// the close was successful
p.futureResult.whenSuccess { promise.succeed(()) }
p.futureResult.whenFailure { error in
if
let sslError = error as? NIOSSLError,
case .uncleanShutdown = sslError,
self.queue.isEmpty
{
// we can ignore unclear shutdown errors
// since no requests are pending
promise.succeed(())
} else {
promise.fail(error)
}
}
} else {
// no close promise anyway, just forward request
context.close(mode: mode, promise: nil)
}
}
func channelInactive(context: ChannelHandlerContext) {
while let next = self.queue.popLast() {
next.promise.fail(MySQLError.closed)
}
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
switch self.state {
case .handshake(let state):
state.done.fail(error)
case .authenticating(let state):
state.done.fail(error)
case .commandPhase:
if let current = self.queue.first {
self.queue.removeFirst()
current.promise.fail(error)
}
}
}
}