/
SNINativeMethodWrapper.Windows.cs
511 lines (429 loc) · 20.6 KB
/
SNINativeMethodWrapper.Windows.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
// 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 Microsoft.Data.Common;
using Microsoft.Data.SqlClient;
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Microsoft.Data.SqlClient
{
internal static partial class SNINativeMethodWrapper
{
private const string SNI = "Microsoft.Data.SqlClient.SNI.dll";
private static int s_sniMaxComposedSpnLength = -1;
private const int SniOpenTimeOut = -1; // infinite
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SqlAsyncCallbackDelegate(IntPtr m_ConsKey, IntPtr pPacket, uint dwError);
internal const int SniIP6AddrStringBufferLength = 48; // from SNI layer
internal static int SniMaxComposedSpnLength
{
get
{
if (s_sniMaxComposedSpnLength == -1)
{
s_sniMaxComposedSpnLength = checked((int)GetSniMaxComposedSpnLength());
}
return s_sniMaxComposedSpnLength;
}
}
#region Structs\Enums
[StructLayout(LayoutKind.Sequential)]
internal struct ConsumerInfo
{
internal int defaultBufferSize;
internal SqlAsyncCallbackDelegate readDelegate;
internal SqlAsyncCallbackDelegate writeDelegate;
internal IntPtr key;
}
internal enum ConsumerNumber
{
SNI_Consumer_SNI,
SNI_Consumer_SSB,
SNI_Consumer_PacketIsReleased,
SNI_Consumer_Invalid,
}
internal enum IOType
{
READ,
WRITE,
}
internal enum PrefixEnum
{
UNKNOWN_PREFIX,
SM_PREFIX,
TCP_PREFIX,
NP_PREFIX,
VIA_PREFIX,
INVALID_PREFIX,
}
internal enum ProviderEnum
{
HTTP_PROV,
NP_PROV,
SESSION_PROV,
SIGN_PROV,
SM_PROV,
SMUX_PROV,
SSL_PROV,
TCP_PROV,
VIA_PROV,
MAX_PROVS,
INVALID_PROV,
}
internal enum QTypes
{
SNI_QUERY_CONN_INFO,
SNI_QUERY_CONN_BUFSIZE,
SNI_QUERY_CONN_KEY,
SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE,
SNI_QUERY_SERVER_ENCRYPT_POSSIBLE,
SNI_QUERY_CERTIFICATE,
SNI_QUERY_LOCALDB_HMODULE,
SNI_QUERY_CONN_ENCRYPT,
SNI_QUERY_CONN_PROVIDERNUM,
SNI_QUERY_CONN_CONNID,
SNI_QUERY_CONN_PARENTCONNID,
SNI_QUERY_CONN_SECPKG,
SNI_QUERY_CONN_NETPACKETSIZE,
SNI_QUERY_CONN_NODENUM,
SNI_QUERY_CONN_PACKETSRECD,
SNI_QUERY_CONN_PACKETSSENT,
SNI_QUERY_CONN_PEERADDR,
SNI_QUERY_CONN_PEERPORT,
SNI_QUERY_CONN_LASTREADTIME,
SNI_QUERY_CONN_LASTWRITETIME,
SNI_QUERY_CONN_CONSUMER_ID,
SNI_QUERY_CONN_CONNECTTIME,
SNI_QUERY_CONN_HTTPENDPOINT,
SNI_QUERY_CONN_LOCALADDR,
SNI_QUERY_CONN_LOCALPORT,
SNI_QUERY_CONN_SSLHANDSHAKESTATE,
SNI_QUERY_CONN_SOBUFAUTOTUNING,
SNI_QUERY_CONN_SECPKGNAME,
SNI_QUERY_CONN_SECPKGMUTUALAUTH,
SNI_QUERY_CONN_CONSUMERCONNID,
SNI_QUERY_CONN_SNIUCI,
SNI_QUERY_CONN_SUPPORTS_EXTENDED_PROTECTION,
SNI_QUERY_CONN_CHANNEL_PROVIDES_AUTHENTICATION_CONTEXT,
SNI_QUERY_CONN_PEERID,
SNI_QUERY_CONN_SUPPORTS_SYNC_OVER_ASYNC,
}
internal enum TransparentNetworkResolutionMode : byte
{
DisabledMode = 0,
SequentialMode,
ParallelMode
};
[StructLayout(LayoutKind.Sequential)]
private struct Sni_Consumer_Info
{
public int DefaultUserDataLength;
public IntPtr ConsumerKey;
public IntPtr fnReadComp;
public IntPtr fnWriteComp;
public IntPtr fnTrace;
public IntPtr fnAcceptComp;
public uint dwNumProts;
public IntPtr rgListenInfo;
public IntPtr NodeAffinity;
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct SNI_CLIENT_CONSUMER_INFO
{
public Sni_Consumer_Info ConsumerInfo;
[MarshalAs(UnmanagedType.LPWStr)]
public string wszConnectionString;
public PrefixEnum networkLibrary;
public byte* szSPN;
public uint cchSPN;
public byte* szInstanceName;
public uint cchInstanceName;
[MarshalAs(UnmanagedType.Bool)]
public bool fOverrideLastConnectCache;
[MarshalAs(UnmanagedType.Bool)]
public bool fSynchronousConnection;
public int timeout;
[MarshalAs(UnmanagedType.Bool)]
public bool fParallel;
public TransparentNetworkResolutionMode transparentNetworkResolution;
public int totalTimeout;
public bool isAzureSqlServerEndpoint;
public SNI_DNSCache_Info DNSCacheInfo;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct SNI_DNSCache_Info
{
[MarshalAs(UnmanagedType.LPWStr)]
public string wszCachedFQDN;
[MarshalAs(UnmanagedType.LPWStr)]
public string wszCachedTcpIPv4;
[MarshalAs(UnmanagedType.LPWStr)]
public string wszCachedTcpIPv6;
[MarshalAs(UnmanagedType.LPWStr)]
public string wszCachedTcpPort;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct SNI_Error
{
internal ProviderEnum provider;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 261)]
internal string errorMessage;
internal uint nativeError;
internal uint sniError;
[MarshalAs(UnmanagedType.LPWStr)]
internal string fileName;
[MarshalAs(UnmanagedType.LPWStr)]
internal string function;
internal uint lineNumber;
}
#endregion
#region DLL Imports
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIAddProviderWrapper")]
internal static extern uint SNIAddProvider(SNIHandle pConn, ProviderEnum ProvNum, [In] ref uint pInfo);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNICheckConnectionWrapper")]
internal static extern uint SNICheckConnection([In] SNIHandle pConn);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNICloseWrapper")]
internal static extern uint SNIClose(IntPtr pConn);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
internal static extern void SNIGetLastError(out SNI_Error pErrorStruct);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
internal static extern void SNIPacketRelease(IntPtr pPacket);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIPacketResetWrapper")]
internal static extern void SNIPacketReset([In] SNIHandle pConn, IOType IOType, SNIPacket pPacket, ConsumerNumber ConsNum);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
internal static extern uint SNIQueryInfo(QTypes QType, ref uint pbQInfo);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
internal static extern uint SNIQueryInfo(QTypes QType, ref IntPtr pbQInfo);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIReadAsyncWrapper")]
internal static extern uint SNIReadAsync(SNIHandle pConn, ref IntPtr ppNewPacket);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
internal static extern uint SNIReadSyncOverAsync(SNIHandle pConn, ref IntPtr ppNewPacket, int timeout);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIRemoveProviderWrapper")]
internal static extern uint SNIRemoveProvider(SNIHandle pConn, ProviderEnum ProvNum);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
internal static extern uint SNISecInitPackage(ref uint pcbMaxToken);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNISetInfoWrapper")]
internal static extern uint SNISetInfo(SNIHandle pConn, QTypes QType, [In] ref uint pbQInfo);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
internal static extern uint SNITerminate();
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIWaitForSSLHandshakeToCompleteWrapper")]
internal static extern uint SNIWaitForSSLHandshakeToComplete([In] SNIHandle pConn, int dwMilliseconds, out uint pProtocolVersion);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
internal static extern uint UnmanagedIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern uint GetSniMaxComposedSpnLength();
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIGetInfoWrapper([In] SNIHandle pConn, SNINativeMethodWrapper.QTypes QType, out Guid pbQInfo);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIGetInfoWrapper([In] SNIHandle pConn, SNINativeMethodWrapper.QTypes QType, out ushort portNum);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern uint SNIGetPeerAddrStrWrapper([In] SNIHandle pConn, int bufferSize, StringBuilder addrBuffer, out uint addrLen);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIGetInfoWrapper([In] SNIHandle pConn, SNINativeMethodWrapper.QTypes QType, out ProviderEnum provNum);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIInitialize([In] IntPtr pmo);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIOpenSyncExWrapper(ref SNI_CLIENT_CONSUMER_INFO pClientConsumerInfo, out IntPtr ppConn);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIOpenWrapper(
[In] ref Sni_Consumer_Info pConsumerInfo,
[MarshalAs(UnmanagedType.LPWStr)] string szConnect,
[In] SNIHandle pConn,
out IntPtr ppConn,
[MarshalAs(UnmanagedType.Bool)] bool fSync,
[In] ref SNI_DNSCache_Info pDNSCachedInfo);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr SNIPacketAllocateWrapper([In] SafeHandle pConn, IOType IOType);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIPacketGetDataWrapper([In] IntPtr packet, [In, Out] byte[] readBuffer, uint readBufferLength, out uint dataSize);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void SNIPacketSetData(SNIPacket pPacket, [In] byte* pbBuf, uint cbBuf);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe uint SNISecGenClientContextWrapper(
[In] SNIHandle pConn,
[In, Out] byte[] pIn,
uint cbIn,
[In, Out] byte[] pOut,
[In] ref uint pcbOut,
[MarshalAsAttribute(UnmanagedType.Bool)] out bool pfDone,
byte* szServerInfo,
uint cbServerInfo,
[MarshalAsAttribute(UnmanagedType.LPWStr)] string pwszUserName,
[MarshalAsAttribute(UnmanagedType.LPWStr)] string pwszPassword);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIWriteAsyncWrapper(SNIHandle pConn, [In] SNIPacket pPacket);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
internal static extern bool RegisterTraceProviderWrapper(int eventKeyword);
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
internal static extern void UnregisterTraceProviderWrapper();
#endregion
internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId)
{
return SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_CONNID, out connId);
}
internal static uint SniGetProviderNumber(SNIHandle pConn, ref ProviderEnum provNum)
{
return SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_PROVIDERNUM, out provNum);
}
internal static uint SniGetConnectionPort(SNIHandle pConn, ref ushort portNum)
{
return SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_PEERPORT, out portNum);
}
internal static uint SniGetConnectionIPString(SNIHandle pConn, ref string connIPStr)
{
UInt32 ret;
uint connIPLen = 0;
int bufferSize = SniIP6AddrStringBufferLength;
StringBuilder addrBuffer = new StringBuilder(bufferSize);
ret = SNIGetPeerAddrStrWrapper(pConn, bufferSize, addrBuffer, out connIPLen);
connIPStr = addrBuffer.ToString(0, Convert.ToInt32(connIPLen));
return ret;
}
internal static uint SNIInitialize()
{
return SNIInitialize(IntPtr.Zero);
}
internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync, SQLDNSInfo cachedDNSInfo)
{
// initialize consumer info for MARS
Sni_Consumer_Info native_consumerInfo = new Sni_Consumer_Info();
MarshalConsumerInfo(consumerInfo, ref native_consumerInfo);
SNI_DNSCache_Info native_cachedDNSInfo = new SNI_DNSCache_Info();
native_cachedDNSInfo.wszCachedFQDN = cachedDNSInfo?.FQDN;
native_cachedDNSInfo.wszCachedTcpIPv4 = cachedDNSInfo?.AddrIPv4;
native_cachedDNSInfo.wszCachedTcpIPv6 = cachedDNSInfo?.AddrIPv6;
native_cachedDNSInfo.wszCachedTcpPort = cachedDNSInfo?.Port;
return SNIOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync, ref native_cachedDNSInfo);
}
internal static unsafe uint SNIOpenSyncEx(ConsumerInfo consumerInfo, string constring, ref IntPtr pConn, byte[] spnBuffer, byte[] instanceName, bool fOverrideCache, bool fSync, int timeout, bool fParallel, SQLDNSInfo cachedDNSInfo)
{
fixed (byte* pin_instanceName = &instanceName[0])
{
SNI_CLIENT_CONSUMER_INFO clientConsumerInfo = new SNI_CLIENT_CONSUMER_INFO();
// initialize client ConsumerInfo part first
MarshalConsumerInfo(consumerInfo, ref clientConsumerInfo.ConsumerInfo);
clientConsumerInfo.wszConnectionString = constring;
clientConsumerInfo.networkLibrary = PrefixEnum.UNKNOWN_PREFIX;
clientConsumerInfo.szInstanceName = pin_instanceName;
clientConsumerInfo.cchInstanceName = (uint)instanceName.Length;
clientConsumerInfo.fOverrideLastConnectCache = fOverrideCache;
clientConsumerInfo.fSynchronousConnection = fSync;
clientConsumerInfo.timeout = timeout;
clientConsumerInfo.fParallel = fParallel;
clientConsumerInfo.transparentNetworkResolution = TransparentNetworkResolutionMode.DisabledMode;
clientConsumerInfo.totalTimeout = SniOpenTimeOut;
clientConsumerInfo.isAzureSqlServerEndpoint = ADP.IsAzureSqlServerEndpoint(constring);
clientConsumerInfo.DNSCacheInfo.wszCachedFQDN = cachedDNSInfo?.FQDN;
clientConsumerInfo.DNSCacheInfo.wszCachedTcpIPv4 = cachedDNSInfo?.AddrIPv4;
clientConsumerInfo.DNSCacheInfo.wszCachedTcpIPv6 = cachedDNSInfo?.AddrIPv6;
clientConsumerInfo.DNSCacheInfo.wszCachedTcpPort = cachedDNSInfo?.Port;
if (spnBuffer != null)
{
fixed (byte* pin_spnBuffer = &spnBuffer[0])
{
clientConsumerInfo.szSPN = pin_spnBuffer;
clientConsumerInfo.cchSPN = (uint)spnBuffer.Length;
return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn);
}
}
else
{
// else leave szSPN null (SQL Auth)
return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn);
}
}
}
internal static void SNIPacketAllocate(SafeHandle pConn, IOType IOType, ref IntPtr pPacket)
{
pPacket = SNIPacketAllocateWrapper(pConn, IOType);
}
internal static unsafe uint SNIPacketGetData(IntPtr packet, byte[] readBuffer, ref uint dataSize)
{
return SNIPacketGetDataWrapper(packet, readBuffer, (uint)readBuffer.Length, out dataSize);
}
internal static unsafe void SNIPacketSetData(SNIPacket packet, byte[] data, int length)
{
fixed (byte* pin_data = &data[0])
{
SNIPacketSetData(packet, pin_data, (uint)length);
}
}
internal static unsafe uint SNISecGenClientContext(SNIHandle pConnectionObject, byte[] inBuff, uint receivedLength, byte[] OutBuff, ref uint sendLength, byte[] serverUserName)
{
fixed (byte* pin_serverUserName = &serverUserName[0])
{
bool local_fDone;
return SNISecGenClientContextWrapper(
pConnectionObject,
inBuff,
receivedLength,
OutBuff,
ref sendLength,
out local_fDone,
pin_serverUserName,
(uint)serverUserName.Length,
null,
null);
}
}
internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync)
{
if (sync)
{
return SNIWriteSyncOverAsync(pConn, packet);
}
else
{
return SNIWriteAsyncWrapper(pConn, packet);
}
}
private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref Sni_Consumer_Info native_consumerInfo)
{
native_consumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize;
native_consumerInfo.fnReadComp = null != consumerInfo.readDelegate
? Marshal.GetFunctionPointerForDelegate(consumerInfo.readDelegate)
: IntPtr.Zero;
native_consumerInfo.fnWriteComp = null != consumerInfo.writeDelegate
? Marshal.GetFunctionPointerForDelegate(consumerInfo.writeDelegate)
: IntPtr.Zero;
native_consumerInfo.ConsumerKey = consumerInfo.key;
}
internal static bool RegisterTraceProvider(int eventKeyword)
{
// Registers the TraceLogging provider, enabling it to generate events.
// Return true if enabled, otherwise false.
return RegisterTraceProviderWrapper(eventKeyword);
}
internal static void UnregisterTraceProvider()
{
UnregisterTraceProviderWrapper();
}
}
}
namespace Microsoft.Data
{
internal static partial class SafeNativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)]
internal static extern IntPtr GetProcAddress(IntPtr HModule, [MarshalAs(UnmanagedType.LPStr), In] string funcName);
}
}
namespace Microsoft.Data
{
internal static class Win32NativeMethods
{
internal static bool IsTokenRestrictedWrapper(IntPtr token)
{
bool isRestricted;
uint result = SNINativeMethodWrapper.UnmanagedIsTokenRestricted(token, out isRestricted);
if (result != 0)
{
Marshal.ThrowExceptionForHR(unchecked((int)result));
}
return isRestricted;
}
}
}