/
AbstractConnectProtocol.java
1518 lines (1336 loc) · 49.3 KB
/
AbstractConnectProtocol.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
/*
*
* MariaDB Client for Java
*
* Copyright (c) 2012-2014 Monty Program Ab.
* Copyright (c) 2015-2017 MariaDB Ab.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this library; if not, write to Monty Program Ab info@montyprogram.com.
*
* This particular MariaDB Client for Java file is work
* derived from a Drizzle-JDBC. Drizzle-JDBC file which is covered by subject to
* the following copyright and notice provisions:
*
* Copyright (c) 2009-2011, Marcus Eriksson
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of the driver nor the names of its contributors may not be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
*/
package org.mariadb.jdbc.internal.protocol;
import static org.mariadb.jdbc.internal.com.Packet.COM_QUERY;
import static org.mariadb.jdbc.internal.com.Packet.EOF;
import static org.mariadb.jdbc.internal.com.Packet.ERROR;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLNonTransientConnectionException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.mariadb.jdbc.HostAddress;
import org.mariadb.jdbc.MariaDbConnection;
import org.mariadb.jdbc.UrlParser;
import org.mariadb.jdbc.internal.MariaDbServerCapabilities;
import org.mariadb.jdbc.internal.com.read.Buffer;
import org.mariadb.jdbc.internal.com.read.ErrorPacket;
import org.mariadb.jdbc.internal.com.read.OkPacket;
import org.mariadb.jdbc.internal.com.read.ReadInitialHandShakePacket;
import org.mariadb.jdbc.internal.com.read.dao.Results;
import org.mariadb.jdbc.internal.com.send.InterfaceAuthSwitchSendResponsePacket;
import org.mariadb.jdbc.internal.com.send.SendClosePacket;
import org.mariadb.jdbc.internal.com.send.SendHandshakeResponsePacket;
import org.mariadb.jdbc.internal.com.send.SendOldPasswordAuthPacket;
import org.mariadb.jdbc.internal.com.send.SendSslConnectionRequestPacket;
import org.mariadb.jdbc.internal.failover.FailoverProxy;
import org.mariadb.jdbc.internal.io.LruTraceCache;
import org.mariadb.jdbc.internal.io.input.DecompressPacketInputStream;
import org.mariadb.jdbc.internal.io.input.PacketInputStream;
import org.mariadb.jdbc.internal.io.input.StandardPacketInputStream;
import org.mariadb.jdbc.internal.io.output.CompressPacketOutputStream;
import org.mariadb.jdbc.internal.io.output.PacketOutputStream;
import org.mariadb.jdbc.internal.io.output.StandardPacketOutputStream;
import org.mariadb.jdbc.internal.logging.Logger;
import org.mariadb.jdbc.internal.logging.LoggerFactory;
import org.mariadb.jdbc.internal.protocol.authentication.AuthenticationProviderHolder;
import org.mariadb.jdbc.internal.protocol.authentication.DefaultAuthenticationProvider;
import org.mariadb.jdbc.internal.protocol.tls.HostnameVerifierImpl;
import org.mariadb.jdbc.internal.protocol.tls.MariaDbX509KeyManager;
import org.mariadb.jdbc.internal.protocol.tls.MariaDbX509TrustManager;
import org.mariadb.jdbc.internal.util.Options;
import org.mariadb.jdbc.internal.util.ServerPrepareStatementCache;
import org.mariadb.jdbc.internal.util.Utils;
import org.mariadb.jdbc.internal.util.constant.HaMode;
import org.mariadb.jdbc.internal.util.constant.ParameterConstant;
import org.mariadb.jdbc.internal.util.constant.ServerStatus;
import org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper;
import org.mariadb.jdbc.internal.util.pool.GlobalStateInfo;
public abstract class AbstractConnectProtocol implements Protocol {
private static final byte[] SESSION_QUERY = ("SELECT @@max_allowed_packet,"
+ "@@system_time_zone,"
+ "@@time_zone,"
+ "@@auto_increment_increment").getBytes(StandardCharsets.UTF_8);
private static final byte[] IS_MASTER_QUERY = "show global variables like 'innodb_read_only'"
.getBytes(StandardCharsets.UTF_8);
private static final Logger logger = LoggerFactory.getLogger(AbstractConnectProtocol.class);
protected final ReentrantLock lock;
protected final UrlParser urlParser;
protected final Options options;
private final String username;
private final String password;
private final LruTraceCache traceCache = new LruTraceCache();
private final GlobalStateInfo globalInfo;
public boolean hasWarnings = false;
public Results activeStreamingResult = null;
public short serverStatus;
protected int autoIncrementIncrement;
protected Socket socket;
protected PacketOutputStream writer;
protected boolean readOnly = false;
protected PacketInputStream reader;
protected FailoverProxy proxy;
protected volatile boolean connected = false;
protected boolean explicitClosed = false;
protected String database;
protected long serverThreadId;
protected ServerPrepareStatementCache serverPrepareStatementCache;
protected boolean eofDeprecated = false;
protected long serverCapabilities;
private HostAddress currentHost;
private boolean hostFailed;
private String serverVersion;
private boolean serverMariaDb;
private int majorVersion;
private int minorVersion;
private int patchVersion;
private TimeZone timeZone;
/**
* Get a protocol instance.
*
* @param urlParser connection URL information
* @param globalInfo server global variables information
* @param lock the lock for thread synchronisation
*/
public AbstractConnectProtocol(final UrlParser urlParser, final GlobalStateInfo globalInfo,
final ReentrantLock lock) {
urlParser.auroraPipelineQuirks();
this.lock = lock;
this.urlParser = urlParser;
this.options = urlParser.getOptions();
this.database = (urlParser.getDatabase() == null ? "" : urlParser.getDatabase());
this.username = (urlParser.getUsername() == null ? "" : urlParser.getUsername());
this.password = (urlParser.getPassword() == null ? "" : urlParser.getPassword());
this.globalInfo = globalInfo;
if (options.cachePrepStmts && options.useServerPrepStmts) {
serverPrepareStatementCache = ServerPrepareStatementCache
.newInstance(options.prepStmtCacheSize, this);
}
}
private static void closeSocket(PacketInputStream packetInputStream,
PacketOutputStream packetOutputStream, Socket socket) {
try {
try {
long maxCurrentMillis = System.currentTimeMillis() + 10;
socket.shutdownOutput();
socket.setSoTimeout(3);
InputStream is = socket.getInputStream();
//noinspection StatementWithEmptyBody
while (is.read() != -1 && System.currentTimeMillis() < maxCurrentMillis) {
//read byte
}
} catch (Throwable t) {
//eat exception
}
packetOutputStream.close();
packetInputStream.close();
} catch (IOException e) {
//eat
} finally {
try {
socket.close();
} catch (IOException e) {
//socket closed, if any error, so not throwing error
}
}
}
/**
* Closes socket and stream readers/writers Attempts graceful shutdown.
*/
public void close() {
if (lock != null) {
lock.lock();
}
this.connected = false;
try {
/* If a streaming result set is open, close it.*/
skip();
} catch (Exception e) {
/* eat exception */
}
SendClosePacket.send(writer);
closeSocket(reader, writer, socket);
cleanMemory();
if (lock != null) {
lock.unlock();
}
}
/**
* Force closes socket and stream readers/writers.
*/
public void abort() {
this.explicitClosed = true;
boolean lockStatus = false;
if (lock != null) {
lockStatus = lock.tryLock();
}
this.connected = false;
abortActiveStream();
if (!lockStatus) {
//lock not available : query is running
// force end by executing an KILL connection
forceAbort();
try {
socket.setSoLinger(true, 0);
} catch (IOException ioException) {
//eat
}
} else {
SendClosePacket.send(writer);
}
closeSocket(reader, writer, socket);
cleanMemory();
if (lockStatus) {
lock.unlock();
}
}
private void forceAbort() {
try (MasterProtocol copiedProtocol = new MasterProtocol(urlParser, new GlobalStateInfo(),
new ReentrantLock())) {
copiedProtocol.setHostAddress(getHostAddress());
copiedProtocol.connect();
//no lock, because there is already a query running that possessed the lock.
copiedProtocol.executeQuery("KILL " + serverThreadId);
} catch (SQLException sqle) {
//eat
}
}
private void abortActiveStream() {
try {
/* If a streaming result set is open, abort it.*/
if (activeStreamingResult != null) {
activeStreamingResult.abort();
activeStreamingResult = null;
}
} catch (Exception e) {
/* eat exception */
}
}
/**
* Skip packets not read that are not needed. Packets are read according to needs. If some data
* have not been read before next execution, skip it.
* <i>Lock must be set before using this method</i>
*
* @throws SQLException exception
*/
public void skip() throws SQLException {
if (activeStreamingResult != null) {
activeStreamingResult.loadFully(true, this);
activeStreamingResult = null;
}
}
private void cleanMemory() {
if (options.cachePrepStmts && options.useServerPrepStmts) {
serverPrepareStatementCache.clear();
}
if (options.enablePacketDebug) {
traceCache.clearMemory();
}
}
public void setServerStatus(short serverStatus) {
this.serverStatus = serverStatus;
}
/**
* Remove flag has more results.
*/
public void removeHasMoreResults() {
if (hasMoreResults()) {
this.serverStatus = (short) (serverStatus ^ ServerStatus.MORE_RESULTS_EXISTS);
}
}
private SSLSocketFactory getSslSocketFactory() throws SQLException {
TrustManager[] trustManager = null;
KeyManager[] keyManager = null;
if (options.trustServerCertificate || options.serverSslCert != null
|| options.trustStore != null) {
trustManager = new X509TrustManager[]{new MariaDbX509TrustManager(options)};
}
if (options.keyStore != null) {
keyManager = new KeyManager[]{
loadClientCerts(options.keyStore, options.keyStorePassword, options.keyPassword)};
} else {
String keyStore = System.getProperty("javax.net.ssl.keyStore");
String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
if (keyStore != null) {
try {
keyManager = new KeyManager[]{
loadClientCerts(keyStore, keyStorePassword, keyStorePassword)};
} catch (SQLException queryException) {
keyManager = null;
logger.error("Error loading keymanager from system properties", queryException);
}
}
}
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManager, trustManager, null);
return sslContext.getSocketFactory();
} catch (KeyManagementException keyManagementEx) {
throw ExceptionMapper.connException("Could not initialize SSL context", keyManagementEx);
} catch (NoSuchAlgorithmException noSuchAlgorithmEx) {
throw ExceptionMapper
.connException("SSLContext TLS Algorithm not unknown", noSuchAlgorithmEx);
}
}
private KeyManager loadClientCerts(String keyStoreUrl, String keyStorePassword,
String keyPassword) throws SQLException {
InputStream inStream = null;
try {
char[] keyStorePasswordChars =
keyStorePassword == null ? null : keyStorePassword.toCharArray();
try {
inStream = new URL(keyStoreUrl).openStream();
} catch (IOException ioexception) {
inStream = new FileInputStream(keyStoreUrl);
}
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(inStream, keyStorePasswordChars);
char[] keyStoreChars =
(keyPassword == null) ? keyStorePasswordChars : keyPassword.toCharArray();
return new MariaDbX509KeyManager(ks, keyStoreChars);
} catch (GeneralSecurityException generalSecurityEx) {
throw ExceptionMapper.connException("Failed to create keyStore instance", generalSecurityEx);
} catch (FileNotFoundException fileNotFoundEx) {
throw ExceptionMapper
.connException("Failed to find keyStore file. Option keyStore=" + keyStoreUrl,
fileNotFoundEx);
} catch (IOException ioEx) {
throw ExceptionMapper
.connException("Failed to read keyStore file. Option keyStore=" + keyStoreUrl, ioEx);
} finally {
try {
if (inStream != null) {
inStream.close();
}
} catch (IOException ioEx) {
//ignore error
}
}
}
/**
* InitializeSocketOption.
*/
private void initializeSocketOption() {
try {
socket.setTcpNoDelay(options.tcpNoDelay);
if (options.tcpKeepAlive) {
socket.setKeepAlive(true);
}
if (options.tcpRcvBuf != null) {
socket.setReceiveBufferSize(options.tcpRcvBuf);
}
if (options.tcpSndBuf != null) {
socket.setSendBufferSize(options.tcpSndBuf);
}
if (options.tcpAbortiveClose) {
socket.setSoLinger(true, 0);
}
} catch (Exception e) {
logger.debug("Failed to set socket option", e);
}
}
/**
* Connect to currentHost.
*
* @throws SQLException exception
*/
public void connect() throws SQLException {
if (!isClosed()) {
close();
}
try {
connect((currentHost != null) ? currentHost.host : null,
(currentHost != null) ? currentHost.port : 3306);
} catch (IOException ioException) {
throw ExceptionMapper.connException(
"Could not connect to " + currentHost + ". " + ioException.getMessage() + getTraces(),
ioException);
}
}
/**
* Connect the client and perform handshake.
*
* @param host host
* @param port port
* @throws SQLException handshake error, e.g wrong user or password
* @throws IOException connection error (host/port not available)
*/
private void connect(String host, int port) throws SQLException, IOException {
try {
socket = Utils.createSocket(urlParser, host);
if (options.socketTimeout != null) {
socket.setSoTimeout(options.socketTimeout);
}
initializeSocketOption();
// Bind the socket to a particular interface if the connection property
// localSocketAddress has been defined.
if (options.localSocketAddress != null) {
InetSocketAddress localAddress = new InetSocketAddress(options.localSocketAddress, 0);
socket.bind(localAddress);
}
if (!socket.isConnected()) {
InetSocketAddress sockAddr =
urlParser.getOptions().pipe == null ? new InetSocketAddress(host, port) : null;
if (options.connectTimeout != 0) {
socket.connect(sockAddr, options.connectTimeout);
} else {
socket.connect(sockAddr);
}
}
handleConnectionPhases(host);
connected = true;
if (options.useCompression) {
writer = new CompressPacketOutputStream(writer.getOutputStream(),
options.maxQuerySizeToLog);
reader = new DecompressPacketInputStream(
((StandardPacketInputStream) reader).getInputStream(),
options.maxQuerySizeToLog);
if (options.enablePacketDebug) {
writer.setTraceCache(traceCache);
reader.setTraceCache(traceCache);
}
}
boolean mustLoadAdditionalInfo = true;
if (globalInfo != null) {
if (globalInfo.isAutocommit() == options.autocommit) {
mustLoadAdditionalInfo = false;
}
}
if (mustLoadAdditionalInfo) {
Map<String, String> serverData = new TreeMap<>();
if (options.usePipelineAuth && !options.createDatabaseIfNotExist) {
try {
sendPipelineAdditionalData();
readPipelineAdditionalData(serverData);
} catch (SQLException sqle) {
if ("08".equals(sqle.getSQLState())) {
throw sqle;
}
//in case pipeline is not supported
//(proxy flush socket after reading first packet)
additionalData(serverData);
}
} else {
additionalData(serverData);
}
writer.setMaxAllowedPacket(Integer.parseInt(serverData.get("max_allowed_packet")));
autoIncrementIncrement = Integer.parseInt(serverData.get("auto_increment_increment"));
loadCalendar(serverData.get("time_zone"), serverData.get("system_time_zone"));
} else {
writer.setMaxAllowedPacket((int) globalInfo.getMaxAllowedPacket());
autoIncrementIncrement = globalInfo.getAutoIncrementIncrement();
loadCalendar(globalInfo.getTimeZone(), globalInfo.getSystemTimeZone());
}
reader.setServerThreadId(this.serverThreadId, isMasterConnection());
writer.setServerThreadId(this.serverThreadId, isMasterConnection());
activeStreamingResult = null;
hostFailed = false;
} catch (IOException | SQLException ioException) {
ensureClosingSocketOnException();
throw ioException;
}
}
/**
* Send all additional needed values. Command are send one after the other, assuming that command
* are less than 65k (minimum hosts TCP/IP buffer size)
*
* @throws IOException if socket exception occur
*/
private void sendPipelineAdditionalData() throws IOException {
sendSessionInfos();
sendRequestSessionVariables();
//for aurora, check that connection is master
sendPipelineCheckMaster();
}
private void sendSessionInfos() throws IOException {
// In JDBC, connection must start in autocommit mode
// [CONJ-269] we cannot rely on serverStatus & ServerStatus.AUTOCOMMIT before this command to avoid this command.
// if autocommit=0 is set on server configuration, DB always send Autocommit on serverStatus flag
// after setting autocommit, we can rely on serverStatus value
StringBuilder sessionOption = new StringBuilder("autocommit=")
.append(options.autocommit ? "1" : "0");
if ((serverCapabilities & MariaDbServerCapabilities.CLIENT_SESSION_TRACK) != 0) {
sessionOption.append(", session_track_schema=1");
if (options.rewriteBatchedStatements) {
sessionOption.append(", session_track_system_variables='auto_increment_increment' ");
}
}
if (options.jdbcCompliantTruncation) {
sessionOption.append(", sql_mode = concat(@@sql_mode,',STRICT_TRANS_TABLES')");
}
if (options.sessionVariables != null && !options.sessionVariables.isEmpty()) {
sessionOption.append(",").append(Utils.parseSessionVariables(options.sessionVariables));
}
writer.startPacket(0);
writer.write(COM_QUERY);
writer.write("set " + sessionOption.toString());
writer.flush();
}
private void sendRequestSessionVariables() throws IOException {
writer.startPacket(0);
writer.write(COM_QUERY);
writer.write(SESSION_QUERY);
writer.flush();
}
private void readRequestSessionVariables(Map<String, String> serverData) throws SQLException {
Results results = new Results();
getResult(results);
results.commandEnd();
ResultSet resultSet = results.getResultSet();
if (resultSet != null) {
resultSet.next();
serverData.put("max_allowed_packet", resultSet.getString(1));
serverData.put("system_time_zone", resultSet.getString(2));
serverData.put("time_zone", resultSet.getString(3));
serverData.put("auto_increment_increment", resultSet.getString(4));
} else {
throw new SQLException("Error reading SessionVariables results. Socket is connected ? "
+ socket.isConnected());
}
}
private void sendCreateDatabaseIfNotExist(String quotedDb) throws IOException {
writer.startPacket(0);
writer.write(COM_QUERY);
writer.write("CREATE DATABASE IF NOT EXISTS " + quotedDb);
writer.flush();
}
private void sendUseDatabaseIfNotExist(String quotedDb) throws IOException {
writer.startPacket(0);
writer.write(COM_QUERY);
writer.write("USE " + quotedDb);
writer.flush();
}
private void readPipelineAdditionalData(Map<String, String> serverData) throws SQLException {
SQLException resultingException = null;
//read set session OKPacket
try {
getResult(new Results());
} catch (SQLException sqlException) {
//must read all results, will be thrown only when all results are read.
resultingException = sqlException;
}
boolean canTrySessionWithShow = false;
try {
readRequestSessionVariables(serverData);
} catch (SQLException sqlException) {
if (resultingException == null) {
resultingException = ExceptionMapper
.connException("could not load system variables", sqlException);
canTrySessionWithShow = true;
}
}
try {
readPipelineCheckMaster();
} catch (SQLException sqlException) {
canTrySessionWithShow = false;
if (resultingException == null) {
throw ExceptionMapper
.connException("could not identified if server is master", sqlException);
}
}
if (canTrySessionWithShow) {
//fallback in case of galera non primary nodes that permit only show / set command,
//not SELECT when not part of quorum
requestSessionDataWithShow(serverData);
}
if (resultingException != null) {
throw resultingException;
}
connected = true;
}
private void requestSessionDataWithShow(Map<String, String> serverData) throws SQLException {
try {
Results results = new Results();
executeQuery(true, results, "SHOW VARIABLES WHERE Variable_name in ("
+ "'max_allowed_packet',"
+ "'system_time_zone',"
+ "'time_zone',"
+ "'auto_increment_increment')");
results.commandEnd();
ResultSet resultSet = results.getResultSet();
if (resultSet != null) {
while (resultSet.next()) {
if (logger.isDebugEnabled()) {
logger.debug("server data {} = {}",
resultSet.getString(1),
resultSet.getString(2));
}
serverData.put(resultSet.getString(1), resultSet.getString(2));
}
if (serverData.size() < 4) {
throw ExceptionMapper.connException(
"could not load system variables. socket connected: " + socket.isConnected());
}
}
} catch (SQLException sqlException) {
throw ExceptionMapper.connException("could not load system variables", sqlException);
}
}
private void additionalData(Map<String, String> serverData) throws IOException, SQLException {
sendSessionInfos();
getResult(new Results());
try {
sendRequestSessionVariables();
readRequestSessionVariables(serverData);
} catch (SQLException sqlException) {
requestSessionDataWithShow(serverData);
}
//for aurora, check that connection is master
sendPipelineCheckMaster();
readPipelineCheckMaster();
if (options.createDatabaseIfNotExist && !database.isEmpty()) {
// Try to create the database if it does not exist
String quotedDb = MariaDbConnection.quoteIdentifier(this.database);
sendCreateDatabaseIfNotExist(quotedDb);
getResult(new Results());
sendUseDatabaseIfNotExist(quotedDb);
getResult(new Results());
}
}
private void ensureClosingSocketOnException() {
if (socket != null) {
try {
socket.close();
} catch (IOException ioe) {
//eat exception
}
}
}
/**
* Is the connection closed.
*
* @return true if the connection is closed
*/
public boolean isClosed() {
return !this.connected;
}
private void handleConnectionPhases(String host) throws SQLException {
try {
reader = new StandardPacketInputStream(socket.getInputStream(), options);
writer = new StandardPacketOutputStream(socket.getOutputStream(), options);
if (options.enablePacketDebug) {
writer.setTraceCache(traceCache);
reader.setTraceCache(traceCache);
}
final ReadInitialHandShakePacket greetingPacket = new ReadInitialHandShakePacket(reader);
this.serverThreadId = greetingPacket.getServerThreadId();
reader.setServerThreadId(this.serverThreadId, null);
writer.setServerThreadId(this.serverThreadId, null);
this.serverVersion = greetingPacket.getServerVersion();
this.serverMariaDb = greetingPacket.isServerMariaDb();
this.serverCapabilities = greetingPacket.getServerCapabilities();
parseVersion();
byte exchangeCharset = decideLanguage(greetingPacket.getServerLanguage() & 0xFF);
long clientCapabilities = initializeClientCapabilities(serverCapabilities);
byte packetSeq = 1;
if (options.useSsl
&& (greetingPacket.getServerCapabilities() & MariaDbServerCapabilities.SSL) != 0) {
clientCapabilities |= MariaDbServerCapabilities.SSL;
SendSslConnectionRequestPacket amcap = new SendSslConnectionRequestPacket(
clientCapabilities, exchangeCharset);
amcap.send(writer);
SSLSocketFactory sslSocketFactory = getSslSocketFactory();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket,
socket.getInetAddress().getHostAddress(), socket.getPort(), true);
enabledSslProtocolSuites(sslSocket);
enabledSslCipherSuites(sslSocket);
sslSocket.setUseClientMode(true);
sslSocket.startHandshake();
// perform hostname verification
// (rfc2818 indicate that if "client has external information as to the expected identity of the server,
// the hostname check MAY be omitted")
if (!options.disableSslHostnameVerification && !options.trustServerCertificate) {
HostnameVerifierImpl hostnameVerifier = new HostnameVerifierImpl();
SSLSession session = sslSocket.getSession();
if (!hostnameVerifier.verify(host, session, serverThreadId)) {
//Use proprietary verify method in order to have an exception with a better description of error.
try {
Certificate[] certs = session.getPeerCertificates();
X509Certificate cert = (X509Certificate) certs[0];
hostnameVerifier.verify(host, cert, serverThreadId);
} catch (SSLException ex) {
throw new SQLNonTransientConnectionException(
"SSL hostname verification failed : " + ex.getMessage()
+ "\nThis verification can be disabled using the option \"disableSslHostnameVerification\" "
+ "but won't prevent man-in-the-middle attacks anymore", "08006");
}
}
}
socket = sslSocket;
writer = new StandardPacketOutputStream(socket.getOutputStream(), options);
reader = new StandardPacketInputStream(socket.getInputStream(), options);
if (options.enablePacketDebug) {
writer.setTraceCache(traceCache);
reader.setTraceCache(traceCache);
}
packetSeq++;
} else if (options.useSsl) {
throw new SQLException("Trying to connect with ssl, but ssl not enabled in the server");
}
authentication(exchangeCharset, clientCapabilities, packetSeq, greetingPacket);
} catch (IOException ioException) {
if (reader != null) {
try {
reader.close();
} catch (IOException ee) {
//eat exception
}
}
if (currentHost == null) {
throw ExceptionMapper.connException(
"Could not connect to socket : " + ioException.getMessage(),
ioException);
}
throw ExceptionMapper.connException(
"Could not connect to " + currentHost.host + ":" + currentHost.port + " : " + ioException
.getMessage(),
ioException);
}
}
private void authentication(byte exchangeCharset, long clientCapabilities, byte packetSeq,
ReadInitialHandShakePacket greetingPacket)
throws SQLException, IOException {
//send handshake response
SendHandshakeResponsePacket.send(writer, this.username,
this.password,
this.currentHost,
database,
clientCapabilities,
serverCapabilities,
exchangeCharset,
packetSeq,
options,
greetingPacket);
Buffer buffer = reader.getPacket(false);
if ((buffer.getByteAt(0) & 0xFF) == 0xFE) {
writer.permitTrace(false);
InterfaceAuthSwitchSendResponsePacket interfaceSendPacket;
if ((serverCapabilities & MariaDbServerCapabilities.PLUGIN_AUTH) != 0) {
buffer.readByte();
byte[] authData;
String plugin;
if (buffer.remaining() > 0) {
//AuthSwitchRequest packet.
plugin = buffer.readStringNullEnd(Charset.forName("ASCII"));
authData = buffer.readRawBytes(buffer.remaining());
} else {
//OldAuthSwitchRequest
plugin = DefaultAuthenticationProvider.MYSQL_OLD_PASSWORD;
authData = Utils.copyWithLength(greetingPacket.getSeed(), 8);
}
//Authentication according to plugin.
//see AuthenticationProviderHolder for implement other plugin
interfaceSendPacket = AuthenticationProviderHolder.getAuthenticationProvider()
.processAuthPlugin(reader, plugin, password, authData, reader.getLastPacketSeq() + 1,
options.passwordCharacterEncoding);
} else {
interfaceSendPacket = new SendOldPasswordAuthPacket(this.password,
Utils.copyWithLength(greetingPacket.getSeed(), 8),
reader.getLastPacketSeq() + 1, options.passwordCharacterEncoding);
}
interfaceSendPacket.send(writer);
interfaceSendPacket.handleResultPacket(reader);
} else {
if (buffer.getByteAt(0) == ERROR) {
ErrorPacket errorPacket = new ErrorPacket(buffer);
if (password != null && !password.isEmpty() && errorPacket.getErrorNumber() == 1045
&& "28000".equals(errorPacket.getSqlState())) {
//Access denied
throw new SQLException(errorPacket.getMessage()
+ "\nCurrent charset is " + Charset.defaultCharset().displayName()
+ ". If password has been set using other charset, consider "
+ "using option 'passwordCharacterEncoding'",
errorPacket.getSqlState(), errorPacket.getErrorNumber());
}
throw new SQLException(errorPacket.getMessage(), errorPacket.getSqlState(),
errorPacket.getErrorNumber());
}
serverStatus = new OkPacket(buffer).getServerStatus();
}
writer.permitTrace(true);
}
private long initializeClientCapabilities(long serverCapabilities) {
long capabilities = MariaDbServerCapabilities.IGNORE_SPACE
| MariaDbServerCapabilities.CLIENT_PROTOCOL_41
| MariaDbServerCapabilities.TRANSACTIONS
| MariaDbServerCapabilities.SECURE_CONNECTION
| MariaDbServerCapabilities.LOCAL_FILES
| MariaDbServerCapabilities.MULTI_RESULTS
| MariaDbServerCapabilities.PS_MULTI_RESULTS
| MariaDbServerCapabilities.PLUGIN_AUTH
| MariaDbServerCapabilities.CONNECT_ATTRS
| MariaDbServerCapabilities.PLUGIN_AUTH_LENENC_CLIENT_DATA
| MariaDbServerCapabilities.CLIENT_SESSION_TRACK;
// MySQL/MariaDB has two ways of calculating row count, eg for an UPDATE statement.
// The default (and JDBC standard) is "found rows". The other option is "affected rows".
// See https://jira.mariadb.org/browse/CONJ-384
if (!options.useAffectedRows) {
capabilities |= MariaDbServerCapabilities.FOUND_ROWS;
}
if (options.allowMultiQueries || (options.rewriteBatchedStatements)) {
capabilities |= MariaDbServerCapabilities.MULTI_STATEMENTS;
}
if ((serverCapabilities & MariaDbServerCapabilities.CLIENT_DEPRECATE_EOF) != 0) {
capabilities |= MariaDbServerCapabilities.CLIENT_DEPRECATE_EOF;
eofDeprecated = true;
}
if (options.useCompression) {
if ((serverCapabilities & MariaDbServerCapabilities.COMPRESS) == 0) {
//ensure that server has compress capacity - MaxScale doesn't
options.useCompression = false;
} else {
capabilities |= MariaDbServerCapabilities.COMPRESS;
}
}
if (options.interactiveClient) {
capabilities |= MariaDbServerCapabilities.CLIENT_INTERACTIVE;
}
// If a database is given, but createDatabaseIfNotExist is not defined or is false,
// then just try to connect to the given database
if (!database.isEmpty() && !options.createDatabaseIfNotExist) {
capabilities |= MariaDbServerCapabilities.CONNECT_WITH_DB;
}
return capabilities;
}
private void loadCalendar(final String srvTimeZone, final String srvSystemTimeZone)
throws SQLException {
if (options.useLegacyDatetimeCode) {
//legacy use client timezone
timeZone = Calendar.getInstance().getTimeZone();
} else {
//use server time zone
String tz = options.serverTimezone;
if (tz == null) {
tz = srvTimeZone;
if ("SYSTEM".equals(tz)) {
tz = srvSystemTimeZone;
}
}