forked from microsoft/mssql-jdbc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSQLServerConnection.java
6499 lines (5569 loc) · 295 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.Serializable;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLPermission;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
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 org.ietf.jgss.GSSCredential;
import mssql.googlecode.cityhash.CityHash;
import mssql.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
import mssql.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap.Builder;
import mssql.googlecode.concurrentlinkedhashmap.EvictionListener;
/**
* Provides an implementation java.sql.connection interface that assists creating a JDBC connection to SQL Server.
* SQLServerConnections support JDBC connection pooling and may be either physical JDBC connections or logical JDBC
* connections.
*
* SQLServerConnection manages transaction control for all statements that were created from it. SQLServerConnection may
* participate in XA distributed transactions managed via an XAResource adapter.
*
* SQLServerConnection instantiates a new TDSChannel object for use by itself and all statement objects that are created
* under this connection.
*
* 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.
*
* SQLServerConnection is not thread safe, however multiple statements created from a single connection can be
* processing simultaneously in concurrent threads.
*
* This class's public functions need to be kept identical to the SQLServerConnectionPoolProxy's.
*
* 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 Declare all new
* custom (non-static) Public APIs in ISQLServerConnection interface such that they can also be implemented by
* SQLServerConnectionPoolProxy
*/
public class SQLServerConnection implements ISQLServerConnection, java.io.Serializable {
/**
* Always refresh SerialVersionUID when prompted
*/
private static final long serialVersionUID = 1965647556064751510L;
long timerExpire;
boolean attemptRefreshTokenLocked = false;
/**
* Thresholds related to when prepared statement handles are cleaned-up. 1 == immediately.
*
* The default for the prepared statement clean-up action threshold (i.e. when sp_unprepare is called).
*/
static final int DEFAULT_SERVER_PREPARED_STATEMENT_DISCARD_THRESHOLD = 10; // Used to set the initial default, can
// be changed later.
private int serverPreparedStatementDiscardThreshold = -1; // Current limit for this particular connection.
/**
* The default for if prepared statements should execute sp_executesql before following the prepare, unprepare
* pattern.
*
* Used to set the initial default, can be changed later. false == use sp_executesql -> sp_prepexec -> sp_execute ->
* batched -> sp_unprepare pattern, true == skip sp_executesql part of pattern.
*/
static final boolean DEFAULT_ENABLE_PREPARE_ON_FIRST_PREPARED_STATEMENT_CALL = false;
private Boolean enablePrepareOnFirstPreparedStatementCall = null; // Current limit for this particular connection.
// Handle the actual queue of discarded prepared statements.
private ConcurrentLinkedQueue<PreparedStatementHandle> discardedPreparedStatementHandles = new ConcurrentLinkedQueue<>();
private AtomicInteger discardedPreparedStatementHandleCount = new AtomicInteger(0);
private SQLServerColumnEncryptionKeyStoreProvider keystoreProvider = null;
private boolean fedAuthRequiredByUser = false;
private boolean fedAuthRequiredPreLoginResponse = 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;
private String originalHostNameInCertificate = null;
private String clientCertificate = null;
private String clientKey = null;
private String clientKeyPassword = "";
final int ENGINE_EDITION_FOR_SQL_AZURE = 5;
final int ENGINE_EDITION_FOR_SQL_AZURE_DW = 6;
final int ENGINE_EDITION_FOR_SQL_AZURE_MI = 8;
private Boolean isAzure = null;
private Boolean isAzureDW = null;
private Boolean isAzureMI = null;
private SharedTimer sharedTimer;
/**
* Return an existing cached SharedTimer associated with this Connection or create a new one.
*
* The SharedTimer will be released when the Connection is closed.
*
* @throws SQLServerException
*/
SharedTimer getSharedTimer() throws SQLServerException {
if (state == State.Closed) {
SQLServerException.makeFromDriverError(null, null, SQLServerException.getErrString("R_connectionIsClosed"),
null, false);
}
if (null == sharedTimer) {
this.sharedTimer = SharedTimer.getTimer();
}
return this.sharedTimer;
}
static class CityHash128Key implements java.io.Serializable {
/**
* Always refresh SerialVersionUID when prompted
*/
private static final long serialVersionUID = 166788428640603097L;
String unhashedString;
private long[] segments;
private int hashCode;
CityHash128Key(String sql, String parametersDefinition) {
this(sql + parametersDefinition);
}
@SuppressWarnings("deprecation")
CityHash128Key(String s) {
unhashedString = s;
byte[] bytes = new byte[s.length()];
s.getBytes(0, s.length(), bytes, 0);
segments = CityHash.cityHash128(bytes, 0, bytes.length);
}
public boolean equals(Object obj) {
if (!(obj instanceof CityHash128Key))
return false;
return (java.util.Arrays.equals(segments, ((CityHash128Key) obj).segments)// checks if hash is equal,
// short-circuitting;
&& this.unhashedString.equals(((CityHash128Key) obj).unhashedString));// checks if string is equal
}
public int hashCode() {
if (0 == hashCode) {
hashCode = java.util.Arrays.hashCode(segments);
}
return hashCode;
}
}
/**
* Keeps track of an individual prepared statement handle.
*/
class PreparedStatementHandle {
private int handle = 0;
private final AtomicInteger handleRefCount = new AtomicInteger();
private boolean isDirectSql;
private volatile boolean evictedFromCache;
private volatile boolean explicitlyDiscarded;
private CityHash128Key key;
PreparedStatementHandle(CityHash128Key key, int handle, boolean isDirectSql, boolean isEvictedFromCache) {
this.key = key;
this.handle = handle;
this.isDirectSql = isDirectSql;
this.setIsEvictedFromCache(isEvictedFromCache);
handleRefCount.set(1);
}
/** Has the statement been evicted from the statement handle cache. */
private boolean isEvictedFromCache() {
return evictedFromCache;
}
/** Specify whether the statement been evicted from the statement handle cache. */
private void setIsEvictedFromCache(boolean isEvictedFromCache) {
this.evictedFromCache = isEvictedFromCache;
}
/** Specify that this statement has been explicitly discarded from being used by the cache. */
void setIsExplicitlyDiscarded() {
this.explicitlyDiscarded = true;
evictCachedPreparedStatementHandle(this);
}
/** Has the statement been explicitly discarded. */
private boolean isExplicitlyDiscarded() {
return explicitlyDiscarded;
}
/** Returns the actual handle. */
int getHandle() {
return handle;
}
/** Returns the cache key. */
CityHash128Key getKey() {
return key;
}
boolean isDirectSql() {
return isDirectSql;
}
/**
* Makes sure handle cannot be re-used.
*
* @return false: Handle could not be discarded, it is in use. true: Handle was successfully put on path for
* discarding.
*/
private boolean tryDiscardHandle() {
return handleRefCount.compareAndSet(0, -999);
}
/** Returns whether this statement has been discarded and can no longer be re-used. */
private boolean isDiscarded() {
return 0 > handleRefCount.intValue();
}
/**
* Adds a new reference to this handle, i.e. re-using it.
*
* @return false: Reference could not be added, statement has been discarded or does not have a handle
* associated with it. true: Reference was successfully added.
*/
boolean tryAddReference() {
return (isDiscarded() || isExplicitlyDiscarded()) ? false : handleRefCount.incrementAndGet() > 0;
}
/** Remove a reference from this handle */
void removeReference() {
handleRefCount.decrementAndGet();
}
}
/** Size of the parsed SQL-text metadata cache */
static final private int PARSED_SQL_CACHE_SIZE = 100;
/** Cache of parsed SQL meta data */
static private ConcurrentLinkedHashMap<CityHash128Key, ParsedSQLCacheItem> parsedSQLCache;
static {
parsedSQLCache = new Builder<CityHash128Key, ParsedSQLCacheItem>()
.maximumWeightedCapacity(PARSED_SQL_CACHE_SIZE).build();
}
/** Returns prepared statement cache entry if exists, if not parse and create a new one */
static ParsedSQLCacheItem getCachedParsedSQL(CityHash128Key key) {
return parsedSQLCache.get(key);
}
/** Parses and create a information about parsed SQL text */
static ParsedSQLCacheItem parseAndCacheSQL(CityHash128Key key, String sql) throws SQLServerException {
JDBCSyntaxTranslator translator = new JDBCSyntaxTranslator();
String parsedSql = translator.translate(sql);
String procName = translator.getProcedureName(); // may return null
boolean returnValueSyntax = translator.hasReturnValueSyntax();
int[] parameterPositions = locateParams(parsedSql);
ParsedSQLCacheItem cacheItem = new ParsedSQLCacheItem(parsedSql, parameterPositions, procName,
returnValueSyntax);
parsedSQLCache.putIfAbsent(key, cacheItem);
return cacheItem;
}
/** Default size for prepared statement caches */
static final int DEFAULT_STATEMENT_POOLING_CACHE_SIZE = 0;
/** Size of the prepared statement handle cache */
private int statementPoolingCacheSize = DEFAULT_STATEMENT_POOLING_CACHE_SIZE;
/** Cache of prepared statement handles */
private ConcurrentLinkedHashMap<CityHash128Key, PreparedStatementHandle> preparedStatementHandleCache;
/** Cache of prepared statement parameter metadata */
private ConcurrentLinkedHashMap<CityHash128Key, SQLServerParameterMetaData> parameterMetadataCache;
/**
* Checks whether statement pooling is enabled or disabled. The default is set to true;
*/
private boolean disableStatementPooling = true;
/**
* Locates statement parameters.
*
* @param sql
* SQL text to parse for positions of parameters to initialize.
*/
private static int[] locateParams(String sql) {
LinkedList<Integer> parameterPositions = new LinkedList<>();
// Locate the parameter placeholders in the SQL string.
int offset = -1;
while ((offset = ParameterUtils.scanSQLForChar('?', sql, ++offset)) < sql.length()) {
parameterPositions.add(offset);
}
// return as int[]
return parameterPositions.stream().mapToInt(Integer::valueOf).toArray();
}
/**
* Encapsulates the data to be sent to the server as part of Federated Authentication Feature Extension.
*/
class FederatedAuthenticationFeatureExtensionData implements Serializable {
/**
* Always update serialVersionUID when prompted
*/
private static final long serialVersionUID = -6709861741957202475L;
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)) {
case "ACTIVEDIRECTORYPASSWORD":
this.authentication = SqlAuthentication.ActiveDirectoryPassword;
break;
case "ACTIVEDIRECTORYINTEGRATED":
this.authentication = SqlAuthentication.ActiveDirectoryIntegrated;
break;
case "ACTIVEDIRECTORYMSI":
this.authentication = SqlAuthentication.ActiveDirectoryMSI;
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 AZURE_REST_MSI_URL = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01";
static final String ADAL_GET_ACCESS_TOKEN_FUNCTION_NAME = "ADALGetAccessToken";
static final String ACCESS_TOKEN_IDENTIFIER = "\"access_token\":\"";
static final String ACCESS_TOKEN_EXPIRES_IN_IDENTIFIER = "\"expires_in\":\"";
static final String ACCESS_TOKEN_EXPIRES_ON_IDENTIFIER = "\"expires_on\":\"";
static final String ACCESS_TOKEN_EXPIRES_ON_DATE_FORMAT = "M/d/yyyy h:mm:ss a X";
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
private final static float TIMEOUTSTEP_TNIR = 0.125F;
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
private static final String callAbortPerm = "callAbort";
private static final String SET_NETWORK_TIMEOUT_PERM = "setNetworkTimeout";
// see connection properties doc (default is false).
private boolean sendStringParametersAsUnicode = SQLServerDriverBooleanProperty.SEND_STRING_PARAMETERS_AS_UNICODE
.getDefaultValue();
private String hostName = null;
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;
}
/**
* Timeout value for canceling the query timeout.
*/
private int cancelQueryTimeoutSeconds;
/**
* Returns the cancelTimeout in seconds.
*
* @return
*/
final int getCancelQueryTimeoutSeconds() {
return cancelQueryTimeoutSeconds;
}
private int socketTimeoutMilliseconds;
final int getSocketTimeoutMilliseconds() {
return socketTimeoutMilliseconds;
}
/**
* boolean value for deciding if the driver should use bulk copy API for batch inserts.
*/
private boolean useBulkCopyForBatchInsert;
/**
* Returns the useBulkCopyForBatchInsert value.
*
* @return flag for using Bulk Copy API for batch insert operations.
*/
public boolean getUseBulkCopyForBatchInsert() {
return useBulkCopyForBatchInsert;
}
/**
* Specifies the flag for using Bulk Copy API for batch insert operations.
*
* @param useBulkCopyForBatchInsert
* boolean value for useBulkCopyForBatchInsert.
*/
public void setUseBulkCopyForBatchInsert(boolean useBulkCopyForBatchInsert) {
this.useBulkCopyForBatchInsert = useBulkCopyForBatchInsert;
}
boolean userSetTNIR = true;
private boolean sendTimeAsDatetime = SQLServerDriverBooleanProperty.SEND_TIME_AS_DATETIME.getDefaultValue();
private boolean useFmtOnly = SQLServerDriverBooleanProperty.USE_FMT_ONLY.getDefaultValue();
@Override
public 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;
}
private String socketFactoryClass = null;
final String getSocketFactoryClass() {
return socketFactoryClass;
}
private String socketFactoryConstructorArg = null;
final String getSocketFactoryConstructorArg() {
return socketFactoryConstructorArg;
}
private String trustManagerClass = null;
final String getTrustManagerClass() {
assert TDS.ENCRYPT_INVALID != requestedEncryptionLevel;
return trustManagerClass;
}
private String trustManagerConstructorArg = null;
final String getTrustManagerConstructorArg() {
assert TDS.ENCRYPT_INVALID != requestedEncryptionLevel;
return trustManagerConstructorArg;
}
static final String RESERVED_PROVIDER_NAME_PREFIX = "MSSQL_";
String columnEncryptionSetting = null;
boolean isColumnEncryptionSettingEnabled() {
return (columnEncryptionSetting.equalsIgnoreCase(ColumnEncryptionSetting.Enabled.toString()));
}
String enclaveAttestationUrl = null;
String enclaveAttestationProtocol = null;
String keyStoreAuthentication = null;
String keyStoreSecret = null;
String keyStoreLocation = null;
String keyStorePrincipalId = null;
private ColumnEncryptionVersion serverColumnEncryptionVersion = ColumnEncryptionVersion.AE_NotSupported;
private String enclaveType = null;
boolean getServerSupportsColumnEncryption() {
return (serverColumnEncryptionVersion.value() > ColumnEncryptionVersion.AE_NotSupported.value());
}
ColumnEncryptionVersion getServerColumnEncryptionVersion() {
return serverColumnEncryptionVersion;
}
private boolean serverSupportsDataClassification = false;
boolean getServerSupportsDataClassification() {
return serverSupportsDataClassification;
}
static Map<String, SQLServerColumnEncryptionKeyStoreProvider> globalSystemColumnEncryptionKeyStoreProviders = new HashMap<>();
static {
if (System.getProperty("os.name").toLowerCase(Locale.ENGLISH).startsWith("windows")) {
SQLServerColumnEncryptionCertificateStoreProvider provider = new SQLServerColumnEncryptionCertificateStoreProvider();
globalSystemColumnEncryptionKeyStoreProviders.put(provider.getName(), provider);
}
}
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<>();
/**
* 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(loggingClassName, "registerColumnEncryptionKeyStoreProviders",
"Registering Column Encryption Key Store Providers");
if (null == clientKeyStoreProviders) {
throw new SQLServerException(null, SQLServerException.getErrString("R_CustomKeyStoreProviderMapNull"), null,
0, false);
}
if (null != globalCustomColumnEncryptionKeyStoreProviders
&& !globalCustomColumnEncryptionKeyStoreProviders.isEmpty()) {
throw new SQLServerException(null, SQLServerException.getErrString("R_CustomKeyStoreProviderSetOnce"), null,
0, false);
}
globalCustomColumnEncryptionKeyStoreProviders = new HashMap<>();
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(loggingClassName, "registerColumnEncryptionKeyStoreProviders",
"Number of Key store providers that are registered:"
+ globalCustomColumnEncryptionKeyStoreProviders.size());
}
/**
* Unregisters all the custom key store providers from the globalCustomColumnEncryptionKeyStoreProviders by clearing
* the map and setting it to null.
*/
public static synchronized void unregisterColumnEncryptionKeyStoreProviders() {
loggerExternal.entering(loggingClassName, "unregisterColumnEncryptionKeyStoreProviders",
"Removing Column Encryption Key Store Provider");
if (null != globalCustomColumnEncryptionKeyStoreProviders) {
globalCustomColumnEncryptionKeyStoreProviders.clear();
globalCustomColumnEncryptionKeyStoreProviders = null;
}
loggerExternal.exiting(loggingClassName, "unregisterColumnEncryptionKeyStoreProviders",
"Number of Key store providers that are registered: 0");
}
synchronized SQLServerColumnEncryptionKeyStoreProvider getGlobalSystemColumnEncryptionKeyStoreProvider(
String providerName) {
return (null != globalSystemColumnEncryptionKeyStoreProviders && globalSystemColumnEncryptionKeyStoreProviders
.containsKey(providerName)) ? globalSystemColumnEncryptionKeyStoreProviders.get(providerName) : null;
}
synchronized String getAllGlobalCustomSystemColumnEncryptionKeyStoreProviders() {
return (null != globalCustomColumnEncryptionKeyStoreProviders) ? globalCustomColumnEncryptionKeyStoreProviders
.keySet().toString() : 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;
}
synchronized SQLServerColumnEncryptionKeyStoreProvider getGlobalCustomColumnEncryptionKeyStoreProvider(
String providerName) {
return (null != globalCustomColumnEncryptionKeyStoreProviders && globalCustomColumnEncryptionKeyStoreProviders
.containsKey(providerName)) ? globalCustomColumnEncryptionKeyStoreProviders.get(providerName) : null;
}
synchronized SQLServerColumnEncryptionKeyStoreProvider getSystemColumnEncryptionKeyStoreProvider(
String providerName) {
return (null != systemColumnEncryptionKeyStoreProvider && systemColumnEncryptionKeyStoreProvider
.containsKey(providerName)) ? systemColumnEncryptionKeyStoreProvider.get(providerName) : null;
}
synchronized SQLServerColumnEncryptionKeyStoreProvider getColumnEncryptionKeyStoreProvider(
String providerName) throws SQLServerException {
// Check for the connection provider first.
keystoreProvider = getSystemColumnEncryptionKeyStoreProvider(providerName);
// There is no connection provider of this name, check for the global system providers.
if (null == keystoreProvider) {
keystoreProvider = getGlobalSystemColumnEncryptionKeyStoreProvider(providerName);
}
// There is no global system provider of this name, check for the global custom providers.
if (null == keystoreProvider) {
keystoreProvider = getGlobalCustomColumnEncryptionKeyStoreProvider(providerName);
}
// No provider was found of this name.
if (null == keystoreProvider) {
String systemProviders = getAllSystemColumnEncryptionKeyStoreProviders();
String customProviders = getAllGlobalCustomSystemColumnEncryptionKeyStoreProviders();
MessageFormat form = new MessageFormat(
SQLServerException.getErrString("R_UnrecognizedKeyStoreProviderName"));
Object[] msgArgs = {providerName, systemProviders, customProviders};
throw new SQLServerException(form.format(msgArgs), null);
}
return keystoreProvider;
}
private String trustedServerNameAE = null;
private static Map<String, List<String>> columnEncryptionTrustedMasterKeyPaths = new HashMap<>();
/**
* 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(loggingClassName, "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(loggingClassName, "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(loggingClassName, "updateColumnEncryptionTrustedMasterKeyPaths",
"Updating Trusted Master Key Paths");
// Use upper case for server and instance names.
columnEncryptionTrustedMasterKeyPaths.put(server.toUpperCase(), trustedKeyPaths);
loggerExternal.exiting(loggingClassName, "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(loggingClassName, "removeColumnEncryptionTrustedMasterKeyPaths",
"Removing Trusted Master Key Paths");
// Use upper case for server and instance names.
columnEncryptionTrustedMasterKeyPaths.remove(server.toUpperCase());
loggerExternal.exiting(loggingClassName, "removeColumnEncryptionTrustedMasterKeyPaths",
"Number of Trusted Master Key Paths: " + columnEncryptionTrustedMasterKeyPaths.size());
}
/**
* Returns the Trusted Master Key Paths.
*
* @return columnEncryptionTrustedMasterKeyPaths.
*/
public static synchronized Map<String, List<String>> getColumnEncryptionTrustedMasterKeyPaths() {
loggerExternal.entering(loggingClassName, "getColumnEncryptionTrustedMasterKeyPaths",
"Getting Trusted Master Key Paths");
Map<String, List<String>> masterKeyPathCopy = new HashMap<>();
for (Map.Entry<String, List<String>> entry : columnEncryptionTrustedMasterKeyPaths.entrySet()) {
masterKeyPathCopy.put(entry.getKey(), entry.getValue());
}
loggerExternal.exiting(loggingClassName, "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 boolean ntlmAuthentication = false;
private byte[] ntlmPasswordHash = null;
private AuthenticationScheme intAuthScheme = AuthenticationScheme.nativeAuthentication;
private GSSCredential impersonatedUserCred;
private boolean isUserCreatedCredential;
// 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 volatile 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) ? Integer.MAX_VALUE : 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;