-
Notifications
You must be signed in to change notification settings - Fork 570
/
NativeProtocol.java
2168 lines (1767 loc) · 90.8 KB
/
NativeProtocol.java
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 (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 2.0, as published by the
* Free Software Foundation.
*
* This program is also distributed with certain software (including but not
* limited to OpenSSL) that is licensed under separate terms, as designated in a
* particular file or component or in included license documentation. The
* authors of MySQL hereby grant you an additional permission to link the
* program and your derivative works with the separately licensed software that
* they have included with MySQL.
*
* Without limiting anything contained in the foregoing, this file, which is
* part of MySQL Connector/J, is also subject to the Universal FOSS Exception,
* version 1.0, a copy of which can be found at
* http://oss.oracle.com/licenses/universal-foss-exception.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
* for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.mysql.cj.protocol.a;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.sql.DataTruncation;
import java.sql.SQLWarning;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TimeZone;
import java.util.function.Supplier;
import com.mysql.cj.CharsetMapping;
import com.mysql.cj.Constants;
import com.mysql.cj.MessageBuilder;
import com.mysql.cj.Messages;
import com.mysql.cj.MysqlType;
import com.mysql.cj.Query;
import com.mysql.cj.QueryResult;
import com.mysql.cj.ServerPreparedQuery;
import com.mysql.cj.ServerVersion;
import com.mysql.cj.Session;
import com.mysql.cj.TransactionEventHandler;
import com.mysql.cj.conf.PropertyKey;
import com.mysql.cj.conf.PropertySet;
import com.mysql.cj.conf.RuntimeProperty;
import com.mysql.cj.conf.RuntimeProperty.RuntimePropertyListener;
import com.mysql.cj.exceptions.CJCommunicationsException;
import com.mysql.cj.exceptions.CJConnectionFeatureNotAvailableException;
import com.mysql.cj.exceptions.CJException;
import com.mysql.cj.exceptions.CJOperationNotSupportedException;
import com.mysql.cj.exceptions.CJPacketTooBigException;
import com.mysql.cj.exceptions.ClosedOnExpiredPasswordException;
import com.mysql.cj.exceptions.DataTruncationException;
import com.mysql.cj.exceptions.ExceptionFactory;
import com.mysql.cj.exceptions.FeatureNotAvailableException;
import com.mysql.cj.exceptions.MysqlErrorNumbers;
import com.mysql.cj.exceptions.PasswordExpiredException;
import com.mysql.cj.exceptions.WrongArgumentException;
import com.mysql.cj.interceptors.QueryInterceptor;
import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import com.mysql.cj.log.BaseMetricsHolder;
import com.mysql.cj.log.Log;
import com.mysql.cj.log.ProfilerEvent;
import com.mysql.cj.log.ProfilerEventHandler;
import com.mysql.cj.protocol.AbstractProtocol;
import com.mysql.cj.protocol.AuthenticationProvider;
import com.mysql.cj.protocol.ColumnDefinition;
import com.mysql.cj.protocol.ExportControlled;
import com.mysql.cj.protocol.FullReadInputStream;
import com.mysql.cj.protocol.Message;
import com.mysql.cj.protocol.MessageReader;
import com.mysql.cj.protocol.MessageSender;
import com.mysql.cj.protocol.PacketReceivedTimeHolder;
import com.mysql.cj.protocol.PacketSentTimeHolder;
import com.mysql.cj.protocol.Protocol;
import com.mysql.cj.protocol.ProtocolEntity;
import com.mysql.cj.protocol.ProtocolEntityFactory;
import com.mysql.cj.protocol.ProtocolEntityReader;
import com.mysql.cj.protocol.ResultBuilder;
import com.mysql.cj.protocol.Resultset;
import com.mysql.cj.protocol.Resultset.Concurrency;
import com.mysql.cj.protocol.Resultset.Type;
import com.mysql.cj.protocol.ResultsetRow;
import com.mysql.cj.protocol.ResultsetRows;
import com.mysql.cj.protocol.ServerSession;
import com.mysql.cj.protocol.SocketConnection;
import com.mysql.cj.protocol.a.NativeConstants.IntegerDataType;
import com.mysql.cj.protocol.a.NativeConstants.StringLengthDataType;
import com.mysql.cj.protocol.a.NativeConstants.StringSelfDataType;
import com.mysql.cj.protocol.a.result.OkPacket;
import com.mysql.cj.result.Field;
import com.mysql.cj.result.IntegerValueFactory;
import com.mysql.cj.result.Row;
import com.mysql.cj.result.StringValueFactory;
import com.mysql.cj.result.ValueFactory;
import com.mysql.cj.util.LazyString;
import com.mysql.cj.util.StringUtils;
import com.mysql.cj.util.TestUtils;
import com.mysql.cj.util.TimeUtil;
import com.mysql.cj.util.Util;
public class NativeProtocol extends AbstractProtocol<NativePacketPayload> implements Protocol<NativePacketPayload>, RuntimePropertyListener {
protected static final int INITIAL_PACKET_SIZE = 1024;
protected static final int COMP_HEADER_LENGTH = 3;
protected static final int MAX_QUERY_SIZE_TO_EXPLAIN = 1024 * 1024; // don't explain queries above 1MB
private static final String EXPLAINABLE_STATEMENT = "SELECT";
private static final String[] EXPLAINABLE_STATEMENT_EXTENSION = new String[] { "INSERT", "UPDATE", "REPLACE", "DELETE" };
protected MessageSender<NativePacketPayload> packetSender;
protected MessageReader<NativePacketHeader, NativePacketPayload> packetReader;
protected NativeServerSession serverSession;
/** Track this to manually shut down. */
protected CompressedPacketSender compressedPacketSender;
//private PacketPayload sendPacket = null;
protected NativePacketPayload sharedSendPacket = null;
/** Use this when reading in rows to avoid thousands of new() calls, because the byte arrays just get copied out of the packet anyway */
protected NativePacketPayload reusablePacket = null;
/**
* Packet used for 'LOAD DATA LOCAL INFILE'
*
* We use a SoftReference, so that we don't penalize intermittent use of this feature
*/
private SoftReference<NativePacketPayload> loadFileBufRef;
protected byte packetSequence = 0;
protected boolean useCompression = false;
private RuntimeProperty<Integer> maxAllowedPacket;
private RuntimeProperty<Boolean> useServerPrepStmts;
//private boolean needToGrabQueryFromPacket;
private boolean autoGenerateTestcaseScript;
/** Does the server support long column info? */
private boolean logSlowQueries = false;
private boolean useAutoSlowLog;
private boolean profileSQL = false;
private long slowQueryThreshold;
private int commandCount = 0;
protected boolean hadWarnings = false;
private int warningCount = 0;
protected Map<Class<? extends ProtocolEntity>, ProtocolEntityReader<? extends ProtocolEntity, ? extends Message>> PROTOCOL_ENTITY_CLASS_TO_TEXT_READER;
protected Map<Class<? extends ProtocolEntity>, ProtocolEntityReader<? extends ProtocolEntity, ? extends Message>> PROTOCOL_ENTITY_CLASS_TO_BINARY_READER;
/**
* Does the character set of this connection match the character set of the
* platform
*/
protected boolean platformDbCharsetMatches = true; // changed once we've connected.
private int statementExecutionDepth = 0;
private List<QueryInterceptor> queryInterceptors;
private RuntimeProperty<Boolean> maintainTimeStats;
private RuntimeProperty<Integer> maxQuerySizeToLog;
private InputStream localInfileInputStream;
private BaseMetricsHolder metricsHolder;
/**
* The comment (if any) that we'll prepend to all queries
* sent to the server (to show up in "SHOW PROCESSLIST")
*/
private String queryComment = null;
/**
* We store the platform 'encoding' here, only used to avoid munging filenames for LOAD DATA LOCAL INFILE...
*/
private static String jvmPlatformCharset = null;
private NativeMessageBuilder commandBuilder = new NativeMessageBuilder(); // TODO use shared builder
static {
OutputStreamWriter outWriter = null;
//
// Use the I/O system to get the encoding (if possible), to avoid security restrictions on System.getProperty("file.encoding") in applets (why is that
// restricted?)
//
try {
outWriter = new OutputStreamWriter(new ByteArrayOutputStream());
jvmPlatformCharset = outWriter.getEncoding();
} finally {
try {
if (outWriter != null) {
outWriter.close();
}
} catch (IOException ioEx) {
// ignore
}
}
}
public static NativeProtocol getInstance(Session session, SocketConnection socketConnection, PropertySet propertySet, Log log,
TransactionEventHandler transactionManager) {
NativeProtocol protocol = new NativeProtocol(log);
protocol.init(session, socketConnection, propertySet, transactionManager);
return protocol;
}
public NativeProtocol(Log logger) {
this.log = logger;
this.metricsHolder = new BaseMetricsHolder();
}
@Override
public void init(Session sess, SocketConnection phConnection, PropertySet propSet, TransactionEventHandler trManager) {
super.init(sess, phConnection, propSet, trManager);
this.maintainTimeStats = this.propertySet.getBooleanProperty(PropertyKey.maintainTimeStats);
this.maxQuerySizeToLog = this.propertySet.getIntegerProperty(PropertyKey.maxQuerySizeToLog);
this.useAutoSlowLog = this.propertySet.getBooleanProperty(PropertyKey.autoSlowLog).getValue();
this.logSlowQueries = this.propertySet.getBooleanProperty(PropertyKey.logSlowQueries).getValue();
this.maxAllowedPacket = this.propertySet.getIntegerProperty(PropertyKey.maxAllowedPacket);
this.profileSQL = this.propertySet.getBooleanProperty(PropertyKey.profileSQL).getValue();
this.autoGenerateTestcaseScript = this.propertySet.getBooleanProperty(PropertyKey.autoGenerateTestcaseScript).getValue();
this.useServerPrepStmts = this.propertySet.getBooleanProperty(PropertyKey.useServerPrepStmts);
this.reusablePacket = new NativePacketPayload(INITIAL_PACKET_SIZE);
//this.sendPacket = new Buffer(INITIAL_PACKET_SIZE);
try {
this.packetSender = new SimplePacketSender(this.socketConnection.getMysqlOutput());
this.packetReader = new SimplePacketReader(this.socketConnection, this.maxAllowedPacket);
} catch (IOException ioEx) {
throw ExceptionFactory.createCommunicationsException(this.propertySet, this.serverSession, this.getPacketSentTimeHolder(),
this.getPacketReceivedTimeHolder(), ioEx, getExceptionInterceptor());
}
//this.needToGrabQueryFromPacket = (this.profileSQL || this.logSlowQueries || this.autoGenerateTestcaseScript);
if (this.propertySet.getBooleanProperty(PropertyKey.logSlowQueries).getValue()) {
calculateSlowQueryThreshold();
}
this.authProvider = new NativeAuthenticationProvider();
this.authProvider.init(this, this.getPropertySet(), this.socketConnection.getExceptionInterceptor());
Map<Class<? extends ProtocolEntity>, ProtocolEntityReader<? extends ProtocolEntity, NativePacketPayload>> protocolEntityClassToTextReader = new HashMap<>();
protocolEntityClassToTextReader.put(ColumnDefinition.class, new ColumnDefinitionReader(this));
protocolEntityClassToTextReader.put(ResultsetRow.class, new ResultsetRowReader(this));
protocolEntityClassToTextReader.put(Resultset.class, new TextResultsetReader(this));
this.PROTOCOL_ENTITY_CLASS_TO_TEXT_READER = Collections.unmodifiableMap(protocolEntityClassToTextReader);
Map<Class<? extends ProtocolEntity>, ProtocolEntityReader<? extends ProtocolEntity, NativePacketPayload>> protocolEntityClassToBinaryReader = new HashMap<>();
protocolEntityClassToBinaryReader.put(ColumnDefinition.class, new ColumnDefinitionReader(this));
protocolEntityClassToBinaryReader.put(Resultset.class, new BinaryResultsetReader(this));
this.PROTOCOL_ENTITY_CLASS_TO_BINARY_READER = Collections.unmodifiableMap(protocolEntityClassToBinaryReader);
}
@Override
public MessageBuilder<NativePacketPayload> getMessageBuilder() {
throw ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported");
}
public MessageSender<NativePacketPayload> getPacketSender() {
return this.packetSender;
}
public MessageReader<NativePacketHeader, NativePacketPayload> getPacketReader() {
return this.packetReader;
}
/**
* Negotiates the SSL communications channel used when connecting
* to a MySQL server that understands SSL.
*
* @param packLength
* packet length
*/
@Override
public void negotiateSSLConnection(int packLength) {
if (!ExportControlled.enabled()) {
throw new CJConnectionFeatureNotAvailableException(this.getPropertySet(), this.serverSession, this.getPacketSentTimeHolder(), null);
}
long clientParam = this.serverSession.getClientParam();
clientParam |= NativeServerSession.CLIENT_SSL;
this.serverSession.setClientParam(clientParam);
NativePacketPayload packet = new NativePacketPayload(packLength);
packet.writeInteger(IntegerDataType.INT4, clientParam);
packet.writeInteger(IntegerDataType.INT4, NativeConstants.MAX_PACKET_SIZE);
packet.writeInteger(IntegerDataType.INT1, AuthenticationProvider.getCharsetForHandshake(this.authProvider.getEncodingForHandshake(),
this.serverSession.getCapabilities().getServerVersion()));
packet.writeBytes(StringLengthDataType.STRING_FIXED, new byte[23]); // Set of bytes reserved for future use.
send(packet, packet.getPosition());
try {
this.socketConnection.performTlsHandshake(this.serverSession);
// i/o streams were replaced, build new packet sender/reader
this.packetSender = new SimplePacketSender(this.socketConnection.getMysqlOutput());
this.packetReader = new SimplePacketReader(this.socketConnection, this.maxAllowedPacket);
} catch (FeatureNotAvailableException nae) {
throw new CJConnectionFeatureNotAvailableException(this.getPropertySet(), this.serverSession, this.getPacketSentTimeHolder(), nae);
} catch (IOException ioEx) {
throw ExceptionFactory.createCommunicationsException(this.propertySet, this.serverSession, this.getPacketSentTimeHolder(),
this.getPacketReceivedTimeHolder(), ioEx, getExceptionInterceptor());
}
}
public void rejectProtocol(NativePacketPayload msg) {
try {
this.socketConnection.getMysqlSocket().close();
} catch (Exception e) {
// ignore
}
int errno = 2000;
NativePacketPayload buf = msg;
buf.setPosition(1); // skip the packet type
errno = (int) buf.readInteger(IntegerDataType.INT2);
String serverErrorMessage = "";
try {
serverErrorMessage = buf.readString(StringSelfDataType.STRING_TERM, "ASCII");
} catch (Exception e) {
//
}
StringBuilder errorBuf = new StringBuilder(Messages.getString("Protocol.0"));
errorBuf.append(serverErrorMessage);
errorBuf.append("\"");
String xOpen = MysqlErrorNumbers.mysqlToSqlState(errno);
throw ExceptionFactory.createException(MysqlErrorNumbers.get(xOpen) + ", " + errorBuf.toString(), xOpen, errno, false, null, getExceptionInterceptor());
}
@Override
public void beforeHandshake() {
// Reset packet sequences
this.packetReader.resetMessageSequence();
// Create session state
this.serverSession = new NativeServerSession(this.propertySet);
// Read the first packet
NativeCapabilities capabilities = readServerCapabilities();
this.serverSession.setCapabilities(capabilities);
}
@Override
public void afterHandshake() {
checkTransactionState();
PropertySet pset = this.getPropertySet();
try {
//
// Can't enable compression until after handshake
//
if (((this.serverSession.getCapabilities().getCapabilityFlags() & NativeServerSession.CLIENT_COMPRESS) != 0)
&& pset.getBooleanProperty(PropertyKey.useCompression).getValue()
&& !(this.socketConnection.getMysqlInput().getUnderlyingStream() instanceof CompressedInputStream)) {
this.useCompression = true;
this.socketConnection.setMysqlInput(new FullReadInputStream(
new CompressedInputStream(this.socketConnection.getMysqlInput(), pset.getBooleanProperty(PropertyKey.traceProtocol), this.log)));
this.compressedPacketSender = new CompressedPacketSender(this.socketConnection.getMysqlOutput());
this.packetSender = this.compressedPacketSender;
}
applyPacketDecorators(this.packetSender, this.packetReader);
this.socketConnection.getSocketFactory().afterHandshake();
} catch (IOException ioEx) {
throw ExceptionFactory.createCommunicationsException(this.getPropertySet(), this.serverSession, this.getPacketSentTimeHolder(),
this.getPacketReceivedTimeHolder(), ioEx, getExceptionInterceptor());
}
// listen for properties changes to allow decorators reconfiguration
this.maintainTimeStats.addListener(this);
pset.getBooleanProperty(PropertyKey.traceProtocol).addListener(this);
pset.getBooleanProperty(PropertyKey.enablePacketDebug).addListener(this);
}
@Override
public void handlePropertyChange(RuntimeProperty<?> prop) {
switch (prop.getPropertyDefinition().getPropertyKey()) {
case maintainTimeStats:
case traceProtocol:
case enablePacketDebug:
applyPacketDecorators(this.packetSender.undecorateAll(), this.packetReader.undecorateAll());
break;
default:
break;
}
}
/**
* Apply optional decorators to configured PacketSender and PacketReader.
*
* @param sender
* {@link MessageSender}
* @param messageReader
* {@link MessageReader}
*/
public void applyPacketDecorators(MessageSender<NativePacketPayload> sender, MessageReader<NativePacketHeader, NativePacketPayload> messageReader) {
TimeTrackingPacketSender ttSender = null;
TimeTrackingPacketReader ttReader = null;
LinkedList<StringBuilder> debugRingBuffer = null;
if (this.maintainTimeStats.getValue()) {
ttSender = new TimeTrackingPacketSender(sender);
sender = ttSender;
ttReader = new TimeTrackingPacketReader(messageReader);
messageReader = ttReader;
}
if (this.propertySet.getBooleanProperty(PropertyKey.traceProtocol).getValue()) {
sender = new TracingPacketSender(sender, this.log, this.socketConnection.getHost(), getServerSession().getCapabilities().getThreadId());
messageReader = new TracingPacketReader(messageReader, this.log);
}
if (this.getPropertySet().getBooleanProperty(PropertyKey.enablePacketDebug).getValue()) {
debugRingBuffer = new LinkedList<>();
sender = new DebugBufferingPacketSender(sender, debugRingBuffer, this.propertySet.getIntegerProperty(PropertyKey.packetDebugBufferSize));
messageReader = new DebugBufferingPacketReader(messageReader, debugRingBuffer,
this.propertySet.getIntegerProperty(PropertyKey.packetDebugBufferSize));
}
// do it after other decorators to have trace and debug applied to individual packets
messageReader = new MultiPacketReader(messageReader);
// atomic replacement of currently used objects
synchronized (this.packetReader) {
this.packetReader = messageReader;
this.packetDebugRingBuffer = debugRingBuffer;
this.setPacketSentTimeHolder(ttSender != null ? ttSender : new PacketSentTimeHolder() {
});
}
synchronized (this.packetSender) {
this.packetSender = sender;
this.setPacketReceivedTimeHolder(ttReader != null ? ttReader : new PacketReceivedTimeHolder() {
});
}
}
public NativeCapabilities readServerCapabilities() {
// Read the first packet
NativePacketPayload buf = readMessage(null);
// Server Greeting Error packet instead of Server Greeting
if (buf.isErrorPacket()) {
rejectProtocol(buf);
}
NativeCapabilities serverCapabilities = new NativeCapabilities();
serverCapabilities.setInitialHandshakePacket(buf);
return serverCapabilities;
}
@Override
public NativeServerSession getServerSession() {
return this.serverSession;
}
@Override
public void changeDatabase(String database) {
if (database == null || database.length() == 0) {
return;
}
try {
sendCommand(this.commandBuilder.buildComInitDb(getSharedSendPacket(), database), false, 0);
} catch (CJException ex) {
if (this.getPropertySet().getBooleanProperty(PropertyKey.createDatabaseIfNotExist).getValue()) {
sendCommand(this.commandBuilder.buildComQuery(getSharedSendPacket(), "CREATE DATABASE IF NOT EXISTS " + database), false, 0);
sendCommand(this.commandBuilder.buildComInitDb(getSharedSendPacket(), database), false, 0);
} else {
throw ExceptionFactory.createCommunicationsException(this.getPropertySet(), this.serverSession, this.getPacketSentTimeHolder(),
this.getPacketReceivedTimeHolder(), ex, getExceptionInterceptor());
}
}
}
@Override
public final NativePacketPayload readMessage(NativePacketPayload reuse) {
try {
NativePacketHeader header = this.packetReader.readHeader();
NativePacketPayload buf = this.packetReader.readMessage(Optional.ofNullable(reuse), header);
this.packetSequence = header.getMessageSequence();
return buf;
} catch (IOException ioEx) {
throw ExceptionFactory.createCommunicationsException(this.propertySet, this.serverSession, this.getPacketSentTimeHolder(),
this.getPacketReceivedTimeHolder(), ioEx, getExceptionInterceptor());
} catch (OutOfMemoryError oom) {
throw ExceptionFactory.createException(oom.getMessage(), MysqlErrorNumbers.SQL_STATE_MEMORY_ALLOCATION_ERROR, 0, false, oom,
this.exceptionInterceptor);
}
}
/**
* @param packet
* {@link Message}
* @param packetLen
* length of header + payload
*/
@Override
public final void send(Message packet, int packetLen) {
try {
if (this.maxAllowedPacket.getValue() > 0 && packetLen > this.maxAllowedPacket.getValue()) {
throw new CJPacketTooBigException(packetLen, this.maxAllowedPacket.getValue());
}
this.packetSequence++;
this.packetSender.send(packet.getByteBuffer(), packetLen, this.packetSequence);
//
// Don't hold on to large packets
//
if (packet == this.sharedSendPacket) {
reclaimLargeSharedSendPacket();
}
} catch (IOException ioEx) {
throw ExceptionFactory.createCommunicationsException(this.getPropertySet(), this.serverSession, this.getPacketSentTimeHolder(),
this.getPacketReceivedTimeHolder(), ioEx, getExceptionInterceptor());
}
}
@Override
public final NativePacketPayload sendCommand(Message queryPacket, boolean skipCheck, int timeoutMillis) {
int command = queryPacket.getByteBuffer()[0];
this.commandCount++;
if (this.queryInterceptors != null) {
NativePacketPayload interceptedPacketPayload = (NativePacketPayload) invokeQueryInterceptorsPre(queryPacket, false);
if (interceptedPacketPayload != null) {
return interceptedPacketPayload;
}
}
this.packetReader.resetMessageSequence();
int oldTimeout = 0;
if (timeoutMillis != 0) {
try {
oldTimeout = this.socketConnection.getMysqlSocket().getSoTimeout();
this.socketConnection.getMysqlSocket().setSoTimeout(timeoutMillis);
} catch (IOException e) {
throw ExceptionFactory.createCommunicationsException(this.propertySet, this.serverSession, this.getPacketSentTimeHolder(),
this.getPacketReceivedTimeHolder(), e, getExceptionInterceptor());
}
}
try {
checkForOutstandingStreamingData();
// Clear serverStatus...this value is guarded by an external mutex, as you can only ever be processing one command at a time
this.serverSession.setStatusFlags(0, true);
this.hadWarnings = false;
this.setWarningCount(0);
//
// Compressed input stream needs cleared at beginning of each command execution...
//
if (this.useCompression) {
int bytesLeft = this.socketConnection.getMysqlInput().available();
if (bytesLeft > 0) {
this.socketConnection.getMysqlInput().skip(bytesLeft);
}
}
try {
clearInputStream();
this.packetSequence = -1;
send(queryPacket, queryPacket.getPosition());
} catch (CJException ex) {
// don't wrap CJExceptions
throw ex;
} catch (Exception ex) {
throw ExceptionFactory.createCommunicationsException(this.propertySet, this.serverSession, this.getPacketSentTimeHolder(),
this.getPacketReceivedTimeHolder(), ex, getExceptionInterceptor());
}
NativePacketPayload returnPacket = null;
if (!skipCheck) {
if ((command == NativeConstants.COM_STMT_EXECUTE) || (command == NativeConstants.COM_STMT_RESET)) {
this.packetReader.resetMessageSequence();
}
returnPacket = checkErrorMessage(command);
if (this.queryInterceptors != null) {
returnPacket = (NativePacketPayload) invokeQueryInterceptorsPost(queryPacket, returnPacket, false);
}
}
return returnPacket;
} catch (IOException ioEx) {
this.serverSession.preserveOldTransactionState();
throw ExceptionFactory.createCommunicationsException(this.propertySet, this.serverSession, this.getPacketSentTimeHolder(),
this.getPacketReceivedTimeHolder(), ioEx, getExceptionInterceptor());
} catch (CJException e) {
this.serverSession.preserveOldTransactionState();
throw e;
} finally {
if (timeoutMillis != 0) {
try {
this.socketConnection.getMysqlSocket().setSoTimeout(oldTimeout);
} catch (IOException e) {
throw ExceptionFactory.createCommunicationsException(this.propertySet, this.serverSession, this.getPacketSentTimeHolder(),
this.getPacketReceivedTimeHolder(), e, getExceptionInterceptor());
}
}
}
}
public void checkTransactionState() {
int transState = this.serverSession.getTransactionState();
if (transState == ServerSession.TRANSACTION_COMPLETED) {
this.transactionManager.transactionCompleted();
} else if (transState == ServerSession.TRANSACTION_STARTED) {
this.transactionManager.transactionBegun();
}
}
public NativePacketPayload checkErrorMessage() {
return checkErrorMessage(-1);
}
/**
* Checks for errors in the reply packet, and if none, returns the reply
* packet, ready for reading
*
* @param command
* the command being issued (if used)
* @return NativePacketPayload
* @throws CJException
* if an error packet was received
* @throws CJCommunicationsException
* if a database error occurs
*/
private NativePacketPayload checkErrorMessage(int command) {
NativePacketPayload resultPacket = null;
this.serverSession.setStatusFlags(0);
try {
// Check return value, if we get a java.io.EOFException, the server has gone away. We'll pass it on up the exception chain and let someone higher up
// decide what to do (barf, reconnect, etc).
resultPacket = readMessage(this.reusablePacket);
} catch (CJException ex) {
// Don't wrap CJExceptions
throw ex;
} catch (Exception fallThru) {
throw ExceptionFactory.createCommunicationsException(this.propertySet, this.serverSession, this.getPacketSentTimeHolder(),
this.getPacketReceivedTimeHolder(), fallThru, getExceptionInterceptor());
}
checkErrorMessage(resultPacket);
return resultPacket;
}
public void checkErrorMessage(NativePacketPayload resultPacket) {
resultPacket.setPosition(0);
byte statusCode = (byte) resultPacket.readInteger(IntegerDataType.INT1);
// Error handling
if (statusCode == (byte) 0xff) {
String serverErrorMessage;
int errno = 2000;
errno = (int) resultPacket.readInteger(IntegerDataType.INT2);
String xOpen = null;
serverErrorMessage = resultPacket.readString(StringSelfDataType.STRING_TERM, this.serverSession.getErrorMessageEncoding());
if (serverErrorMessage.charAt(0) == '#') {
// we have an SQLState
if (serverErrorMessage.length() > 6) {
xOpen = serverErrorMessage.substring(1, 6);
serverErrorMessage = serverErrorMessage.substring(6);
if (xOpen.equals("HY000")) {
xOpen = MysqlErrorNumbers.mysqlToSqlState(errno);
}
} else {
xOpen = MysqlErrorNumbers.mysqlToSqlState(errno);
}
} else {
xOpen = MysqlErrorNumbers.mysqlToSqlState(errno);
}
clearInputStream();
StringBuilder errorBuf = new StringBuilder();
String xOpenErrorMessage = MysqlErrorNumbers.get(xOpen);
boolean useOnlyServerErrorMessages = this.propertySet.getBooleanProperty(PropertyKey.useOnlyServerErrorMessages).getValue();
if (!useOnlyServerErrorMessages) {
if (xOpenErrorMessage != null) {
errorBuf.append(xOpenErrorMessage);
errorBuf.append(Messages.getString("Protocol.0"));
}
}
errorBuf.append(serverErrorMessage);
if (!useOnlyServerErrorMessages) {
if (xOpenErrorMessage != null) {
errorBuf.append("\"");
}
}
appendDeadlockStatusInformation(this.session, xOpen, errorBuf);
if (xOpen != null) {
if (xOpen.startsWith("22")) {
throw new DataTruncationException(errorBuf.toString(), 0, true, false, 0, 0, errno);
}
if (errno == MysqlErrorNumbers.ER_MUST_CHANGE_PASSWORD) {
throw ExceptionFactory.createException(PasswordExpiredException.class, errorBuf.toString(), getExceptionInterceptor());
} else if (errno == MysqlErrorNumbers.ER_MUST_CHANGE_PASSWORD_LOGIN) {
throw ExceptionFactory.createException(ClosedOnExpiredPasswordException.class, errorBuf.toString(), getExceptionInterceptor());
}
}
throw ExceptionFactory.createException(errorBuf.toString(), xOpen, errno, false, null, getExceptionInterceptor());
}
}
private void reclaimLargeSharedSendPacket() {
if ((this.sharedSendPacket != null) && (this.sharedSendPacket.getCapacity() > 1048576)) {
this.sharedSendPacket = new NativePacketPayload(INITIAL_PACKET_SIZE);
}
}
public void clearInputStream() {
try {
int len;
// Due to a bug in some older Linux kernels (fixed after the patch "tcp: fix FIONREAD/SIOCINQ"), our SocketInputStream.available() may return 1 even
// if there is no data in the Stream, so, we need to check if InputStream.skip() actually skipped anything.
while ((len = this.socketConnection.getMysqlInput().available()) > 0 && this.socketConnection.getMysqlInput().skip(len) > 0) {
continue;
}
} catch (IOException ioEx) {
throw ExceptionFactory.createCommunicationsException(this.propertySet, this.serverSession, this.getPacketSentTimeHolder(),
this.getPacketReceivedTimeHolder(), ioEx, getExceptionInterceptor());
}
}
/**
* Don't hold on to overly-large packets
*/
public void reclaimLargeReusablePacket() {
if ((this.reusablePacket != null) && (this.reusablePacket.getCapacity() > 1048576)) {
this.reusablePacket = new NativePacketPayload(INITIAL_PACKET_SIZE);
}
}
/**
* Build a query packet from the given string and send it to the server.
*
* @param <T>
* extends {@link Resultset}
* @param callingQuery
* {@link Query}
* @param query
* query string
* @param characterEncoding
* Java encoding name
* @param maxRows
* rows limit
* @param streamResults
* whether a stream result should be created
* @param cachedMetadata
* use this metadata instead of the one provided on wire
* @param resultSetFactory
* {@link ProtocolEntityFactory}
* @return T instance
* @throws IOException
* if an i/o error occurs
*/
public final <T extends Resultset> T sendQueryString(Query callingQuery, String query, String characterEncoding, int maxRows, boolean streamResults,
ColumnDefinition cachedMetadata, ProtocolEntityFactory<T, NativePacketPayload> resultSetFactory) throws IOException {
String statementComment = this.queryComment;
if (this.propertySet.getBooleanProperty(PropertyKey.includeThreadNamesAsStatementComment).getValue()) {
statementComment = (statementComment != null ? statementComment + ", " : "") + "java thread: " + Thread.currentThread().getName();
}
// We don't know exactly how many bytes we're going to get from the query. Since we're dealing with UTF-8, the max is 4, so pad it
// (4 * query) + space for headers
int packLength = 1 + (query.length() * 4) + 2;
byte[] commentAsBytes = null;
if (statementComment != null) {
commentAsBytes = StringUtils.getBytes(statementComment, characterEncoding);
packLength += commentAsBytes.length;
packLength += 6; // for /*[space] [space]*/
}
// TODO decide how to safely use the shared this.sendPacket
//if (this.sendPacket == null) {
NativePacketPayload sendPacket = new NativePacketPayload(packLength);
//}
sendPacket.setPosition(0);
sendPacket.writeInteger(IntegerDataType.INT1, NativeConstants.COM_QUERY);
if (commentAsBytes != null) {
sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, Constants.SLASH_STAR_SPACE_AS_BYTES);
sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, commentAsBytes);
sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, Constants.SPACE_STAR_SLASH_SPACE_AS_BYTES);
}
if (!this.platformDbCharsetMatches && StringUtils.startsWithIgnoreCaseAndWs(query, "LOAD DATA")) {
sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, StringUtils.getBytes(query));
} else {
sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, StringUtils.getBytes(query, characterEncoding));
}
return sendQueryPacket(callingQuery, sendPacket, maxRows, streamResults, cachedMetadata, resultSetFactory);
}
/**
* Send a query stored in a packet to the server.
*
* @param <T>
* extends {@link Resultset}
* @param callingQuery
* {@link Query}
* @param queryPacket
* {@link NativePacketPayload} containing query
* @param maxRows
* rows limit
* @param streamResults
* whether a stream result should be created
* @param cachedMetadata
* use this metadata instead of the one provided on wire
* @param resultSetFactory
* {@link ProtocolEntityFactory}
* @return T instance
* @throws IOException
* if an i/o error occurs
*/
public final <T extends Resultset> T sendQueryPacket(Query callingQuery, NativePacketPayload queryPacket, int maxRows, boolean streamResults,
ColumnDefinition cachedMetadata, ProtocolEntityFactory<T, NativePacketPayload> resultSetFactory) throws IOException {
long queryStartTime = this.profileSQL || this.logSlowQueries ? getCurrentTimeNanosOrMillis() : 0;
this.statementExecutionDepth++;
byte[] queryBuf = queryPacket.getByteBuffer();
int oldPacketPosition = queryPacket.getPosition(); // save the packet position
LazyString query = new LazyString(queryBuf, 1, (oldPacketPosition - 1));
try {
if (this.queryInterceptors != null) {
T interceptedResults = invokeQueryInterceptorsPre(query, callingQuery, false);
if (interceptedResults != null) {
return interceptedResults;
}
}
if (this.autoGenerateTestcaseScript) {
StringBuilder debugBuf = new StringBuilder(query.length() + 32);
generateQueryCommentBlock(debugBuf);
debugBuf.append(query);
debugBuf.append(';');
TestUtils.dumpTestcaseQuery(debugBuf.toString());
}
// Send query command and sql query string
NativePacketPayload resultPacket = sendCommand(queryPacket, false, 0);
long queryEndTime = this.profileSQL || this.logSlowQueries ? getCurrentTimeNanosOrMillis() : 0L;
long queryDuration = this.profileSQL || this.logSlowQueries ? queryEndTime - queryStartTime : 0L;
boolean queryWasSlow = this.logSlowQueries && (this.useAutoSlowLog ? this.metricsHolder.checkAbonormallyLongQuery(queryDuration)
: queryDuration > this.propertySet.getIntegerProperty(PropertyKey.slowQueryThresholdMillis).getValue());
long fetchBeginTime = this.profileSQL ? getCurrentTimeNanosOrMillis() : 0L;
T rs = readAllResults(maxRows, streamResults, resultPacket, false, cachedMetadata, resultSetFactory);
if (this.profileSQL || queryWasSlow) {
long fetchEndTime = this.profileSQL ? getCurrentTimeNanosOrMillis() : 0L;
// Extract the actual query from the network packet
boolean truncated = oldPacketPosition > this.maxQuerySizeToLog.getValue();
int extractPosition = truncated ? this.maxQuerySizeToLog.getValue() + 1 : oldPacketPosition;
String extractedQuery = StringUtils.toString(queryBuf, 1, (extractPosition - 1));
if (truncated) {
extractedQuery += Messages.getString("Protocol.2");
}
ProfilerEventHandler eventSink = this.session.getProfilerEventHandler();
if (this.logSlowQueries) {
if (queryWasSlow) {
eventSink.processEvent(ProfilerEvent.TYPE_SLOW_QUERY, this.session, callingQuery, rs, queryDuration, new Throwable(),
Messages.getString("Protocol.SlowQuery",
new Object[] { this.useAutoSlowLog ? " 95% of all queries " : String.valueOf(this.slowQueryThreshold),
this.queryTimingUnits, Long.valueOf(queryDuration), extractedQuery }));
if (this.propertySet.getBooleanProperty(PropertyKey.explainSlowQueries).getValue()) {
if (oldPacketPosition < MAX_QUERY_SIZE_TO_EXPLAIN) {
queryPacket.setPosition(1); // skip first byte
explainSlowQuery(query.toString(), extractedQuery);
} else {
this.log.logWarn(Messages.getString("Protocol.3", new Object[] { MAX_QUERY_SIZE_TO_EXPLAIN }));
}
}
}
if (this.serverSession.noGoodIndexUsed()) {
eventSink.processEvent(ProfilerEvent.TYPE_SLOW_QUERY, this.session, callingQuery, rs, queryDuration, new Throwable(),
Messages.getString("Protocol.4") + extractedQuery);
}
if (this.serverSession.noIndexUsed()) {
eventSink.processEvent(ProfilerEvent.TYPE_SLOW_QUERY, this.session, callingQuery, rs, queryDuration, new Throwable(),
Messages.getString("Protocol.5") + extractedQuery);
}
if (this.serverSession.queryWasSlow()) {
eventSink.processEvent(ProfilerEvent.TYPE_SLOW_QUERY, this.session, callingQuery, rs, queryDuration, new Throwable(),
Messages.getString("Protocol.ServerSlowQuery") + extractedQuery);
}
}
if (this.profileSQL) {
eventSink.processEvent(ProfilerEvent.TYPE_QUERY, this.session, callingQuery, rs, queryDuration, new Throwable(), extractedQuery);
eventSink.processEvent(ProfilerEvent.TYPE_FETCH, this.session, callingQuery, rs, (fetchEndTime - fetchBeginTime), new Throwable(), null);
}