forked from microsoft/mssql-jdbc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSQLServerConnection.java
5184 lines (4427 loc) · 245 KB
/
SQLServerConnection.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
/*
* Microsoft JDBC Driver for SQL Server
*
* Copyright(c) Microsoft Corporation All rights reserved.
*
* This program is made available under the terms of the MIT License. See the LICENSE file in the project root for more information.
*/
package com.microsoft.sqlserver.jdbc;
import static java.nio.charset.StandardCharsets.UTF_16LE;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.IDN;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLPermission;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import javax.sql.XAConnection;
import javax.xml.bind.DatatypeConverter;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
/**
* SQLServerConnection implements a JDBC connection to SQL Server. SQLServerConnections support JDBC connection pooling and may be either physical
* JDBC connections or logical JDBC connections.
* <p>
* SQLServerConnection manages transaction control for all statements that were created from it. SQLServerConnection may participate in XA distributed
* transactions managed via an XAResource adapter.
* <p>
* SQLServerConnection instantiates a new TDSChannel object for use by itself and all statement objects that are created under this connection.
* SQLServerConnection is thread safe.
* <p>
* SQLServerConnection manages a pool of prepared statement handles. Prepared statements are prepared once and typically executed many times with
* different data values for their parameters. Prepared statements are also maintained across logical (pooled) connection closes.
* <p>
* SQLServerConnection is not thread safe, however multiple statements created from a single connection can be processing simultaneously in concurrent
* threads.
* <p>
* This class's public functions need to be kept identical to the SQLServerConnectionPoolProxy's.
* <p>
* The API javadoc for JDBC API methods that this class implements are not repeated here. Please see Sun's JDBC API interfaces javadoc for those
* details.
*/
// Note all the public functions in this class also need to be defined in SQLServerConnectionPoolProxy.
public class SQLServerConnection implements ISQLServerConnection {
long timerExpire;
boolean attemptRefreshTokenLocked = false;
private boolean fedAuthRequiredByUser = false;
private boolean fedAuthRequiredPreLoginResponse = false;
private boolean federatedAuthenticationAcknowledged = false;
private boolean federatedAuthenticationRequested = false;
private boolean federatedAuthenticationInfoRequested = false; // Keep this distinct from _federatedAuthenticationRequested, since some fedauth
// library types may not need more info
private FederatedAuthenticationFeatureExtensionData fedAuthFeatureExtensionData = null;
private String authenticationString = null;
private byte[] accessTokenInByte = null;
private SqlFedAuthToken fedAuthToken = null;
SqlFedAuthToken getAuthenticationResult() {
return fedAuthToken;
}
/**
* Struct encapsulating the data to be sent to the server as part of Federated Authentication Feature Extension.
*/
class FederatedAuthenticationFeatureExtensionData {
boolean fedAuthRequiredPreLoginResponse;
int libraryType = -1;
byte[] accessToken = null;
SqlAuthentication authentication = null;
FederatedAuthenticationFeatureExtensionData(int libraryType,
String authenticationString,
boolean fedAuthRequiredPreLoginResponse) throws SQLServerException {
this.libraryType = libraryType;
this.fedAuthRequiredPreLoginResponse = fedAuthRequiredPreLoginResponse;
switch (authenticationString.toUpperCase(Locale.ENGLISH).trim()) {
case "ACTIVEDIRECTORYPASSWORD":
this.authentication = SqlAuthentication.ActiveDirectoryPassword;
break;
case "ACTIVEDIRECTORYINTEGRATED":
this.authentication = SqlAuthentication.ActiveDirectoryIntegrated;
break;
default:
assert (false);
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_InvalidConnectionSetting"));
Object[] msgArgs = {"authentication", authenticationString};
throw new SQLServerException(null, form.format(msgArgs), null, 0, false);
}
}
FederatedAuthenticationFeatureExtensionData(int libraryType,
boolean fedAuthRequiredPreLoginResponse,
byte[] accessToken) {
this.libraryType = libraryType;
this.fedAuthRequiredPreLoginResponse = fedAuthRequiredPreLoginResponse;
this.accessToken = accessToken;
}
}
class SqlFedAuthInfo {
String spn;
String stsurl;
@Override
public String toString() {
return "STSURL: " + stsurl + ", SPN: " + spn;
}
}
class ActiveDirectoryAuthentication {
static final String JDBC_FEDAUTH_CLIENT_ID = "7f98cb04-cd1e-40df-9140-3bf7e2cea4db";
static final String ADAL_GET_ACCESS_TOKEN_FUNCTION_NAME = "ADALGetAccessToken";
static final int GET_ACCESS_TOKEN_SUCCESS = 0;
static final int GET_ACCESS_TOKEN_INVALID_GRANT = 1;
static final int GET_ACCESS_TOKEN_TANSISENT_ERROR = 2;
static final int GET_ACCESS_TOKEN_OTHER_ERROR = 3;
}
/**
* denotes the state of the SqlServerConnection
*/
private enum State {
Initialized,// default value on calling SQLServerConnection constructor
Connected, // indicates that the TCP connection has completed
Opened, // indicates that the prelogin, login have completed, the database session established and the connection is ready for use.
Closed // indicates that the connection has been closed.
}
private final static float TIMEOUTSTEP = 0.08F; // fraction of timeout to use for fast failover connections
final static int TnirFirstAttemptTimeoutMs = 500; // fraction of timeout to use for fast failover connections
/*
* Connection state variables. NB If new state is added then logical connections derived from a physical connection must inherit the same state.
* If state variables are added they must be added also in connection cloning method clone()
*/
private final static int INTERMITTENT_TLS_MAX_RETRY = 5;
// Indicates if we received a routing ENVCHANGE in the current connection attempt
private boolean isRoutedInCurrentAttempt = false;
// Contains the routing info received from routing ENVCHANGE
private ServerPortPlaceHolder routingInfo = null;
ServerPortPlaceHolder getRoutingInfo() {
return routingInfo;
}
// Permission targets
// currently only callAbort is implemented
private static final String callAbortPerm = "callAbort";
private boolean sendStringParametersAsUnicode = SQLServerDriverBooleanProperty.SEND_STRING_PARAMETERS_AS_UNICODE.getDefaultValue(); // see
// connection
// properties
// doc
// (default
// is
// false).
boolean sendStringParametersAsUnicode() {
return sendStringParametersAsUnicode;
}
private boolean lastUpdateCount; // see connection properties doc
final boolean useLastUpdateCount() {
return lastUpdateCount;
}
// Translates the serverName from Unicode to ASCII Compatible Encoding (ACE), as defined by the ToASCII operation of RFC 3490
private boolean serverNameAsACE = SQLServerDriverBooleanProperty.SERVER_NAME_AS_ACE.getDefaultValue();
boolean serverNameAsACE() {
return serverNameAsACE;
}
// see feature_connection_director_multi_subnet_JDBC.docx
private boolean multiSubnetFailover;
final boolean getMultiSubnetFailover() {
return multiSubnetFailover;
}
private boolean transparentNetworkIPResolution;
final boolean getTransparentNetworkIPResolution() {
return transparentNetworkIPResolution;
}
private ApplicationIntent applicationIntent = null;
final ApplicationIntent getApplicationIntent() {
return applicationIntent;
}
private int nLockTimeout; // see connection properties doc
private String selectMethod; // see connection properties doc 4.0 new property
final String getSelectMethod() {
return selectMethod;
}
private String responseBuffering;
final String getResponseBuffering() {
return responseBuffering;
}
private int queryTimeoutSeconds;
final int getQueryTimeoutSeconds() {
return queryTimeoutSeconds;
}
private int socketTimeoutMilliseconds;
final int getSocketTimeoutMilliseconds() {
return socketTimeoutMilliseconds;
}
private boolean sendTimeAsDatetime = SQLServerDriverBooleanProperty.SEND_TIME_AS_DATETIME.getDefaultValue();
/**
* Checks the sendTimeAsDatetime property.
*
* @return boolean value of sendTimeAsDatetime
*/
public synchronized final boolean getSendTimeAsDatetime() {
return !isKatmaiOrLater() || sendTimeAsDatetime;
}
final int baseYear() {
return getSendTimeAsDatetime() ? TDS.BASE_YEAR_1970 : TDS.BASE_YEAR_1900;
}
private byte requestedEncryptionLevel = TDS.ENCRYPT_INVALID;
final byte getRequestedEncryptionLevel() {
assert TDS.ENCRYPT_INVALID != requestedEncryptionLevel;
return requestedEncryptionLevel;
}
private boolean trustServerCertificate;
final boolean trustServerCertificate() {
return trustServerCertificate;
}
private byte negotiatedEncryptionLevel = TDS.ENCRYPT_INVALID;
final byte getNegotiatedEncryptionLevel() {
assert TDS.ENCRYPT_INVALID != negotiatedEncryptionLevel;
return negotiatedEncryptionLevel;
}
static final String RESERVED_PROVIDER_NAME_PREFIX = "MSSQL_";
String columnEncryptionSetting = null;
boolean isColumnEncryptionSettingEnabled() {
return (columnEncryptionSetting.equalsIgnoreCase(ColumnEncryptionSetting.Enabled.toString()));
}
String keyStoreAuthentication = null;
String keyStoreSecret = null;
String keyStoreLocation = null;
private boolean serverSupportsColumnEncryption = false;
boolean getServerSupportsColumnEncryption() {
return serverSupportsColumnEncryption;
}
static boolean isWindows;
static Map<String, SQLServerColumnEncryptionKeyStoreProvider> globalSystemColumnEncryptionKeyStoreProviders = new HashMap<String, SQLServerColumnEncryptionKeyStoreProvider>();
static {
if (System.getProperty("os.name").toLowerCase(Locale.ENGLISH).startsWith("windows")) {
isWindows = true;
SQLServerColumnEncryptionCertificateStoreProvider provider = new SQLServerColumnEncryptionCertificateStoreProvider();
globalSystemColumnEncryptionKeyStoreProviders.put(provider.getName(), provider);
}
else {
isWindows = false;
}
}
static Map<String, SQLServerColumnEncryptionKeyStoreProvider> globalCustomColumnEncryptionKeyStoreProviders = null;
// This is a per-connection store provider. It can be JKS or AKV.
Map<String, SQLServerColumnEncryptionKeyStoreProvider> systemColumnEncryptionKeyStoreProvider = new HashMap<String, SQLServerColumnEncryptionKeyStoreProvider>();
/**
* Registers key store providers in the globalCustomColumnEncryptionKeyStoreProviders.
*
* @param clientKeyStoreProviders
* a map containing the store providers information.
* @throws SQLServerException
* when an error occurs
*/
public static synchronized void registerColumnEncryptionKeyStoreProviders(
Map<String, SQLServerColumnEncryptionKeyStoreProvider> clientKeyStoreProviders) throws SQLServerException {
loggerExternal.entering(SQLServerConnection.class.getName(), "registerColumnEncryptionKeyStoreProviders",
"Registering Column Encryption Key Store Providers");
if (null == clientKeyStoreProviders) {
throw new SQLServerException(null, SQLServerException.getErrString("R_CustomKeyStoreProviderMapNull"), null, 0, false);
}
if (null != globalCustomColumnEncryptionKeyStoreProviders) {
throw new SQLServerException(null, SQLServerException.getErrString("R_CustomKeyStoreProviderSetOnce"), null, 0, false);
}
globalCustomColumnEncryptionKeyStoreProviders = new HashMap<String, SQLServerColumnEncryptionKeyStoreProvider>();
for (Map.Entry<String, SQLServerColumnEncryptionKeyStoreProvider> entry : clientKeyStoreProviders.entrySet()) {
String providerName = entry.getKey();
if (null == providerName || 0 == providerName.length()) {
throw new SQLServerException(null, SQLServerException.getErrString("R_EmptyCustomKeyStoreProviderName"), null, 0, false);
}
if ((providerName.substring(0, 6).equalsIgnoreCase(RESERVED_PROVIDER_NAME_PREFIX))) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_InvalidCustomKeyStoreProviderName"));
Object[] msgArgs = {providerName, RESERVED_PROVIDER_NAME_PREFIX};
throw new SQLServerException(null, form.format(msgArgs), null, 0, false);
}
if (null == entry.getValue()) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_CustomKeyStoreProviderValueNull"));
Object[] msgArgs = {providerName, RESERVED_PROVIDER_NAME_PREFIX};
throw new SQLServerException(null, form.format(msgArgs), null, 0, false);
}
globalCustomColumnEncryptionKeyStoreProviders.put(entry.getKey(), entry.getValue());
}
loggerExternal.exiting(SQLServerConnection.class.getName(), "registerColumnEncryptionKeyStoreProviders",
"Number of Key store providers that are registered:" + globalCustomColumnEncryptionKeyStoreProviders.size());
}
static synchronized SQLServerColumnEncryptionKeyStoreProvider getGlobalSystemColumnEncryptionKeyStoreProvider(String providerName) {
if (null != globalSystemColumnEncryptionKeyStoreProviders && globalSystemColumnEncryptionKeyStoreProviders.containsKey(providerName)) {
return globalSystemColumnEncryptionKeyStoreProviders.get(providerName);
}
return null;
}
static synchronized String getAllGlobalCustomSystemColumnEncryptionKeyStoreProviders() {
if (null != globalCustomColumnEncryptionKeyStoreProviders)
return globalCustomColumnEncryptionKeyStoreProviders.keySet().toString();
else
return null;
}
synchronized String getAllSystemColumnEncryptionKeyStoreProviders() {
String keyStores = "";
if (0 != systemColumnEncryptionKeyStoreProvider.size())
keyStores = systemColumnEncryptionKeyStoreProvider.keySet().toString();
if (0 != SQLServerConnection.globalSystemColumnEncryptionKeyStoreProviders.size())
keyStores += "," + SQLServerConnection.globalSystemColumnEncryptionKeyStoreProviders.keySet().toString();
return keyStores;
}
static synchronized SQLServerColumnEncryptionKeyStoreProvider getGlobalCustomColumnEncryptionKeyStoreProvider(String providerName) {
if (null != globalCustomColumnEncryptionKeyStoreProviders && globalCustomColumnEncryptionKeyStoreProviders.containsKey(providerName)) {
return globalCustomColumnEncryptionKeyStoreProviders.get(providerName);
}
return null;
}
synchronized SQLServerColumnEncryptionKeyStoreProvider getSystemColumnEncryptionKeyStoreProvider(String providerName) {
if ((null != systemColumnEncryptionKeyStoreProvider) && (systemColumnEncryptionKeyStoreProvider.containsKey(providerName))) {
return systemColumnEncryptionKeyStoreProvider.get(providerName);
}
else {
return null;
}
}
private String trustedServerNameAE = null;
private static Map<String, List<String>> columnEncryptionTrustedMasterKeyPaths = new HashMap<String, List<String>>();
/**
* Sets Trusted Master Key Paths in the columnEncryptionTrustedMasterKeyPaths.
*
* @param trustedKeyPaths
* all master key paths that are trusted
*/
public static synchronized void setColumnEncryptionTrustedMasterKeyPaths(Map<String, List<String>> trustedKeyPaths) {
loggerExternal.entering(SQLServerConnection.class.getName(), "setColumnEncryptionTrustedMasterKeyPaths", "Setting Trusted Master Key Paths");
// Use upper case for server and instance names.
columnEncryptionTrustedMasterKeyPaths.clear();
for (Map.Entry<String, List<String>> entry : trustedKeyPaths.entrySet()) {
columnEncryptionTrustedMasterKeyPaths.put(entry.getKey().toUpperCase(), entry.getValue());
}
loggerExternal.exiting(SQLServerConnection.class.getName(), "setColumnEncryptionTrustedMasterKeyPaths",
"Number of Trusted Master Key Paths: " + columnEncryptionTrustedMasterKeyPaths.size());
}
/**
* Updates the columnEncryptionTrustedMasterKeyPaths with the new Server and trustedKeyPaths.
*
* @param server
* String server name
* @param trustedKeyPaths
* all master key paths that are trusted
*/
public static synchronized void updateColumnEncryptionTrustedMasterKeyPaths(String server,
List<String> trustedKeyPaths) {
loggerExternal.entering(SQLServerConnection.class.getName(), "updateColumnEncryptionTrustedMasterKeyPaths",
"Updating Trusted Master Key Paths");
// Use upper case for server and instance names.
columnEncryptionTrustedMasterKeyPaths.put(server.toUpperCase(), trustedKeyPaths);
loggerExternal.exiting(SQLServerConnection.class.getName(), "updateColumnEncryptionTrustedMasterKeyPaths",
"Number of Trusted Master Key Paths: " + columnEncryptionTrustedMasterKeyPaths.size());
}
/**
* Removes the trusted Master key Path from the columnEncryptionTrustedMasterKeyPaths.
*
* @param server
* String server name
*/
public static synchronized void removeColumnEncryptionTrustedMasterKeyPaths(String server) {
loggerExternal.entering(SQLServerConnection.class.getName(), "removeColumnEncryptionTrustedMasterKeyPaths",
"Removing Trusted Master Key Paths");
// Use upper case for server and instance names.
columnEncryptionTrustedMasterKeyPaths.remove(server.toUpperCase());
loggerExternal.exiting(SQLServerConnection.class.getName(), "removeColumnEncryptionTrustedMasterKeyPaths",
"Number of Trusted Master Key Paths: " + columnEncryptionTrustedMasterKeyPaths.size());
}
/**
* Retrieves the Trusted Master Key Paths.
*
* @return columnEncryptionTrustedMasterKeyPaths.
*/
public static synchronized Map<String, List<String>> getColumnEncryptionTrustedMasterKeyPaths() {
loggerExternal.entering(SQLServerConnection.class.getName(), "getColumnEncryptionTrustedMasterKeyPaths", "Getting Trusted Master Key Paths");
Map<String, List<String>> masterKeyPathCopy = new HashMap<String, List<String>>();
for (Map.Entry<String, List<String>> entry : columnEncryptionTrustedMasterKeyPaths.entrySet()) {
masterKeyPathCopy.put(entry.getKey(), entry.getValue());
}
loggerExternal.exiting(SQLServerConnection.class.getName(), "getColumnEncryptionTrustedMasterKeyPaths",
"Number of Trusted Master Key Paths: " + masterKeyPathCopy.size());
return masterKeyPathCopy;
}
static synchronized List<String> getColumnEncryptionTrustedMasterKeyPaths(String server,
Boolean[] hasEntry) {
if (columnEncryptionTrustedMasterKeyPaths.containsKey(server)) {
hasEntry[0] = true;
return columnEncryptionTrustedMasterKeyPaths.get(server);
}
else {
hasEntry[0] = false;
return null;
}
}
Properties activeConnectionProperties; // the active set of connection properties
private boolean integratedSecurity = SQLServerDriverBooleanProperty.INTEGRATED_SECURITY.getDefaultValue();
private AuthenticationScheme intAuthScheme = AuthenticationScheme.nativeAuthentication;
private GSSCredential ImpersonatedUserCred ;
// This is the current connect place holder this should point one of the primary or failover place holder
ServerPortPlaceHolder currentConnectPlaceHolder = null;
String sqlServerVersion; // SQL Server version string
boolean xopenStates; // XOPEN or SQL 92 state codes?
private boolean databaseAutoCommitMode;
private boolean inXATransaction = false; // Set to true when in an XA transaction.
private byte[] transactionDescriptor = new byte[8];
// Flag (Yukon and later) set to true whenever a transaction is rolled back.
// The flag's value is reset to false when a new transaction starts or when the autoCommit mode changes.
private boolean rolledBackTransaction;
final boolean rolledBackTransaction() {
return rolledBackTransaction;
}
private State state = State.Initialized; // connection state
private void setState(State state) {
this.state = state;
}
// This function actually represents whether a database session is not open.
// The session is not available before the session is established and
// after the session is closed.
final boolean isSessionUnAvailable() {
return !(state.equals(State.Opened));
}
final static int maxDecimalPrecision = 38; // @@max_precision for SQL 2000 and 2005 is 38.
final static int defaultDecimalPrecision = 18;
final String traceID;
/** Limit for the size of data (in bytes) returned for value on this connection */
private int maxFieldSize; // default: 0 --> no limit
final void setMaxFieldSize(int limit) throws SQLServerException {
// assert limit >= 0;
if (maxFieldSize != limit) {
if (loggerExternal.isLoggable(Level.FINER) && Util.IsActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
// If no limit on field size, set text size to max (2147483647), NOT default (0 --> 4K)
connectionCommand("SET TEXTSIZE " + ((0 == limit) ? 2147483647 : limit), "setMaxFieldSize");
maxFieldSize = limit;
}
}
// This function is used both to init the values on creation of connection
// and resetting the values after the connection is released to the pool for reuse.
final void initResettableValues() {
rolledBackTransaction = false;
transactionIsolationLevel = Connection.TRANSACTION_READ_COMMITTED;// default isolation level
maxFieldSize = 0; // default: 0 --> no limit
maxRows = 0; // default: 0 --> no limit
nLockTimeout = -1;
databaseAutoCommitMode = true;// auto commit mode
holdability = ResultSet.HOLD_CURSORS_OVER_COMMIT;
sqlWarnings = null;
sCatalog = originalCatalog;
databaseMetaData = null;
}
/** Limit for the maximum number of rows returned from queries on this connection */
private int maxRows; // default: 0 --> no limit
final void setMaxRows(int limit) throws SQLServerException {
// assert limit >= 0;
if (maxRows != limit) {
if (loggerExternal.isLoggable(Level.FINER) && Util.IsActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
connectionCommand("SET ROWCOUNT " + limit, "setMaxRows");
maxRows = limit;
}
}
private SQLCollation databaseCollation; // Default database collation read from ENVCHANGE_SQLCOLLATION token.
final SQLCollation getDatabaseCollation() {
return databaseCollation;
}
static private final AtomicInteger baseConnectionID = new AtomicInteger(0); // connection id dispenser
// This is the current catalog
private String sCatalog = "master"; // the database catalog
// This is the catalog immediately after login.
private String originalCatalog = "master";
private int transactionIsolationLevel;
private SQLServerPooledConnection pooledConnectionParent;
private DatabaseMetaData databaseMetaData; // the meta data for this connection
private int nNextSavePointId = 10000; // first save point id
static final private java.util.logging.Logger connectionlogger = java.util.logging.Logger
.getLogger("com.microsoft.sqlserver.jdbc.internals.SQLServerConnection");
static final private java.util.logging.Logger loggerExternal = java.util.logging.Logger.getLogger("com.microsoft.sqlserver.jdbc.Connection");
private final String loggingClassName;
// there are three ways to get a failover partner
// connection string, from the failover map, the connecting server returned
// the following variable only stores the serverReturned failver information.
private String failoverPartnerServerProvided = null;
private int holdability;
final int getHoldabilityInternal() {
return holdability;
}
// Default TDS packet size used after logon if no other value was set via
// the packetSize connection property. The value was chosen to take maximum
// advantage of SQL Server's default page size.
private int tdsPacketSize = TDS.INITIAL_PACKET_SIZE;
private int requestedPacketSize = TDS.DEFAULT_PACKET_SIZE;
final int getTDSPacketSize() {
return tdsPacketSize;
}
private TDSChannel tdsChannel;
private TDSCommand currentCommand = null;
private int tdsVersion = TDS.VER_UNKNOWN;
final boolean isKatmaiOrLater() {
assert TDS.VER_UNKNOWN != tdsVersion;
assert tdsVersion >= TDS.VER_YUKON;
return tdsVersion >= TDS.VER_KATMAI;
}
final boolean isDenaliOrLater() {
return tdsVersion >= TDS.VER_DENALI;
}
private int serverMajorVersion;
int getServerMajorVersion() {
return serverMajorVersion;
}
private SQLServerConnectionPoolProxy proxy;
private UUID clientConnectionId = null;
/**
* Retrieves the clientConnectionID.
*
* @throws SQLServerException
* when an error occurs
*/
public UUID getClientConnectionId() throws SQLServerException {
// If the connection is closed, we do not allow external application to get
// ClientConnectionId.
checkClosed();
return clientConnectionId;
}
// This function is called internally, e.g. when login process fails, we
// need to append the ClientConnectionId to error string.
final UUID getClientConIdInternal() {
return clientConnectionId;
}
final boolean attachConnId() {
return state.equals(State.Connected);
}
@SuppressWarnings("unused")
SQLServerConnection(String parentInfo) throws SQLServerException {
int connectionID = nextConnectionID(); // sequential connection id
traceID = "ConnectionID:" + connectionID;
loggingClassName = "com.microsoft.sqlserver.jdbc.SQLServerConnection:" + connectionID;
if (connectionlogger.isLoggable(Level.FINE))
connectionlogger.fine(toString() + " created by (" + parentInfo + ")");
initResettableValues();
// JDBC 3 driver only works with 1.5 JRE
if (3 == DriverJDBCVersion.major && !Util.SYSTEM_SPEC_VERSION.equals("1.5")) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unsupportedJREVersion"));
Object[] msgArgs = {Util.SYSTEM_SPEC_VERSION};
String message = form.format(msgArgs);
connectionlogger.severe(message);
throw new UnsupportedOperationException(message);
}
}
void setFailoverPartnerServerProvided(String partner) {
failoverPartnerServerProvided = partner;
// after login this info should be added to the map
}
final void setAssociatedProxy(SQLServerConnectionPoolProxy proxy) {
this.proxy = proxy;
}
/*
* This function is used by the functions that return a connection object to outside world. E.g. stmt.getConnection, these functions should return
* the proxy not the actual physical connection when the physical connection is pooled and the user should be accessing the connection functions
* via the proxy object.
*/
final Connection getConnection() {
if (null != proxy)
return proxy;
else
return this;
}
final void resetPooledConnection() {
tdsChannel.resetPooledConnection();
initResettableValues();
}
/**
* Generate the next unique connection id.
*
* @return the next conn id
*/
/* L0 */ private static int nextConnectionID() {
return baseConnectionID.incrementAndGet(); // 4.04 Ensure thread safe id allocation
}
java.util.logging.Logger getConnectionLogger() {
return connectionlogger;
}
String getClassNameLogging() {
return loggingClassName;
}
/**
* This is a helper function to provide an ID string suitable for tracing.
*/
public String toString() {
if (null != clientConnectionId)
return traceID + " ClientConnectionId: " + clientConnectionId.toString();
else
return traceID;
}
/**
* Throw a not implemeneted exception.
*
* @throws SQLServerException
*/
/* L0 */ void NotImplemented() throws SQLServerException {
SQLServerException.makeFromDriverError(this, this, SQLServerException.getErrString("R_notSupported"), null, false);
}
/**
* Check if the connection is closed Create a new connection if it's a fedauth connection and the access token is going to expire.
*
* @throws SQLServerException
*/
/* L0 */ void checkClosed() throws SQLServerException {
if (isSessionUnAvailable()) {
SQLServerException.makeFromDriverError(null, null, SQLServerException.getErrString("R_connectionIsClosed"), null, false);
}
if (null != fedAuthToken) {
if (Util.checkIfNeedNewAccessToken(this)) {
connect(this.activeConnectionProperties, null);
}
}
}
/**
* Check if a string property is enabled.
*
* @param propName
* the string property name
* @param propValue
* the string property value.
* @return false if p == null (meaning take default).
* @return true if p == "true" (case-insensitive).
* @return false if p == "false" (case-insensitive).
* @exception SQLServerException
* thrown if value is not recognized.
*/
/* L0 */ private boolean booleanPropertyOn(String propName,
String propValue) throws SQLServerException {
// Null means take the default of false.
if (null == propValue)
return false;
String lcpropValue = propValue.toLowerCase(Locale.US);
if (lcpropValue.equals("true"))
return true;
if (lcpropValue.equals("false"))
return false;
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidBooleanValue"));
Object[] msgArgs = {propName};
SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
// Adding return false here for compiler's sake, this code is unreachable.
return false;
}
// Maximum number of wide characters for a SQL login record name (such as instance name, application name, etc...).
// See TDS specification, "Login Data Validation Rules" section.
final static int MAX_SQL_LOGIN_NAME_WCHARS = 128;
/**
* Validates propName against maximum allowed length MAX_SQL_LOGIN_NAME_WCHARS. Throws exception if name length exceeded.
*
* @param propName
* the name of the property.
* @param propValue
* the value of the property.
* @throws SQLServerException
*/
void ValidateMaxSQLLoginName(String propName,
String propValue) throws SQLServerException {
if (propValue != null && propValue.length() > MAX_SQL_LOGIN_NAME_WCHARS) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_propertyMaximumExceedsChars"));
Object[] msgArgs = {propName, Integer.toString(MAX_SQL_LOGIN_NAME_WCHARS)};
SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
}
}
Connection connect(Properties propsIn,
SQLServerPooledConnection pooledConnection) throws SQLServerException {
int loginTimeoutSeconds = 0; // Will be set during the first retry attempt.
long start = System.currentTimeMillis();
for (int retryAttempt = 0;;) {
try {
return connectInternal(propsIn, pooledConnection);
}
catch (SQLServerException e) {
// Catch only the TLS 1.2 specific intermittent error.
if (SQLServerException.DRIVER_ERROR_INTERMITTENT_TLS_FAILED != e.getDriverErrorCode()) {
// Re-throw all other exceptions.
throw e;
}
else {
// Special handling of the retry logic for TLS 1.2 intermittent issue.
// If timeout is not set yet, set it once.
if (0 == retryAttempt) {
// We do not need to check for exceptions here, as the connection properties are already
// verified during the first try. Also, we would like to do this calculation
// only for the TLS 1.2 exception case.
loginTimeoutSeconds = SQLServerDriverIntProperty.LOGIN_TIMEOUT.getDefaultValue(); // if the user does not specify a default
// timeout, default is 15 per spec
String sPropValue = propsIn.getProperty(SQLServerDriverIntProperty.LOGIN_TIMEOUT.toString());
if (null != sPropValue && sPropValue.length() > 0) {
loginTimeoutSeconds = Integer.parseInt(sPropValue);
}
}
retryAttempt++;
long elapsedSeconds = ((System.currentTimeMillis() - start) / 1000L);
if (INTERMITTENT_TLS_MAX_RETRY < retryAttempt) {
// Re-throw the exception if we have reached the maximum retry attempts.
if (connectionlogger.isLoggable(Level.FINE)) {
connectionlogger.fine(
"Connection failed during SSL handshake. Maximum retry attempt (" + INTERMITTENT_TLS_MAX_RETRY + ") reached. ");
}
throw e;
}
else if (elapsedSeconds >= loginTimeoutSeconds) {
// Re-throw the exception if we do not have any time left to retry.
if (connectionlogger.isLoggable(Level.FINE)) {
connectionlogger.fine("Connection failed during SSL handshake. Not retrying as timeout expired.");
}
throw e;
}
else {
// Retry the connection.
if (connectionlogger.isLoggable(Level.FINE)) {
connectionlogger
.fine("Connection failed during SSL handshake. Retrying due to an intermittent TLS 1.2 failure issue. Retry attempt = "
+ retryAttempt + ".");
}
}
}
}
}
}
private void registerKeyStoreProviderOnConnection(String keyStoreAuth,
String keyStoreSecret,
String keyStoreLocation) throws SQLServerException {
if (null == keyStoreAuth) {
// secret and location must be null too.
if ((null != keyStoreSecret)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_keyStoreAuthenticationNotSet"));
Object[] msgArgs = {"keyStoreSecret"};
throw new SQLServerException(form.format(msgArgs), null);
}
if (null != keyStoreLocation) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_keyStoreAuthenticationNotSet"));
Object[] msgArgs = {"keyStoreLocation"};
throw new SQLServerException(form.format(msgArgs), null);
}
}
else {
KeyStoreAuthentication keyStoreAuthentication = KeyStoreAuthentication.valueOfString(keyStoreAuth);
switch (keyStoreAuthentication) {
case JavaKeyStorePassword:
// both secret and location must be set for JKS.
if ((null == keyStoreSecret) || (null == keyStoreLocation)) {
throw new SQLServerException(SQLServerException.getErrString("R_keyStoreSecretOrLocationNotSet"), null);
}
else {
SQLServerColumnEncryptionJavaKeyStoreProvider provider = new SQLServerColumnEncryptionJavaKeyStoreProvider(keyStoreLocation,
keyStoreSecret.toCharArray());
systemColumnEncryptionKeyStoreProvider.put(provider.getName(), provider);
}
break;
default:
// valueOfString would throw an exception if the keyStoreAuthentication is not valid.
break;
}
}
}
/**
* Establish a physical database connection based on the user specified connection properties. Logon to the database.
*
* @param propsIn
* the connection properties
* @param pooledConnection
* a parent pooled connection if this is a logical connection
* @throws SQLServerException
* @return the database connection
*/
Connection connectInternal(Properties propsIn,
SQLServerPooledConnection pooledConnection) throws SQLServerException {
try {
activeConnectionProperties = (Properties) propsIn.clone();
pooledConnectionParent = pooledConnection;
String sPropKey = null;
String sPropValue = null;
sPropKey = SQLServerDriverStringProperty.USER.toString();
sPropValue = activeConnectionProperties.getProperty(sPropKey);
if (sPropValue == null) {
sPropValue = SQLServerDriverStringProperty.USER.getDefaultValue();
activeConnectionProperties.setProperty(sPropKey, sPropValue);
}
ValidateMaxSQLLoginName(sPropKey, sPropValue);
sPropKey = SQLServerDriverStringProperty.PASSWORD.toString();
sPropValue = activeConnectionProperties.getProperty(sPropKey);
if (sPropValue == null) {
sPropValue = SQLServerDriverStringProperty.PASSWORD.getDefaultValue();
activeConnectionProperties.setProperty(sPropKey, sPropValue);
}
ValidateMaxSQLLoginName(sPropKey, sPropValue);
sPropKey = SQLServerDriverStringProperty.DATABASE_NAME.toString();
sPropValue = activeConnectionProperties.getProperty(sPropKey);
ValidateMaxSQLLoginName(sPropKey, sPropValue);
int loginTimeoutSeconds = SQLServerDriverIntProperty.LOGIN_TIMEOUT.getDefaultValue(); // if the user does not specify a default timeout,
// default is 15 per spec
sPropValue = activeConnectionProperties.getProperty(SQLServerDriverIntProperty.LOGIN_TIMEOUT.toString());
if (null != sPropValue && sPropValue.length() > 0) {
try {
loginTimeoutSeconds = Integer.parseInt(sPropValue);
}
catch (NumberFormatException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidTimeOut"));
Object[] msgArgs = {sPropValue};
SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
}
if (loginTimeoutSeconds < 0 || loginTimeoutSeconds > 65535) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidTimeOut"));
Object[] msgArgs = {sPropValue};
SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
}
}
// Translates the serverName from Unicode to ASCII Compatible Encoding (ACE), as defined by the ToASCII operation of RFC 3490.
sPropKey = SQLServerDriverBooleanProperty.SERVER_NAME_AS_ACE.toString();
sPropValue = activeConnectionProperties.getProperty(sPropKey);
if (sPropValue == null) {
sPropValue = Boolean.toString(SQLServerDriverBooleanProperty.SERVER_NAME_AS_ACE.getDefaultValue());
activeConnectionProperties.setProperty(sPropKey, sPropValue);
}
serverNameAsACE = booleanPropertyOn(sPropKey, sPropValue);