-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
conn.go
2325 lines (2152 loc) · 73.9 KB
/
conn.go
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// 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/.
// 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.
package server
import (
"bytes"
"context"
"crypto/tls"
"encoding/binary"
goerr "errors"
"fmt"
"io"
"net"
"runtime"
"runtime/pprof"
"runtime/trace"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/opentracing/opentracing-go"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/parser"
"github.com/pingcap/parser/ast"
"github.com/pingcap/parser/auth"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/parser/terror"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/errno"
"github.com/pingcap/tidb/executor"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/metrics"
plannercore "github.com/pingcap/tidb/planner/core"
"github.com/pingcap/tidb/plugin"
"github.com/pingcap/tidb/privilege"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/sessionctx/variable"
storeerr "github.com/pingcap/tidb/store/driver/error"
"github.com/pingcap/tidb/tablecodec"
tidbutil "github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/arena"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/execdetails"
"github.com/pingcap/tidb/util/hack"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/memory"
"github.com/prometheus/client_golang/prometheus"
"github.com/tikv/client-go/v2/util"
"go.uber.org/zap"
)
const (
connStatusDispatching int32 = iota
connStatusReading
connStatusShutdown // Closed by server.
connStatusWaitShutdown // Notified by server to close.
)
var (
queryTotalCountOk = [...]prometheus.Counter{
mysql.ComSleep: metrics.QueryTotalCounter.WithLabelValues("Sleep", "OK"),
mysql.ComQuit: metrics.QueryTotalCounter.WithLabelValues("Quit", "OK"),
mysql.ComInitDB: metrics.QueryTotalCounter.WithLabelValues("InitDB", "OK"),
mysql.ComQuery: metrics.QueryTotalCounter.WithLabelValues("Query", "OK"),
mysql.ComPing: metrics.QueryTotalCounter.WithLabelValues("Ping", "OK"),
mysql.ComFieldList: metrics.QueryTotalCounter.WithLabelValues("FieldList", "OK"),
mysql.ComStmtPrepare: metrics.QueryTotalCounter.WithLabelValues("StmtPrepare", "OK"),
mysql.ComStmtExecute: metrics.QueryTotalCounter.WithLabelValues("StmtExecute", "OK"),
mysql.ComStmtFetch: metrics.QueryTotalCounter.WithLabelValues("StmtFetch", "OK"),
mysql.ComStmtClose: metrics.QueryTotalCounter.WithLabelValues("StmtClose", "OK"),
mysql.ComStmtSendLongData: metrics.QueryTotalCounter.WithLabelValues("StmtSendLongData", "OK"),
mysql.ComStmtReset: metrics.QueryTotalCounter.WithLabelValues("StmtReset", "OK"),
mysql.ComSetOption: metrics.QueryTotalCounter.WithLabelValues("SetOption", "OK"),
}
queryTotalCountErr = [...]prometheus.Counter{
mysql.ComSleep: metrics.QueryTotalCounter.WithLabelValues("Sleep", "Error"),
mysql.ComQuit: metrics.QueryTotalCounter.WithLabelValues("Quit", "Error"),
mysql.ComInitDB: metrics.QueryTotalCounter.WithLabelValues("InitDB", "Error"),
mysql.ComQuery: metrics.QueryTotalCounter.WithLabelValues("Query", "Error"),
mysql.ComPing: metrics.QueryTotalCounter.WithLabelValues("Ping", "Error"),
mysql.ComFieldList: metrics.QueryTotalCounter.WithLabelValues("FieldList", "Error"),
mysql.ComStmtPrepare: metrics.QueryTotalCounter.WithLabelValues("StmtPrepare", "Error"),
mysql.ComStmtExecute: metrics.QueryTotalCounter.WithLabelValues("StmtExecute", "Error"),
mysql.ComStmtFetch: metrics.QueryTotalCounter.WithLabelValues("StmtFetch", "Error"),
mysql.ComStmtClose: metrics.QueryTotalCounter.WithLabelValues("StmtClose", "Error"),
mysql.ComStmtSendLongData: metrics.QueryTotalCounter.WithLabelValues("StmtSendLongData", "Error"),
mysql.ComStmtReset: metrics.QueryTotalCounter.WithLabelValues("StmtReset", "Error"),
mysql.ComSetOption: metrics.QueryTotalCounter.WithLabelValues("SetOption", "Error"),
}
queryDurationHistogramUse = metrics.QueryDurationHistogram.WithLabelValues("Use")
queryDurationHistogramShow = metrics.QueryDurationHistogram.WithLabelValues("Show")
queryDurationHistogramBegin = metrics.QueryDurationHistogram.WithLabelValues("Begin")
queryDurationHistogramCommit = metrics.QueryDurationHistogram.WithLabelValues("Commit")
queryDurationHistogramRollback = metrics.QueryDurationHistogram.WithLabelValues("Rollback")
queryDurationHistogramInsert = metrics.QueryDurationHistogram.WithLabelValues("Insert")
queryDurationHistogramReplace = metrics.QueryDurationHistogram.WithLabelValues("Replace")
queryDurationHistogramDelete = metrics.QueryDurationHistogram.WithLabelValues("Delete")
queryDurationHistogramUpdate = metrics.QueryDurationHistogram.WithLabelValues("Update")
queryDurationHistogramSelect = metrics.QueryDurationHistogram.WithLabelValues("Select")
queryDurationHistogramExecute = metrics.QueryDurationHistogram.WithLabelValues("Execute")
queryDurationHistogramSet = metrics.QueryDurationHistogram.WithLabelValues("Set")
queryDurationHistogramGeneral = metrics.QueryDurationHistogram.WithLabelValues(metrics.LblGeneral)
disconnectNormal = metrics.DisconnectionCounter.WithLabelValues(metrics.LblOK)
disconnectByClientWithError = metrics.DisconnectionCounter.WithLabelValues(metrics.LblError)
disconnectErrorUndetermined = metrics.DisconnectionCounter.WithLabelValues("undetermined")
connIdleDurationHistogramNotInTxn = metrics.ConnIdleDurationHistogram.WithLabelValues("0")
connIdleDurationHistogramInTxn = metrics.ConnIdleDurationHistogram.WithLabelValues("1")
)
// newClientConn creates a *clientConn object.
func newClientConn(s *Server) *clientConn {
return &clientConn{
server: s,
connectionID: s.globalConnID.NextID(),
collation: mysql.DefaultCollationID,
alloc: arena.NewAllocator(32 * 1024),
status: connStatusDispatching,
lastActive: time.Now(),
authPlugin: mysql.AuthNativePassword,
}
}
// clientConn represents a connection between server and client, it maintains connection specific state,
// handles client query.
type clientConn struct {
pkt *packetIO // a helper to read and write data in packet format.
bufReadConn *bufferedReadConn // a buffered-read net.Conn or buffered-read tls.Conn.
tlsConn *tls.Conn // TLS connection, nil if not TLS.
server *Server // a reference of server instance.
capability uint32 // client capability affects the way server handles client request.
connectionID uint64 // atomically allocated by a global variable, unique in process scope.
user string // user of the client.
dbname string // default database name.
salt []byte // random bytes used for authentication.
alloc arena.Allocator // an memory allocator for reducing memory allocation.
lastPacket []byte // latest sql query string, currently used for logging error.
ctx *TiDBContext // an interface to execute sql statements.
attrs map[string]string // attributes parsed from client handshake response, not used for now.
peerHost string // peer host
peerPort string // peer port
status int32 // dispatching/reading/shutdown/waitshutdown
lastCode uint16 // last error code
collation uint8 // collation used by client, may be different from the collation used by database.
lastActive time.Time // last active time
authPlugin string // default authentication plugin
isUnixSocket bool // connection is Unix Socket file
// mu is used for cancelling the execution of current transaction.
mu struct {
sync.RWMutex
cancelFunc context.CancelFunc
}
}
func (cc *clientConn) String() string {
collationStr := mysql.Collations[cc.collation]
return fmt.Sprintf("id:%d, addr:%s status:%b, collation:%s, user:%s",
cc.connectionID, cc.bufReadConn.RemoteAddr(), cc.ctx.Status(), collationStr, cc.user,
)
}
// authSwitchRequest is used by the server to ask the client to switch to a different authentication
// plugin. MySQL 8.0 libmysqlclient based clients by default always try `caching_sha2_password`, even
// when the server advertises the its default to be `mysql_native_password`. In addition to this switching
// may be needed on a per user basis as the authentication method is set per user.
// https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchRequest
// https://bugs.mysql.com/bug.php?id=93044
func (cc *clientConn) authSwitchRequest(ctx context.Context, plugin string) ([]byte, error) {
enclen := 1 + len(plugin) + 1 + len(cc.salt) + 1
data := cc.alloc.AllocWithLen(4, enclen)
data = append(data, mysql.AuthSwitchRequest) // switch request
data = append(data, []byte(plugin)...)
data = append(data, byte(0x00)) // requires null
data = append(data, cc.salt...)
data = append(data, 0)
err := cc.writePacket(data)
if err != nil {
logutil.Logger(ctx).Debug("write response to client failed", zap.Error(err))
return nil, err
}
err = cc.flush(ctx)
if err != nil {
logutil.Logger(ctx).Debug("flush response to client failed", zap.Error(err))
return nil, err
}
resp, err := cc.readPacket()
if err != nil {
err = errors.SuspendStack(err)
if errors.Cause(err) == io.EOF {
logutil.Logger(ctx).Warn("authSwitchRequest response fail due to connection has be closed by client-side")
} else {
logutil.Logger(ctx).Warn("authSwitchRequest response fail", zap.Error(err))
}
return nil, err
}
cc.authPlugin = plugin
return resp, nil
}
// handshake works like TCP handshake, but in a higher level, it first writes initial packet to client,
// during handshake, client and server negotiate compatible features and do authentication.
// After handshake, client can send sql query to server.
func (cc *clientConn) handshake(ctx context.Context) error {
if err := cc.writeInitialHandshake(ctx); err != nil {
if errors.Cause(err) == io.EOF {
logutil.Logger(ctx).Debug("Could not send handshake due to connection has be closed by client-side")
} else {
logutil.Logger(ctx).Debug("Write init handshake to client fail", zap.Error(errors.SuspendStack(err)))
}
return err
}
if err := cc.readOptionalSSLRequestAndHandshakeResponse(ctx); err != nil {
err1 := cc.writeError(ctx, err)
if err1 != nil {
logutil.Logger(ctx).Debug("writeError failed", zap.Error(err1))
}
return err
}
// MySQL supports an "init_connect" query, which can be run on initial connection.
// The query must return a non-error or the client is disconnected.
if err := cc.initConnect(ctx); err != nil {
logutil.Logger(ctx).Warn("init_connect failed", zap.Error(err))
initErr := errNewAbortingConnection.FastGenByArgs(cc.connectionID, "unconnected", cc.user, cc.peerHost, "init_connect command failed")
if err1 := cc.writeError(ctx, initErr); err1 != nil {
terror.Log(err1)
}
return initErr
}
data := cc.alloc.AllocWithLen(4, 32)
data = append(data, mysql.OKHeader)
data = append(data, 0, 0)
if cc.capability&mysql.ClientProtocol41 > 0 {
data = dumpUint16(data, mysql.ServerStatusAutocommit)
data = append(data, 0, 0)
}
err := cc.writePacket(data)
cc.pkt.sequence = 0
if err != nil {
err = errors.SuspendStack(err)
logutil.Logger(ctx).Debug("write response to client failed", zap.Error(err))
return err
}
err = cc.flush(ctx)
if err != nil {
err = errors.SuspendStack(err)
logutil.Logger(ctx).Debug("flush response to client failed", zap.Error(err))
return err
}
return err
}
func (cc *clientConn) Close() error {
cc.server.rwlock.Lock()
delete(cc.server.clients, cc.connectionID)
connections := len(cc.server.clients)
cc.server.rwlock.Unlock()
return closeConn(cc, connections)
}
func closeConn(cc *clientConn, connections int) error {
metrics.ConnGauge.Set(float64(connections))
err := cc.bufReadConn.Close()
terror.Log(err)
if cc.ctx != nil {
return cc.ctx.Close()
}
return nil
}
func (cc *clientConn) closeWithoutLock() error {
delete(cc.server.clients, cc.connectionID)
return closeConn(cc, len(cc.server.clients))
}
// writeInitialHandshake sends server version, connection ID, server capability, collation, server status
// and auth salt to the client.
func (cc *clientConn) writeInitialHandshake(ctx context.Context) error {
data := make([]byte, 4, 128)
// min version 10
data = append(data, 10)
// server version[00]
data = append(data, mysql.ServerVersion...)
data = append(data, 0)
// connection id
data = append(data, byte(cc.connectionID), byte(cc.connectionID>>8), byte(cc.connectionID>>16), byte(cc.connectionID>>24))
// auth-plugin-data-part-1
data = append(data, cc.salt[0:8]...)
// filler [00]
data = append(data, 0)
// capability flag lower 2 bytes, using default capability here
data = append(data, byte(cc.server.capability), byte(cc.server.capability>>8))
// charset
if cc.collation == 0 {
cc.collation = uint8(mysql.DefaultCollationID)
}
data = append(data, cc.collation)
// status
data = dumpUint16(data, mysql.ServerStatusAutocommit)
// below 13 byte may not be used
// capability flag upper 2 bytes, using default capability here
data = append(data, byte(cc.server.capability>>16), byte(cc.server.capability>>24))
// length of auth-plugin-data
data = append(data, byte(len(cc.salt)+1))
// reserved 10 [00]
data = append(data, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
// auth-plugin-data-part-2
data = append(data, cc.salt[8:]...)
data = append(data, 0)
// auth-plugin name
if cc.ctx == nil {
err := cc.openSession()
if err != nil {
return err
}
}
defAuthPlugin, err := variable.GetGlobalSystemVar(cc.ctx.GetSessionVars(), variable.DefaultAuthPlugin)
if err != nil {
return err
}
cc.authPlugin = defAuthPlugin
data = append(data, []byte(defAuthPlugin)...)
// Close the session to force this to be re-opened after we parse the response. This is needed
// to ensure we use the collation and client flags from the response for the session.
err = cc.ctx.Close()
if err != nil {
return err
}
cc.ctx = nil
data = append(data, 0)
err = cc.writePacket(data)
if err != nil {
return err
}
return cc.flush(ctx)
}
func (cc *clientConn) readPacket() ([]byte, error) {
return cc.pkt.readPacket()
}
func (cc *clientConn) writePacket(data []byte) error {
failpoint.Inject("FakeClientConn", func() {
if cc.pkt == nil {
failpoint.Return(nil)
}
})
return cc.pkt.writePacket(data)
}
// getSessionVarsWaitTimeout get session variable wait_timeout
func (cc *clientConn) getSessionVarsWaitTimeout(ctx context.Context) uint64 {
valStr, exists := cc.ctx.GetSessionVars().GetSystemVar(variable.WaitTimeout)
if !exists {
return variable.DefWaitTimeout
}
waitTimeout, err := strconv.ParseUint(valStr, 10, 64)
if err != nil {
logutil.Logger(ctx).Warn("get sysval wait_timeout failed, use default value", zap.Error(err))
// if get waitTimeout error, use default value
return variable.DefWaitTimeout
}
return waitTimeout
}
type handshakeResponse41 struct {
Capability uint32
Collation uint8
User string
DBName string
Auth []byte
AuthPlugin string
Attrs map[string]string
}
// parseOldHandshakeResponseHeader parses the old version handshake header HandshakeResponse320
func parseOldHandshakeResponseHeader(ctx context.Context, packet *handshakeResponse41, data []byte) (parsedBytes int, err error) {
// Ensure there are enough data to read:
// https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::HandshakeResponse320
logutil.Logger(ctx).Debug("try to parse hanshake response as Protocol::HandshakeResponse320", zap.ByteString("packetData", data))
if len(data) < 2+3 {
logutil.Logger(ctx).Error("got malformed handshake response", zap.ByteString("packetData", data))
return 0, mysql.ErrMalformPacket
}
offset := 0
// capability
capability := binary.LittleEndian.Uint16(data[:2])
packet.Capability = uint32(capability)
// be compatible with Protocol::HandshakeResponse41
packet.Capability |= mysql.ClientProtocol41
offset += 2
// skip max packet size
offset += 3
// usa default CharsetID
packet.Collation = mysql.CollationNames["utf8mb4_general_ci"]
return offset, nil
}
// parseOldHandshakeResponseBody parse the HandshakeResponse for Protocol::HandshakeResponse320 (except the common header part).
func parseOldHandshakeResponseBody(ctx context.Context, packet *handshakeResponse41, data []byte, offset int) (err error) {
defer func() {
// Check malformat packet cause out of range is disgusting, but don't panic!
if r := recover(); r != nil {
logutil.Logger(ctx).Error("handshake panic", zap.ByteString("packetData", data), zap.Stack("stack"))
err = mysql.ErrMalformPacket
}
}()
// user name
packet.User = string(data[offset : offset+bytes.IndexByte(data[offset:], 0)])
offset += len(packet.User) + 1
if packet.Capability&mysql.ClientConnectWithDB > 0 {
if len(data[offset:]) > 0 {
idx := bytes.IndexByte(data[offset:], 0)
packet.DBName = string(data[offset : offset+idx])
offset = offset + idx + 1
}
if len(data[offset:]) > 0 {
packet.Auth = data[offset : offset+bytes.IndexByte(data[offset:], 0)]
}
} else {
packet.Auth = data[offset : offset+bytes.IndexByte(data[offset:], 0)]
}
return nil
}
// parseHandshakeResponseHeader parses the common header of SSLRequest and HandshakeResponse41.
func parseHandshakeResponseHeader(ctx context.Context, packet *handshakeResponse41, data []byte) (parsedBytes int, err error) {
// Ensure there are enough data to read:
// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest
if len(data) < 4+4+1+23 {
logutil.Logger(ctx).Error("got malformed handshake response", zap.ByteString("packetData", data))
return 0, mysql.ErrMalformPacket
}
offset := 0
// capability
capability := binary.LittleEndian.Uint32(data[:4])
packet.Capability = capability
offset += 4
// skip max packet size
offset += 4
// charset, skip, if you want to use another charset, use set names
packet.Collation = data[offset]
offset++
// skip reserved 23[00]
offset += 23
return offset, nil
}
// parseHandshakeResponseBody parse the HandshakeResponse (except the common header part).
func parseHandshakeResponseBody(ctx context.Context, packet *handshakeResponse41, data []byte, offset int) (err error) {
defer func() {
// Check malformat packet cause out of range is disgusting, but don't panic!
if r := recover(); r != nil {
logutil.Logger(ctx).Error("handshake panic", zap.ByteString("packetData", data))
err = mysql.ErrMalformPacket
}
}()
// user name
packet.User = string(data[offset : offset+bytes.IndexByte(data[offset:], 0)])
offset += len(packet.User) + 1
if packet.Capability&mysql.ClientPluginAuthLenencClientData > 0 {
// MySQL client sets the wrong capability, it will set this bit even server doesn't
// support ClientPluginAuthLenencClientData.
// https://github.com/mysql/mysql-server/blob/5.7/sql-common/client.c#L3478
if data[offset] == 0x1 { // No auth data
offset += 2
} else {
num, null, off := parseLengthEncodedInt(data[offset:])
offset += off
if !null {
packet.Auth = data[offset : offset+int(num)]
offset += int(num)
}
}
} else if packet.Capability&mysql.ClientSecureConnection > 0 {
// auth length and auth
authLen := int(data[offset])
offset++
packet.Auth = data[offset : offset+authLen]
offset += authLen
} else {
packet.Auth = data[offset : offset+bytes.IndexByte(data[offset:], 0)]
offset += len(packet.Auth) + 1
}
if packet.Capability&mysql.ClientConnectWithDB > 0 {
if len(data[offset:]) > 0 {
idx := bytes.IndexByte(data[offset:], 0)
packet.DBName = string(data[offset : offset+idx])
offset += idx + 1
}
}
if packet.Capability&mysql.ClientPluginAuth > 0 {
idx := bytes.IndexByte(data[offset:], 0)
s := offset
f := offset + idx
if s < f { // handle unexpected bad packets
packet.AuthPlugin = string(data[s:f])
}
offset += idx + 1
}
if packet.Capability&mysql.ClientConnectAtts > 0 {
if len(data[offset:]) == 0 {
// Defend some ill-formated packet, connection attribute is not important and can be ignored.
return nil
}
if num, null, off := parseLengthEncodedInt(data[offset:]); !null {
offset += off
row := data[offset : offset+int(num)]
attrs, err := parseAttrs(row)
if err != nil {
logutil.Logger(ctx).Warn("parse attrs failed", zap.Error(err))
return nil
}
packet.Attrs = attrs
}
}
return nil
}
func parseAttrs(data []byte) (map[string]string, error) {
attrs := make(map[string]string)
pos := 0
for pos < len(data) {
key, _, off, err := parseLengthEncodedBytes(data[pos:])
if err != nil {
return attrs, err
}
pos += off
value, _, off, err := parseLengthEncodedBytes(data[pos:])
if err != nil {
return attrs, err
}
pos += off
attrs[string(key)] = string(value)
}
return attrs, nil
}
func (cc *clientConn) readOptionalSSLRequestAndHandshakeResponse(ctx context.Context) error {
// Read a packet. It may be a SSLRequest or HandshakeResponse.
data, err := cc.readPacket()
if err != nil {
err = errors.SuspendStack(err)
if errors.Cause(err) == io.EOF {
logutil.Logger(ctx).Debug("wait handshake response fail due to connection has be closed by client-side")
} else {
logutil.Logger(ctx).Debug("wait handshake response fail", zap.Error(err))
}
return err
}
isOldVersion := false
var resp handshakeResponse41
var pos int
if len(data) < 2 {
logutil.Logger(ctx).Error("got malformed handshake response", zap.ByteString("packetData", data))
return mysql.ErrMalformPacket
}
capability := uint32(binary.LittleEndian.Uint16(data[:2]))
if capability&mysql.ClientProtocol41 > 0 {
pos, err = parseHandshakeResponseHeader(ctx, &resp, data)
} else {
pos, err = parseOldHandshakeResponseHeader(ctx, &resp, data)
isOldVersion = true
}
if err != nil {
terror.Log(err)
return err
}
if resp.Capability&mysql.ClientSSL > 0 {
tlsConfig := (*tls.Config)(atomic.LoadPointer(&cc.server.tlsConfig))
if tlsConfig != nil {
// The packet is a SSLRequest, let's switch to TLS.
if err = cc.upgradeToTLS(tlsConfig); err != nil {
return err
}
// Read the following HandshakeResponse packet.
data, err = cc.readPacket()
if err != nil {
logutil.Logger(ctx).Warn("read handshake response failure after upgrade to TLS", zap.Error(err))
return err
}
if isOldVersion {
pos, err = parseOldHandshakeResponseHeader(ctx, &resp, data)
} else {
pos, err = parseHandshakeResponseHeader(ctx, &resp, data)
}
if err != nil {
terror.Log(err)
return err
}
}
} else if config.GetGlobalConfig().Security.RequireSecureTransport {
err := errSecureTransportRequired.FastGenByArgs()
terror.Log(err)
return err
}
// Read the remaining part of the packet.
if isOldVersion {
err = parseOldHandshakeResponseBody(ctx, &resp, data, pos)
} else {
err = parseHandshakeResponseBody(ctx, &resp, data, pos)
}
if err != nil {
terror.Log(err)
return err
}
cc.capability = resp.Capability & cc.server.capability
cc.user = resp.User
cc.dbname = resp.DBName
cc.collation = resp.Collation
cc.attrs = resp.Attrs
newAuth, err := cc.checkAuthPlugin(ctx, &resp.AuthPlugin)
if err != nil {
logutil.Logger(ctx).Warn("failed to check the user authplugin", zap.Error(err))
}
if len(newAuth) > 0 {
resp.Auth = newAuth
}
switch resp.AuthPlugin {
case mysql.AuthCachingSha2Password:
resp.Auth, err = cc.authSha(ctx)
if err != nil {
return err
}
case mysql.AuthNativePassword:
default:
return errors.New("Unknown auth plugin")
}
err = cc.openSessionAndDoAuth(resp.Auth)
if err != nil {
logutil.Logger(ctx).Warn("open new session or authentication failure", zap.Error(err))
}
return err
}
func (cc *clientConn) authSha(ctx context.Context) ([]byte, error) {
const (
ShaCommand = 1
RequestRsaPubKey = 2
FastAuthOk = 3
FastAuthFail = 4
)
err := cc.writePacket([]byte{0, 0, 0, 0, ShaCommand, FastAuthFail})
if err != nil {
logutil.Logger(ctx).Error("authSha packet write failed", zap.Error(err))
return nil, err
}
err = cc.flush(ctx)
if err != nil {
logutil.Logger(ctx).Error("authSha packet flush failed", zap.Error(err))
return nil, err
}
data, err := cc.readPacket()
if err != nil {
logutil.Logger(ctx).Error("authSha packet read failed", zap.Error(err))
return nil, err
}
return bytes.Trim(data, "\x00"), nil
}
func (cc *clientConn) SessionStatusToString() string {
status := cc.ctx.Status()
inTxn, autoCommit := 0, 0
if status&mysql.ServerStatusInTrans > 0 {
inTxn = 1
}
if status&mysql.ServerStatusAutocommit > 0 {
autoCommit = 1
}
return fmt.Sprintf("inTxn:%d, autocommit:%d",
inTxn, autoCommit,
)
}
func (cc *clientConn) openSession() error {
var tlsStatePtr *tls.ConnectionState
if cc.tlsConn != nil {
tlsState := cc.tlsConn.ConnectionState()
tlsStatePtr = &tlsState
}
var err error
cc.ctx, err = cc.server.driver.OpenCtx(cc.connectionID, cc.capability, cc.collation, cc.dbname, tlsStatePtr)
if err != nil {
return err
}
err = cc.server.checkConnectionCount()
if err != nil {
return err
}
return nil
}
func (cc *clientConn) openSessionAndDoAuth(authData []byte) error {
// Open a context unless this was done before.
if cc.ctx == nil {
err := cc.openSession()
if err != nil {
return err
}
}
hasPassword := "YES"
if len(authData) == 0 {
hasPassword = "NO"
}
host, port, err := cc.PeerHost(hasPassword)
if err != nil {
return err
}
if !cc.ctx.Auth(&auth.UserIdentity{Username: cc.user, Hostname: host}, authData, cc.salt) {
return errAccessDenied.FastGenByArgs(cc.user, host, hasPassword)
}
cc.ctx.SetPort(port)
if cc.dbname != "" {
err = cc.useDB(context.Background(), cc.dbname)
if err != nil {
return err
}
}
cc.ctx.SetSessionManager(cc.server)
return nil
}
// Check if the Authentication Plugin of the server, client and user configuration matches
func (cc *clientConn) checkAuthPlugin(ctx context.Context, authPlugin *string) ([]byte, error) {
// Open a context unless this was done before.
if cc.ctx == nil {
err := cc.openSession()
if err != nil {
return nil, err
}
}
userplugin, err := cc.ctx.AuthPluginForUser(&auth.UserIdentity{Username: cc.user, Hostname: cc.peerHost})
if err != nil {
return nil, err
}
if len(userplugin) == 0 {
*authPlugin = mysql.AuthNativePassword
return nil, nil
}
// If the authentication method send by the server (cc.authPlugin) doesn't match
// the plugin configured for the user account in the mysql.user.plugin column
// or if the authentication method send by the server doesn't match the authentication
// method send by the client (*authPlugin) then we need to switch the authentication
// method to match the one configured for that specific user.
if (cc.authPlugin != userplugin) || (cc.authPlugin != *authPlugin) {
authData, err := cc.authSwitchRequest(ctx, userplugin)
if err != nil {
return nil, err
}
*authPlugin = userplugin
return authData, nil
}
return nil, nil
}
func (cc *clientConn) PeerHost(hasPassword string) (host, port string, err error) {
if len(cc.peerHost) > 0 {
return cc.peerHost, "", nil
}
host = variable.DefHostname
if cc.isUnixSocket {
cc.peerHost = host
return
}
addr := cc.bufReadConn.RemoteAddr().String()
host, port, err = net.SplitHostPort(addr)
if err != nil {
err = errAccessDenied.GenWithStackByArgs(cc.user, addr, hasPassword)
return
}
cc.peerHost = host
cc.peerPort = port
return
}
// skipInitConnect follows MySQL's rules of when init-connect should be skipped.
// In 5.7 it is any user with SUPER privilege, but in 8.0 it is:
// - SUPER or the CONNECTION_ADMIN dynamic privilege.
// - (additional exception) users with expired passwords (not yet supported)
// In TiDB CONNECTION_ADMIN is satisfied by SUPER, so we only need to check once.
func (cc *clientConn) skipInitConnect() bool {
checker := privilege.GetPrivilegeManager(cc.ctx.Session)
activeRoles := cc.ctx.GetSessionVars().ActiveRoles
return checker != nil && checker.RequestDynamicVerification(activeRoles, "CONNECTION_ADMIN", false)
}
// initConnect runs the initConnect SQL statement if it has been specified.
// The semantics are MySQL compatible.
func (cc *clientConn) initConnect(ctx context.Context) error {
val, err := cc.ctx.GetSessionVars().GlobalVarsAccessor.GetGlobalSysVar(variable.InitConnect)
if err != nil {
return err
}
if val == "" || cc.skipInitConnect() {
return nil
}
logutil.Logger(ctx).Debug("init_connect starting")
stmts, err := cc.ctx.Parse(ctx, val)
if err != nil {
return err
}
for _, stmt := range stmts {
rs, err := cc.ctx.ExecuteStmt(ctx, stmt)
if err != nil {
return err
}
// init_connect does not care about the results,
// but they need to be drained because of lazy loading.
if rs != nil {
req := rs.NewChunk()
for {
if err = rs.Next(ctx, req); err != nil {
return err
}
if req.NumRows() == 0 {
break
}
}
if err := rs.Close(); err != nil {
return err
}
}
}
logutil.Logger(ctx).Debug("init_connect complete")
return nil
}
// Run reads client query and writes query result to client in for loop, if there is a panic during query handling,
// it will be recovered and log the panic error.
// This function returns and the connection is closed if there is an IO error or there is a panic.
func (cc *clientConn) Run(ctx context.Context) {
const size = 4096
defer func() {
r := recover()
if r != nil {
buf := make([]byte, size)
stackSize := runtime.Stack(buf, false)
buf = buf[:stackSize]
logutil.Logger(ctx).Error("connection running loop panic",
zap.Stringer("lastSQL", getLastStmtInConn{cc}),
zap.String("err", fmt.Sprintf("%v", r)),
zap.String("stack", string(buf)),
)
err := cc.writeError(ctx, errors.New(fmt.Sprintf("%v", r)))
terror.Log(err)
metrics.PanicCounter.WithLabelValues(metrics.LabelSession).Inc()
}
if atomic.LoadInt32(&cc.status) != connStatusShutdown {
err := cc.Close()
terror.Log(err)
}
}()
// Usually, client connection status changes between [dispatching] <=> [reading].
// When some event happens, server may notify this client connection by setting
// the status to special values, for example: kill or graceful shutdown.
// The client connection would detect the events when it fails to change status
// by CAS operation, it would then take some actions accordingly.
for {
if !atomic.CompareAndSwapInt32(&cc.status, connStatusDispatching, connStatusReading) ||
// The judge below will not be hit by all means,
// But keep it stayed as a reminder and for the code reference for connStatusWaitShutdown.
atomic.LoadInt32(&cc.status) == connStatusWaitShutdown {
return
}
cc.alloc.Reset()
// close connection when idle time is more than wait_timeout
waitTimeout := cc.getSessionVarsWaitTimeout(ctx)
cc.pkt.setReadTimeout(time.Duration(waitTimeout) * time.Second)
start := time.Now()
data, err := cc.readPacket()
if err != nil {
if terror.ErrorNotEqual(err, io.EOF) {
if netErr, isNetErr := errors.Cause(err).(net.Error); isNetErr && netErr.Timeout() {
idleTime := time.Since(start)
logutil.Logger(ctx).Info("read packet timeout, close this connection",
zap.Duration("idle", idleTime),
zap.Uint64("waitTimeout", waitTimeout),
zap.Error(err),
)
} else {
errStack := errors.ErrorStack(err)
if !strings.Contains(errStack, "use of closed network connection") {
logutil.Logger(ctx).Warn("read packet failed, close this connection",
zap.Error(errors.SuspendStack(err)))
}
}
}
disconnectByClientWithError.Inc()
return
}
if !atomic.CompareAndSwapInt32(&cc.status, connStatusReading, connStatusDispatching) {
return
}
startTime := time.Now()
if err = cc.dispatch(ctx, data); err != nil {
cc.audit(plugin.Error) // tell the plugin API there was a dispatch error
if terror.ErrorEqual(err, io.EOF) {
cc.addMetrics(data[0], startTime, nil)
disconnectNormal.Inc()
return
} else if terror.ErrResultUndetermined.Equal(err) {
logutil.Logger(ctx).Error("result undetermined, close this connection", zap.Error(err))
disconnectErrorUndetermined.Inc()
return
} else if terror.ErrCritical.Equal(err) {
metrics.CriticalErrorCounter.Add(1)
logutil.Logger(ctx).Fatal("critical error, stop the server", zap.Error(err))
}
var txnMode string
if cc.ctx != nil {
txnMode = cc.ctx.GetSessionVars().GetReadableTxnMode()
}
metrics.ExecuteErrorCounter.WithLabelValues(metrics.ExecuteErrorToLabel(err)).Inc()
if storeerr.ErrLockAcquireFailAndNoWaitSet.Equal(err) {
logutil.Logger(ctx).Debug("Expected error for FOR UPDATE NOWAIT", zap.Error(err))
} else {