/
SNIProxy.cs
858 lines (743 loc) · 33.2 KB
/
SNIProxy.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
namespace Microsoft.Data.SqlClient.SNI
{
/// <summary>
/// Managed SNI proxy implementation. Contains many SNI entry points used by SqlClient.
/// </summary>
internal class SNIProxy
{
private const int DefaultSqlServerPort = 1433;
private const int DefaultSqlServerDacPort = 1434;
private const string SqlServerSpnHeader = "MSSQLSvc";
internal class SspiClientContextResult
{
internal const uint OK = 0;
internal const uint Failed = 1;
internal const uint KerberosTicketMissing = 2;
}
internal static readonly SNIProxy s_singleton = new SNIProxy();
internal static SNIProxy GetInstance()
{
return s_singleton;
}
/// <summary>
/// Enable SSL on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <param name="options"></param>
/// <returns>SNI error code</returns>
internal uint EnableSsl(SNIHandle handle, uint options)
{
try
{
return handle.EnableSsl(options);
}
catch (Exception e)
{
return SNICommon.ReportSNIError(SNIProviders.SSL_PROV, SNICommon.HandshakeFailureError, e);
}
}
/// <summary>
/// Disable SSL on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <returns>SNI error code</returns>
internal uint DisableSsl(SNIHandle handle)
{
handle.DisableSsl();
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Generate SSPI context
/// </summary>
/// <param name="sspiClientContextStatus">SSPI client context status</param>
/// <param name="receivedBuff">Receive buffer</param>
/// <param name="sendBuff">Send buffer</param>
/// <param name="serverName">Service Principal Name buffer</param>
/// <returns>SNI error code</returns>
internal void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, byte[] receivedBuff, ref byte[] sendBuff, byte[] serverName)
{
SafeDeleteContext securityContext = sspiClientContextStatus.SecurityContext;
ContextFlagsPal contextFlags = sspiClientContextStatus.ContextFlags;
SafeFreeCredentials credentialsHandle = sspiClientContextStatus.CredentialsHandle;
string securityPackage = NegotiationInfoClass.Negotiate;
if (securityContext == null)
{
credentialsHandle = NegotiateStreamPal.AcquireDefaultCredential(securityPackage, false);
}
SecurityBuffer[] inSecurityBufferArray;
if (receivedBuff != null)
{
inSecurityBufferArray = new SecurityBuffer[] { new SecurityBuffer(receivedBuff, SecurityBufferType.SECBUFFER_TOKEN) };
}
else
{
inSecurityBufferArray = Array.Empty<SecurityBuffer>();
}
int tokenSize = NegotiateStreamPal.QueryMaxTokenSize(securityPackage);
SecurityBuffer outSecurityBuffer = new SecurityBuffer(tokenSize, SecurityBufferType.SECBUFFER_TOKEN);
ContextFlagsPal requestedContextFlags = ContextFlagsPal.Connection
| ContextFlagsPal.Confidentiality
| ContextFlagsPal.Delegate
| ContextFlagsPal.MutualAuth;
string serverSPN = System.Text.Encoding.UTF8.GetString(serverName);
SecurityStatusPal statusCode = NegotiateStreamPal.InitializeSecurityContext(
credentialsHandle,
ref securityContext,
serverSPN,
requestedContextFlags,
inSecurityBufferArray,
outSecurityBuffer,
ref contextFlags);
if (statusCode.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded ||
statusCode.ErrorCode == SecurityStatusPalErrorCode.CompAndContinue)
{
inSecurityBufferArray = new SecurityBuffer[] { outSecurityBuffer };
statusCode = NegotiateStreamPal.CompleteAuthToken(ref securityContext, inSecurityBufferArray);
outSecurityBuffer.token = null;
}
sendBuff = outSecurityBuffer.token;
if (sendBuff == null)
{
sendBuff = Array.Empty<byte>();
}
sspiClientContextStatus.SecurityContext = securityContext;
sspiClientContextStatus.ContextFlags = contextFlags;
sspiClientContextStatus.CredentialsHandle = credentialsHandle;
if (IsErrorStatus(statusCode.ErrorCode))
{
// Could not access Kerberos Ticket.
//
// SecurityStatusPalErrorCode.InternalError only occurs in Unix and always comes with a GssApiException,
// so we don't need to check for a GssApiException here.
if (statusCode.ErrorCode == SecurityStatusPalErrorCode.InternalError)
{
throw new InvalidOperationException(SQLMessage.KerberosTicketMissingError() + "\n" + statusCode);
}
else
{
throw new InvalidOperationException(SQLMessage.SSPIGenerateError() + "\n" + statusCode);
}
}
}
private static bool IsErrorStatus(SecurityStatusPalErrorCode errorCode)
{
return errorCode != SecurityStatusPalErrorCode.NotSet &&
errorCode != SecurityStatusPalErrorCode.OK &&
errorCode != SecurityStatusPalErrorCode.ContinueNeeded &&
errorCode != SecurityStatusPalErrorCode.CompleteNeeded &&
errorCode != SecurityStatusPalErrorCode.CompAndContinue &&
errorCode != SecurityStatusPalErrorCode.ContextExpired &&
errorCode != SecurityStatusPalErrorCode.CredentialsNeeded &&
errorCode != SecurityStatusPalErrorCode.Renegotiate;
}
/// <summary>
/// Set connection buffer size
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="bufferSize">Buffer size</param>
/// <returns>SNI error code</returns>
internal uint SetConnectionBufferSize(SNIHandle handle, uint bufferSize)
{
handle.SetBufferSize((int)bufferSize);
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Copies data in SNIPacket to given byte array parameter
/// </summary>
/// <param name="packet">SNIPacket object containing data packets</param>
/// <param name="inBuff">Destination byte array where data packets are copied to</param>
/// <param name="dataSize">Length of data packets</param>
/// <returns>SNI error status</returns>
internal uint PacketGetData(SNIPacket packet, byte[] inBuff, ref uint dataSize)
{
int dataSizeInt = 0;
packet.GetData(inBuff, ref dataSizeInt);
dataSize = (uint)dataSizeInt;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Read synchronously
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">SNI packet</param>
/// <param name="timeout">Timeout</param>
/// <returns>SNI error status</returns>
internal uint ReadSyncOverAsync(SNIHandle handle, out SNIPacket packet, int timeout)
{
return handle.Receive(out packet, timeout);
}
/// <summary>
/// Get SNI connection ID
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="clientConnectionId">Client connection ID</param>
/// <returns>SNI error status</returns>
internal uint GetConnectionId(SNIHandle handle, ref Guid clientConnectionId)
{
clientConnectionId = handle.ConnectionId;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Send a packet
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">SNI packet</param>
/// <param name="sync">true if synchronous, false if asynchronous</param>
/// <returns>SNI error status</returns>
internal uint WritePacket(SNIHandle handle, SNIPacket packet, bool sync)
{
uint result;
if (sync)
{
result = handle.Send(packet);
handle.ReturnPacket(packet);
}
else
{
result = handle.SendAsync(packet);
}
return result;
}
/// <summary>
/// Create a SNI connection handle
/// </summary>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="fullServerName">Full server name from connection string</param>
/// <param name="ignoreSniOpenTimeout">Ignore open timeout</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="instanceName">Instance name</param>
/// <param name="spnBuffer">SPN</param>
/// <param name="flushCache">Flush packet cache</param>
/// <param name="async">Asynchronous connection</param>
/// <param name="parallel">Attempt parallel connects</param>
/// <param name="isIntegratedSecurity"></param>
/// <param name="cachedFQDN">Used for DNS Cache</param>
/// <param name="pendingDNSInfo">Used for DNS Cache</param>
/// <returns>SNI handle</returns>
internal SNIHandle CreateConnectionHandle(object callbackObject, string fullServerName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool parallel, bool isIntegratedSecurity, string cachedFQDN, ref SQLDNSInfo pendingDNSInfo)
{
instanceName = new byte[1];
bool errorWithLocalDBProcessing;
string localDBDataSource = GetLocalDBDataSource(fullServerName, out errorWithLocalDBProcessing);
if (errorWithLocalDBProcessing)
{
return null;
}
// If a localDB Data source is available, we need to use it.
fullServerName = localDBDataSource ?? fullServerName;
DataSource details = DataSource.ParseServerName(fullServerName);
if (details == null)
{
return null;
}
SNIHandle sniHandle = null;
switch (details._connectionProtocol)
{
case DataSource.Protocol.Admin:
case DataSource.Protocol.None: // default to using tcp if no protocol is provided
case DataSource.Protocol.TCP:
sniHandle = CreateTcpHandle(details, timerExpire, callbackObject, parallel, cachedFQDN, ref pendingDNSInfo);
break;
case DataSource.Protocol.NP:
sniHandle = CreateNpHandle(details, timerExpire, callbackObject, parallel);
break;
default:
Debug.Fail($"Unexpected connection protocol: {details._connectionProtocol}");
break;
}
if (isIntegratedSecurity)
{
try
{
spnBuffer = GetSqlServerSPN(details);
}
catch (Exception e)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, SNICommon.ErrorSpnLookup, e);
}
}
return sniHandle;
}
private static byte[] GetSqlServerSPN(DataSource dataSource)
{
Debug.Assert(!string.IsNullOrWhiteSpace(dataSource.ServerName));
string hostName = dataSource.ServerName;
string postfix = null;
if (dataSource.Port != -1)
{
postfix = dataSource.Port.ToString();
}
else if (!string.IsNullOrWhiteSpace(dataSource.InstanceName))
{
postfix = dataSource.InstanceName;
}
// For handling tcp:<hostname> format
else if (dataSource._connectionProtocol == DataSource.Protocol.TCP)
{
postfix = DefaultSqlServerPort.ToString();
}
return GetSqlServerSPN(hostName, postfix);
}
private static byte[] GetSqlServerSPN(string hostNameOrAddress, string portOrInstanceName)
{
Debug.Assert(!string.IsNullOrWhiteSpace(hostNameOrAddress));
IPHostEntry hostEntry = null;
string fullyQualifiedDomainName;
try
{
hostEntry = Dns.GetHostEntry(hostNameOrAddress);
}
catch (SocketException)
{
// A SocketException can occur while resolving the hostname.
// We will fallback on using hostname from the connection string in the finally block
}
finally
{
// If the DNS lookup failed, then resort to using the user provided hostname to construct the SPN.
fullyQualifiedDomainName = hostEntry?.HostName ?? hostNameOrAddress;
}
string serverSpn = SqlServerSpnHeader + "/" + fullyQualifiedDomainName;
if (!string.IsNullOrWhiteSpace(portOrInstanceName))
{
serverSpn += ":" + portOrInstanceName;
}
else
{
serverSpn += $":{DefaultSqlServerPort}";
}
return Encoding.UTF8.GetBytes(serverSpn);
}
/// <summary>
/// Creates an SNITCPHandle object
/// </summary>
/// <param name="details">Data source</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="parallel">Should MultiSubnetFailover be used</param>
/// <param name="cachedFQDN">Key for DNS Cache</param>
/// <param name="pendingDNSInfo">Used for DNS Cache</param>
/// <returns>SNITCPHandle</returns>
private SNITCPHandle CreateTcpHandle(DataSource details, long timerExpire, object callbackObject, bool parallel, string cachedFQDN, ref SQLDNSInfo pendingDNSInfo)
{
// TCP Format:
// tcp:<host name>\<instance name>
// tcp:<host name>,<TCP/IP port number>
string hostName = details.ServerName;
if (string.IsNullOrWhiteSpace(hostName))
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
return null;
}
int port = -1;
bool isAdminConnection = details._connectionProtocol == DataSource.Protocol.Admin;
if (details.IsSsrpRequired)
{
try
{
port = isAdminConnection ?
SSRP.GetDacPortByInstanceName(hostName, details.InstanceName) :
SSRP.GetPortByInstanceName(hostName, details.InstanceName);
}
catch (SocketException se)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InvalidConnStringError, se);
return null;
}
}
else if (details.Port != -1)
{
port = details.Port;
}
else
{
port = isAdminConnection ? DefaultSqlServerDacPort : DefaultSqlServerPort;
}
return new SNITCPHandle(hostName, port, timerExpire, callbackObject, parallel, cachedFQDN, ref pendingDNSInfo);
}
/// <summary>
/// Creates an SNINpHandle object
/// </summary>
/// <param name="details">Data source</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="parallel">Should MultiSubnetFailover be used. Only returns an error for named pipes.</param>
/// <returns>SNINpHandle</returns>
private SNINpHandle CreateNpHandle(DataSource details, long timerExpire, object callbackObject, bool parallel)
{
if (parallel)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.MultiSubnetFailoverWithNonTcpProtocol, string.Empty);
return null;
}
return new SNINpHandle(details.PipeHostName, details.PipeName, timerExpire, callbackObject);
}
/// <summary>
/// Read packet asynchronously
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">Packet</param>
/// <returns>SNI error status</returns>
internal uint ReadAsync(SNIHandle handle, out SNIPacket packet)
{
packet = null;
return handle.ReceiveAsync(ref packet);
}
/// <summary>
/// Set packet data
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="data">Data</param>
/// <param name="length">Length</param>
internal void PacketSetData(SNIPacket packet, byte[] data, int length)
{
packet.AppendData(data, length);
}
/// <summary>
/// Check SNI handle connection
/// </summary>
/// <param name="handle"></param>
/// <returns>SNI error status</returns>
internal uint CheckConnection(SNIHandle handle)
{
return handle.CheckConnection();
}
/// <summary>
/// Get last SNI error on this thread
/// </summary>
/// <returns></returns>
internal SNIError GetLastError()
{
return SNILoadHandle.SingletonInstance.LastError;
}
/// <summary>
/// Gets the Local db Named pipe data source if the input is a localDB server.
/// </summary>
/// <param name="fullServerName">The data source</param>
/// <param name="error">Set true when an error occurred while getting LocalDB up</param>
/// <returns></returns>
private string GetLocalDBDataSource(string fullServerName, out bool error)
{
string localDBConnectionString = null;
bool isBadLocalDBDataSource;
string localDBInstance = DataSource.GetLocalDBInstance(fullServerName, out isBadLocalDBDataSource);
if (isBadLocalDBDataSource)
{
error = true;
return null;
}
else if (!string.IsNullOrEmpty(localDBInstance))
{
// We have successfully received a localDBInstance which is valid.
Debug.Assert(!string.IsNullOrWhiteSpace(localDBInstance), "Local DB Instance name cannot be empty.");
localDBConnectionString = LocalDB.GetLocalDBConnectionString(localDBInstance);
if (fullServerName == null)
{
// The Last error is set in LocalDB.GetLocalDBConnectionString. We don't need to set Last here.
error = true;
return null;
}
}
error = false;
return localDBConnectionString;
}
}
internal class DataSource
{
private const char CommaSeparator = ',';
private const char SemiColon = ':';
private const char BackSlashCharacter = '\\';
private const string DefaultHostName = "localhost";
private const string DefaultSqlServerInstanceName = "mssqlserver";
private const string PipeBeginning = @"\\";
private const string Slash = @"/";
private const string PipeToken = "pipe";
private const string LocalDbHost = "(localdb)";
private const string NamedPipeInstanceNameHeader = "mssql$";
private const string DefaultPipeName = "sql\\query";
internal enum Protocol { TCP, NP, None, Admin };
internal Protocol _connectionProtocol = Protocol.None;
/// <summary>
/// Provides the HostName of the server to connect to for TCP protocol.
/// This information is also used for finding the SPN of SqlServer
/// </summary>
internal string ServerName { get; private set; }
/// <summary>
/// Provides the port on which the TCP connection should be made if one was specified in Data Source
/// </summary>
internal int Port { get; private set; } = -1;
/// <summary>
/// Provides the inferred Instance Name from Server Data Source
/// </summary>
internal string InstanceName { get; private set; }
/// <summary>
/// Provides the pipe name in case of Named Pipes
/// </summary>
internal string PipeName { get; private set; }
/// <summary>
/// Provides the HostName to connect to in case of Named pipes Data Source
/// </summary>
internal string PipeHostName { get; private set; }
private string _workingDataSource;
private string _dataSourceAfterTrimmingProtocol;
internal bool IsBadDataSource { get; private set; } = false;
internal bool IsSsrpRequired { get; private set; } = false;
private DataSource(string dataSource)
{
// Remove all whitespaces from the datasource and all operations will happen on lower case.
_workingDataSource = dataSource.Trim().ToLowerInvariant();
int firstIndexOfColon = _workingDataSource.IndexOf(SemiColon);
PopulateProtocol();
_dataSourceAfterTrimmingProtocol = (firstIndexOfColon > -1) && _connectionProtocol != Protocol.None
? _workingDataSource.Substring(firstIndexOfColon + 1).Trim() : _workingDataSource;
if (_dataSourceAfterTrimmingProtocol.Contains(Slash)) // Pipe paths only allow back slashes
{
if (_connectionProtocol == Protocol.None)
ReportSNIError(SNIProviders.INVALID_PROV);
else if (_connectionProtocol == Protocol.NP)
ReportSNIError(SNIProviders.NP_PROV);
else if (_connectionProtocol == Protocol.TCP)
ReportSNIError(SNIProviders.TCP_PROV);
}
}
private void PopulateProtocol()
{
string[] splitByColon = _workingDataSource.Split(SemiColon);
if (splitByColon.Length <= 1)
{
_connectionProtocol = Protocol.None;
}
else
{
// We trim before switching because " tcp : server , 1433 " is a valid data source
switch (splitByColon[0].Trim())
{
case TdsEnums.TCP:
_connectionProtocol = Protocol.TCP;
break;
case TdsEnums.NP:
_connectionProtocol = Protocol.NP;
break;
case TdsEnums.ADMIN:
_connectionProtocol = Protocol.Admin;
break;
default:
// None of the supported protocols were found. This may be a IPv6 address
_connectionProtocol = Protocol.None;
break;
}
}
}
internal static string GetLocalDBInstance(string dataSource, out bool error)
{
string instanceName = null;
string workingDataSource = dataSource.ToLowerInvariant();
string[] tokensByBackSlash = workingDataSource.Split(BackSlashCharacter);
error = false;
// All LocalDb endpoints are of the format host\instancename where host is always (LocalDb) (case-insensitive)
if (tokensByBackSlash.Length == 2 && LocalDbHost.Equals(tokensByBackSlash[0].TrimStart()))
{
if (!string.IsNullOrWhiteSpace(tokensByBackSlash[1]))
{
instanceName = tokensByBackSlash[1].Trim();
}
else
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBNoInstanceName, string.Empty);
error = true;
return null;
}
}
return instanceName;
}
internal static DataSource ParseServerName(string dataSource)
{
DataSource details = new DataSource(dataSource);
if (details.IsBadDataSource)
{
return null;
}
if (details.InferNamedPipesInformation())
{
return details;
}
if (details.IsBadDataSource)
{
return null;
}
if (details.InferConnectionDetails())
{
return details;
}
return null;
}
private void InferLocalServerName()
{
// If Server name is empty or localhost, then use "localhost"
if (string.IsNullOrEmpty(ServerName) || IsLocalHost(ServerName))
{
ServerName = _connectionProtocol == Protocol.Admin ?
Environment.MachineName : DefaultHostName;
}
}
private bool InferConnectionDetails()
{
string[] tokensByCommaAndSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashCharacter, CommaSeparator);
ServerName = tokensByCommaAndSlash[0].Trim();
int commaIndex = _dataSourceAfterTrimmingProtocol.IndexOf(CommaSeparator);
int backSlashIndex = _dataSourceAfterTrimmingProtocol.IndexOf(PipeBeginning);
// Check the parameters. The parameters are Comma separated in the Data Source. The parameter we really care about is the port
// If Comma exists, the try to get the port number
if (commaIndex > -1)
{
string parameter = backSlashIndex > -1
? ((commaIndex > backSlashIndex) ? tokensByCommaAndSlash[2].Trim() : tokensByCommaAndSlash[1].Trim())
: tokensByCommaAndSlash[1].Trim();
// Bad Data Source like "server, "
if (string.IsNullOrEmpty(parameter))
{
ReportSNIError(SNIProviders.INVALID_PROV);
return false;
}
// For Tcp and Only Tcp are parameters allowed.
if (_connectionProtocol == Protocol.None)
{
_connectionProtocol = Protocol.TCP;
}
else if (_connectionProtocol != Protocol.TCP)
{
// Parameter has been specified for non-TCP protocol. This is not allowed.
ReportSNIError(SNIProviders.INVALID_PROV);
return false;
}
int port;
if (!int.TryParse(parameter, out port))
{
ReportSNIError(SNIProviders.TCP_PROV);
return false;
}
// If the user explicitly specified a invalid port in the connection string.
if (port < 1)
{
ReportSNIError(SNIProviders.TCP_PROV);
return false;
}
Port = port;
}
// Instance Name Handling. Only if we found a '\' and we did not find a port in the Data Source
else if (backSlashIndex > -1)
{
// This means that there will not be any part separated by comma.
InstanceName = tokensByCommaAndSlash[1].Trim();
if (string.IsNullOrWhiteSpace(InstanceName))
{
ReportSNIError(SNIProviders.INVALID_PROV);
return false;
}
if (DefaultSqlServerInstanceName.Equals(InstanceName))
{
ReportSNIError(SNIProviders.INVALID_PROV);
return false;
}
IsSsrpRequired = true;
}
InferLocalServerName();
return true;
}
private void ReportSNIError(SNIProviders provider)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(provider, 0, SNICommon.InvalidConnStringError, string.Empty);
IsBadDataSource = true;
}
private bool InferNamedPipesInformation()
{
// If we have a datasource beginning with a pipe or we have already determined that the protocol is Named Pipe
if (_dataSourceAfterTrimmingProtocol.StartsWith(PipeBeginning) || _connectionProtocol == Protocol.NP)
{
// If the data source is "np:servername"
if (!_dataSourceAfterTrimmingProtocol.Contains(PipeBeginning))
{
PipeHostName = ServerName = _dataSourceAfterTrimmingProtocol;
InferLocalServerName();
PipeName = SNINpHandle.DefaultPipePath;
return true;
}
try
{
string[] tokensByBackSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashCharacter);
// The datasource is of the format \\host\pipe\sql\query [0]\[1]\[2]\[3]\[4]\[5]
// It would at least have 6 parts.
// Another valid Sql named pipe for an named instance is \\.\pipe\MSSQL$MYINSTANCE\sql\query
if (tokensByBackSlash.Length < 6)
{
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
string host = tokensByBackSlash[2];
if (string.IsNullOrEmpty(host))
{
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
//Check if the "pipe" keyword is the first part of path
if (!PipeToken.Equals(tokensByBackSlash[3]))
{
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
if (tokensByBackSlash[4].StartsWith(NamedPipeInstanceNameHeader))
{
InstanceName = tokensByBackSlash[4].Substring(NamedPipeInstanceNameHeader.Length);
}
StringBuilder pipeNameBuilder = new StringBuilder();
for (int i = 4; i < tokensByBackSlash.Length - 1; i++)
{
pipeNameBuilder.Append(tokensByBackSlash[i]);
pipeNameBuilder.Append(Path.DirectorySeparatorChar);
}
// Append the last part without a "/"
pipeNameBuilder.Append(tokensByBackSlash[tokensByBackSlash.Length - 1]);
PipeName = pipeNameBuilder.ToString();
if (string.IsNullOrWhiteSpace(InstanceName) && !DefaultPipeName.Equals(PipeName))
{
InstanceName = PipeToken + PipeName;
}
ServerName = IsLocalHost(host) ? Environment.MachineName : host;
// Pipe hostname is the hostname after leading \\ which should be passed down as is to open Named Pipe.
// For Named Pipes the ServerName makes sense for SPN creation only.
PipeHostName = host;
}
catch (UriFormatException)
{
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
// DataSource is something like "\\pipename"
if (_connectionProtocol == Protocol.None)
{
_connectionProtocol = Protocol.NP;
}
else if (_connectionProtocol != Protocol.NP)
{
// In case the path began with a "\\" and protocol was not Named Pipes
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
return true;
}
return false;
}
private static bool IsLocalHost(string serverName)
=> ".".Equals(serverName) || "(local)".Equals(serverName) || "localhost".Equals(serverName);
}
}