-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathpacketio.go
More file actions
581 lines (512 loc) · 15.3 KB
/
packetio.go
File metadata and controls
581 lines (512 loc) · 15.3 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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
// Copyright 2023 PingCAP, Inc.
// SPDX-License-Identifier: Apache-2.0
// The MIT License (MIT)
//
// Copyright (c) 2014 wandoulabs
// Copyright (c) 2014 siddontang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
package net
import (
"crypto/tls"
"io"
"net"
"sync"
"time"
"github.com/pingcap/tiproxy/lib/config"
"github.com/pingcap/tiproxy/lib/util/errors"
"github.com/pingcap/tiproxy/pkg/proxy/keepalive"
"github.com/pingcap/tiproxy/pkg/proxy/proxyprotocol"
"github.com/pingcap/tiproxy/pkg/util/bufio"
"go.uber.org/zap"
)
var (
ErrInvalidSequence = errors.New("invalid sequence")
)
var (
readerPool sync.Pool
writerPool sync.Pool
)
const (
DefaultConnBufferSize = 32 * 1024
)
// normalizeConnBufferSize keeps 0 as "use the default", so every caller in the
// packet/TLS stack derives buffer sizes from the same effective value.
func normalizeConnBufferSize(bufferSize int) int {
if bufferSize == 0 {
return DefaultConnBufferSize
}
return bufferSize
}
type rwStatus int
const (
rwNone rwStatus = iota
rwRead
rwWrite
)
// packetReadWriter acts like a net.Conn with read and write buffer.
type packetReadWriter interface {
net.Conn
// Peek / Discard / Flush are implemented by bufio.ReadWriter.
Peek(n int) ([]byte, error)
Discard(n int) (int, error)
Flush() error
DirectWrite(p []byte) (int, error)
ReadFrom(r io.Reader) (int64, error)
Proxy() *proxyprotocol.Proxy
ProxyAddr() net.Addr
TLSConnectionState() tls.ConnectionState
InBytes() uint64
OutBytes() uint64
IsPeerActive() bool
SetSequence(uint8)
Sequence() uint8
// ResetSequence is called before executing a command.
ResetSequence()
// BeginRW is called before reading or writing packets.
BeginRW(status rwStatus)
}
var _ packetReadWriter = (*basicReadWriter)(nil)
// basicReadWriter is used for raw connections.
type basicReadWriter struct {
net.Conn
*bufio.ReadWriter
inBytes uint64
outBytes uint64
sequence uint8
pooled bool
}
func getPooledReader(conn net.Conn, size int) *bufio.Reader {
if v := readerPool.Get(); v != nil {
if r := v.(*bufio.Reader); r.Size() == size {
r.Reset(conn)
return r
}
}
return bufio.NewReaderSize(conn, size)
}
func getPooledWriter(conn net.Conn, size int) *bufio.Writer {
if v := writerPool.Get(); v != nil {
if w := v.(*bufio.Writer); w.Size() == size {
w.Reset(conn)
return w
}
}
return bufio.NewWriterSize(conn, size)
}
func newBasicReadWriter(conn net.Conn, bufferSize int) *basicReadWriter {
bufferSize = normalizeConnBufferSize(bufferSize)
return &basicReadWriter{
Conn: conn,
ReadWriter: bufio.NewReadWriter(getPooledReader(conn, bufferSize), getPooledWriter(conn, bufferSize)),
pooled: true,
}
}
func (brw *basicReadWriter) Read(b []byte) (n int, err error) {
n, err = brw.ReadWriter.Read(b)
brw.inBytes += uint64(n)
return n, errors.WithStack(err)
}
func (brw *basicReadWriter) Write(p []byte) (int, error) {
n, err := brw.ReadWriter.Write(p)
brw.outBytes += uint64(n)
return n, errors.WithStack(err)
}
func (brw *basicReadWriter) ReadFrom(r io.Reader) (int64, error) {
n, err := brw.ReadWriter.ReadFrom(r)
brw.outBytes += uint64(n)
return n, errors.WithStack(err)
}
func (brw *basicReadWriter) DirectWrite(p []byte) (int, error) {
n, err := brw.Conn.Write(p)
brw.outBytes += uint64(n)
return n, errors.WithStack(err)
}
func (brw *basicReadWriter) SetSequence(sequence uint8) {
brw.sequence = sequence
}
func (brw *basicReadWriter) Sequence() uint8 {
return brw.sequence
}
func (brw *basicReadWriter) Proxy() *proxyprotocol.Proxy {
return nil
}
func (brw *basicReadWriter) ProxyAddr() net.Addr {
return brw.RemoteAddr()
}
func (brw *basicReadWriter) InBytes() uint64 {
return brw.inBytes
}
func (brw *basicReadWriter) OutBytes() uint64 {
return brw.outBytes
}
func (brw *basicReadWriter) BeginRW(rwStatus) {
}
func (brw *basicReadWriter) ResetSequence() {
brw.sequence = 0
}
func (brw *basicReadWriter) Free() {
if brw.pooled {
brw.pooled = false
brw.ReadWriter.Reader.Reset(nil)
brw.ReadWriter.Writer.Reset(nil)
readerPool.Put(brw.ReadWriter.Reader)
writerPool.Put(brw.ReadWriter.Writer)
}
}
func (brw *basicReadWriter) Close() error {
err := brw.Conn.Close()
brw.Free()
return err
}
func (brw *basicReadWriter) TLSConnectionState() tls.ConnectionState {
return tls.ConnectionState{}
}
// IsPeerActive checks if the peer connection is still active.
// If the backend disconnects, the client should also be disconnected (required by serverless).
// We have no other way than reading from the connection.
//
// This function cannot be called concurrently with other functions of packetReadWriter.
// This function normally costs 1ms, so don't call it too frequently.
// This function may incorrectly return true if the system is extremely slow.
func (brw *basicReadWriter) IsPeerActive() bool {
if err := brw.Conn.SetReadDeadline(time.Now().Add(time.Millisecond)); err != nil {
return false
}
active := true
if _, err := brw.ReadWriter.Peek(1); err != nil {
active = !errors.Is(err, io.EOF)
}
if err := brw.Conn.SetReadDeadline(time.Time{}); err != nil {
return false
}
return active
}
// ReadFull is used to replace io.ReadFull to erase boundary check, function calls and interface conversion.
// It is a hot path when many rows are returned.
func ReadFull(prw packetReadWriter, b []byte) error {
m := len(b)
for n := 0; n < m; {
nn, err := prw.Read(b[n:])
if err != nil {
return err
}
n += nn
}
return nil
}
type PacketIO interface {
ApplyOpts(opts ...PacketIOption)
LocalAddr() net.Addr
RemoteAddr() net.Addr
ResetSequence()
GetSequence() uint8
ReadPacket() (data []byte, err error)
WritePacket(data []byte, flush bool) (err error)
ForwardUntil(dest PacketIO, isEnd func(firstByte byte, firstPktLen int) (end, needData bool),
process func(response []byte) error) error
InBytes() uint64
OutBytes() uint64
InPackets() uint64
OutPackets() uint64
Flush() error
IsPeerActive() bool
SetKeepalive(cfg config.KeepAlive) error
LastKeepAlive() config.KeepAlive
GracefulClose() error
Close() error
// proxy protocol
EnableProxyClient(proxy *proxyprotocol.Proxy)
EnableProxyServer()
Proxy() *proxyprotocol.Proxy
ProxyAddr() net.Addr
// tls
ServerTLSHandshake(tlsConfig *tls.Config) (tls.ConnectionState, error)
ClientTLSHandshake(tlsConfig *tls.Config) error
TLSConnectionState() tls.ConnectionState
// compression
SetCompressionAlgorithm(algorithm CompressAlgorithm, zstdLevel int) error
}
// PacketIO is a helper to read and write sql and proxy protocol.
type packetIO struct {
lastKeepAlive config.KeepAlive
// TLS allocates another buffered layer after the handshake. Keep the
// normalized base connection buffer size here so the TLS layer can scale
// from the caller's setting instead of falling back to unrelated constants.
connBufferSize int
rawConn net.Conn
readWriter packetReadWriter
limitReader io.LimitedReader // reuse memory to reduce allocation
logger *zap.Logger
remoteAddr net.Addr
wrap error
header [4]byte // reuse memory to reduce allocation
readPacketLimit int
inPackets uint64
outPackets uint64
}
func NewPacketIO(conn net.Conn, lg *zap.Logger, bufferSize int, opts ...PacketIOption) *packetIO {
bufferSize = normalizeConnBufferSize(bufferSize)
p := &packetIO{
connBufferSize: bufferSize,
rawConn: conn,
logger: lg,
readWriter: newBasicReadWriter(conn, bufferSize),
}
p.ApplyOpts(opts...)
return p
}
func (p *packetIO) ApplyOpts(opts ...PacketIOption) {
for _, opt := range opts {
opt(p)
}
}
func (p *packetIO) wrapErr(err error) error {
return errors.Wrap(err, p.wrap)
}
func (p *packetIO) LocalAddr() net.Addr {
return p.readWriter.LocalAddr()
}
func (p *packetIO) RemoteAddr() net.Addr {
if p.remoteAddr != nil {
return p.remoteAddr
}
return p.readWriter.RemoteAddr()
}
func (p *packetIO) ProxyAddr() net.Addr {
return p.readWriter.ProxyAddr()
}
func (p *packetIO) ResetSequence() {
p.readWriter.ResetSequence()
}
// GetSequence is used in tests to assert that the sequences on the client and server are equal.
func (p *packetIO) GetSequence() uint8 {
return p.readWriter.Sequence()
}
// readOnePacket reads one packet and returns the data without header, whether there are more packets and error if any.
// If limit >= 0, it returns an error if the packet size exceeds the limit.
// The caller may read a trailing zero-length packet when the previous packet length equals MaxPayloadLen.
func (p *packetIO) readOnePacket(limit int) ([]byte, bool, error) {
if err := ReadFull(p.readWriter, p.header[:]); err != nil {
return nil, false, errors.Wrap(err, ErrReadConn)
}
sequence, pktSequence := p.header[3], p.readWriter.Sequence()
if sequence != pktSequence {
p.logger.Warn("sequence mismatch", zap.Uint8("expected", pktSequence), zap.Uint8("actual", sequence))
}
p.readWriter.SetSequence(sequence + 1)
length := int(p.header[0]) | int(p.header[1])<<8 | int(p.header[2])<<16
if limit >= 0 && length > limit {
return nil, false, errors.Wrapf(ErrPacketTooLarge, "packet size %d exceeds limit %d", length, limit)
}
data := make([]byte, length)
if err := ReadFull(p.readWriter, data); err != nil {
return nil, false, errors.Wrap(err, ErrReadConn)
}
p.inPackets++
return data, length == MaxPayloadLen, nil
}
// ReadPacket reads data and removes the header
func (p *packetIO) ReadPacket() (data []byte, err error) {
p.readWriter.BeginRW(rwRead)
checkPacketLimit := p.readPacketLimit > 0
remaining := p.readPacketLimit
for more := true; more; {
var buf []byte
limit := -1
if checkPacketLimit {
limit = remaining
}
buf, more, err = p.readOnePacket(limit)
if err != nil {
err = p.wrapErr(err)
return
}
if checkPacketLimit {
remaining -= len(buf)
if remaining < 0 {
err = p.wrapErr(errors.Wrapf(ErrPacketTooLarge, "packet size exceeds limit %d", p.readPacketLimit))
return
}
}
if data == nil {
data = buf
} else {
data = append(data, buf...)
}
}
return data, nil
}
func (p *packetIO) writeOnePacket(data []byte) (int, bool, error) {
more := false
length := len(data)
if length >= MaxPayloadLen {
// we need another packet, this is true even if
// the current packet is of len(MaxPayloadLen) exactly
length = MaxPayloadLen
more = true
}
sequence := p.readWriter.Sequence()
p.header[0] = byte(length)
p.header[1] = byte(length >> 8)
p.header[2] = byte(length >> 16)
p.header[3] = sequence
p.readWriter.SetSequence(sequence + 1)
if _, err := p.readWriter.Write(p.header[:]); err != nil {
return 0, more, errors.Wrap(err, ErrWriteConn)
}
if _, err := p.readWriter.Write(data[:length]); err != nil {
return 0, more, errors.Wrap(err, ErrWriteConn)
}
p.outPackets++
return length, more, nil
}
// WritePacket writes data without a header
func (p *packetIO) WritePacket(data []byte, flush bool) (err error) {
p.readWriter.BeginRW(rwWrite)
for more := true; more; {
var n int
n, more, err = p.writeOnePacket(data)
if err != nil {
err = p.wrapErr(err)
return
}
data = data[n:]
}
if flush {
return p.Flush()
}
return nil
}
func (p *packetIO) ForwardUntil(destIO PacketIO, isEnd func(firstByte byte, firstPktLen int) (end, needData bool),
process func(response []byte) error) error {
p.readWriter.BeginRW(rwRead)
dest, _ := destIO.(*packetIO)
// destIO is not packetIO in traffic replay.
if dest != nil {
dest.readWriter.BeginRW(rwWrite)
}
p.limitReader.R = p.readWriter
for {
header, err := p.readWriter.Peek(5)
if err != nil {
return p.wrapErr(errors.Wrap(errors.WithStack(err), ErrReadConn))
}
length := int(header[0]) | int(header[1])<<8 | int(header[2])<<16
end, needData := isEnd(header[4], length)
var data []byte
// Just call ReadFrom if the caller doesn't need the data, even if it's the last packet.
if (end && needData) || dest == nil {
// TODO: allocate a buffer from pool and return the buffer after `process`.
data, err = p.ReadPacket()
if err != nil {
return p.wrapErr(errors.Wrap(err, ErrReadConn))
}
if err := destIO.WritePacket(data, false); err != nil {
err = errors.Wrap(err, ErrWriteConn)
if dest != nil {
err = dest.wrapErr(err)
}
return err
}
} else {
for {
sequence, pktSequence := header[3], p.readWriter.Sequence()
if sequence != pktSequence {
p.logger.Warn("sequence mismatch", zap.Uint8("expected", pktSequence), zap.Uint8("actual", sequence))
}
p.readWriter.SetSequence(sequence + 1)
// Sequence may be different (e.g. with compression) so we can't just copy the data to the destination.
dest.readWriter.SetSequence(dest.readWriter.Sequence() + 1)
p.limitReader.N = int64(length + 4)
if _, err := dest.readWriter.ReadFrom(&p.limitReader); err != nil {
if errors.Is(err, bufio.ErrWriteFail) {
return dest.wrapErr(errors.Wrap(err, ErrWriteConn))
}
return p.wrapErr(errors.Wrap(err, ErrReadConn))
}
p.inPackets++
dest.outPackets++
// For large packets, continue.
if length < MaxPayloadLen {
break
}
if header, err = p.readWriter.Peek(4); err != nil {
return p.wrapErr(errors.Wrap(errors.WithStack(err), ErrReadConn))
}
length = int(header[0]) | int(header[1])<<8 | int(header[2])<<16
}
}
if end {
if process != nil {
// data == nil iff needData == false
return process(data)
}
return nil
}
}
}
func (p *packetIO) InBytes() uint64 {
return p.readWriter.InBytes()
}
func (p *packetIO) OutBytes() uint64 {
return p.readWriter.OutBytes()
}
func (p *packetIO) InPackets() uint64 {
return p.inPackets
}
func (p *packetIO) OutPackets() uint64 {
return p.outPackets
}
func (p *packetIO) Flush() error {
if err := p.readWriter.Flush(); err != nil {
return p.wrapErr(errors.Wrap(errors.WithStack(err), ErrFlushConn))
}
return nil
}
func (p *packetIO) IsPeerActive() bool {
return p.readWriter.IsPeerActive()
}
func (p *packetIO) SetKeepalive(cfg config.KeepAlive) error {
if cfg == p.lastKeepAlive {
return nil
}
p.lastKeepAlive = cfg
return keepalive.SetKeepalive(p.rawConn, cfg)
}
// LastKeepAlive is used for test.
func (p *packetIO) LastKeepAlive() config.KeepAlive {
return p.lastKeepAlive
}
func (p *packetIO) GracefulClose() error {
if err := p.readWriter.SetDeadline(time.Now()); err != nil && !errors.Is(err, net.ErrClosed) {
return err
}
return nil
}
func (p *packetIO) Close() error {
var errs []error
/*
TODO: flush when we want to smoothly exit
if err := p.Flush(); err != nil {
errs = append(errs, err)
}
*/
if err := p.readWriter.Close(); err != nil && !errors.Is(err, net.ErrClosed) {
errs = append(errs, errors.WithStack(err))
}
return p.wrapErr(errors.Collect(ErrCloseConn, errs...))
}