forked from FirebirdSQL/NETProvider
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGdsConnection.cs
More file actions
590 lines (513 loc) · 19.4 KB
/
GdsConnection.cs
File metadata and controls
590 lines (513 loc) · 19.4 KB
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
/*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
* https://github.com/FirebirdSQL/NETProvider/raw/master/license.txt.
*
* Software distributed under the License is distributed on
* an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either
* express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* All Rights Reserved.
*/
//$Authors = Carlos Guzman Alvarez, Jiri Cincura (jiri@cincura.net)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using FirebirdSql.Data.Common;
namespace FirebirdSql.Data.Client.Managed;
internal sealed class GdsConnection
{
private NetworkStream _networkStream;
private FirebirdNetworkHandlingWrapper _firebirdNetworkHandlingWrapper;
public string User { get; private set; }
public string Password { get; private set; }
public string DataSource { get; private set; }
public int PortNumber { get; private set; }
public int Timeout { get; private set; }
public int PacketSize { get; private set; }
public Charset Charset { get; private set; }
public short Dialect { get; private set; }
public bool Compression { get; private set; }
public Version13.WireCryptOption WireCrypt { get; private set; }
public byte[] CryptKey { get; private set; }
public int ProtocolVersion { get; private set; }
public int ProtocolArchitecture { get; private set; }
public int ProtocolMinimunType { get; private set; }
public bool ConnectionBroken => _firebirdNetworkHandlingWrapper?.IOFailed ?? false;
internal IPAddress IPAddress { get; private set; }
internal XdrReaderWriter Xdr { get; private set; }
internal AuthBlock AuthBlock { get; private set; }
public GdsConnection(string dataSource, int port, int timeout)
: this(null, null, dataSource, port, timeout, 8192, Charset.DefaultCharset, 3, false, Version13.WireCryptOption.Enabled, null)
{ }
public GdsConnection(string user, string password, string dataSource, int portNumber, int timeout, int packetSize, Charset charset, short dialect, bool compression, Version13.WireCryptOption wireCrypt, byte[] cryptKey)
{
User = user;
Password = password;
DataSource = dataSource;
PortNumber = portNumber;
Timeout = timeout;
PacketSize = packetSize;
Charset = charset;
Dialect = dialect;
Compression = compression;
WireCrypt = wireCrypt;
CryptKey = cryptKey;
}
public void Connect()
{
try
{
IPAddress = GetIPAddress(DataSource);
var endPoint = new IPEndPoint(IPAddress, PortNumber);
var socket = new Socket(IPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, PacketSize);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, PacketSize);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
socket.Connect(endPoint);
_networkStream = new NetworkStream(socket, true);
_firebirdNetworkHandlingWrapper = new FirebirdNetworkHandlingWrapper(new DataProviderStreamWrapper(_networkStream));
Xdr = new XdrReaderWriter(_firebirdNetworkHandlingWrapper, Charset);
}
catch (SocketException ex)
{
throw IscException.ForTypeErrorCodeStrParam(IscCodes.isc_arg_gds, IscCodes.isc_network_error, DataSource, ex);
}
}
public async ValueTask ConnectAsync(CancellationToken cancellationToken = default)
{
try
{
IPAddress = await GetIPAddressAsync(DataSource, cancellationToken).ConfigureAwait(false);
var endPoint = new IPEndPoint(IPAddress, PortNumber);
var socket = new Socket(IPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, PacketSize);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, PacketSize);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
using (var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(Timeout)))
{
using (var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, cancellationToken))
{
await socket.ConnectAsync(endPoint, combinedCts.Token).ConfigureAwait(false);
}
}
_networkStream = new NetworkStream(socket, true);
_firebirdNetworkHandlingWrapper = new FirebirdNetworkHandlingWrapper(new DataProviderStreamWrapper(_networkStream));
Xdr = new XdrReaderWriter(_firebirdNetworkHandlingWrapper, Charset);
}
catch (SocketException ex)
{
throw IscException.ForTypeErrorCodeStrParam(IscCodes.isc_arg_gds, IscCodes.isc_network_error, DataSource, ex);
}
}
public void Identify(string database)
{
try
{
Xdr.Write(IscCodes.op_connect);
Xdr.Write(IscCodes.op_attach);
Xdr.Write(IscCodes.CONNECT_VERSION3);
Xdr.Write(IscCodes.GenericAchitectureClient);
Xdr.Write(database);
var protocols = ProtocolsSupported.Get(Compression);
Xdr.Write(protocols.Count());
AuthBlock = new AuthBlock(this, User, Password, WireCrypt);
Xdr.WriteBuffer(AuthBlock.UserIdentificationData());
var priority = 0;
foreach (var protocol in protocols)
{
Xdr.Write(protocol.Version);
Xdr.Write(IscCodes.GenericAchitectureClient);
Xdr.Write(IscCodes.p_cnct_min_type);
Xdr.Write(protocol.MaxPType);
Xdr.Write(priority);
priority++;
}
Xdr.Flush();
var operation = Xdr.ReadOperation();
while (operation == IscCodes.op_crypt_key_callback)
{
var data = Xdr.ReadBuffer();
var size = Xdr.ReadInt32();
Xdr.Write(IscCodes.op_crypt_key_callback);
Xdr.WriteBuffer(CryptKey);
Xdr.Write(size);
Xdr.Flush();
operation = Xdr.ReadOperation();
}
if (operation == IscCodes.op_accept || operation == IscCodes.op_cond_accept || operation == IscCodes.op_accept_data)
{
ProtocolVersion = Xdr.ReadInt32();
ProtocolArchitecture = Xdr.ReadInt32();
ProtocolMinimunType = Xdr.ReadInt32();
if (ProtocolVersion < 0)
{
ProtocolVersion = (ushort)(ProtocolVersion & IscCodes.FB_PROTOCOL_MASK) | IscCodes.FB_PROTOCOL_FLAG;
}
if (Compression && !((ProtocolMinimunType & IscCodes.pflag_compress) != 0))
{
Compression = false;
}
if (operation == IscCodes.op_cond_accept || operation == IscCodes.op_accept_data)
{
AuthBlock.Start(
Xdr.ReadBuffer(),
Xdr.ReadString(),
Xdr.ReadBoolean(),
Xdr.ReadBuffer());
if (Compression)
{
// after reading before writing
StartCompression();
}
if (operation == IscCodes.op_cond_accept)
{
while (true)
{
AuthBlock.SendContAuthToBuffer();
Xdr.Flush();
var response = AuthBlock.ProcessContAuthResponse();
if (response is Version13.ContAuthResponse contAuthResponse)
{
AuthBlock.Start(contAuthResponse.ServerData, contAuthResponse.AcceptPluginName, contAuthResponse.IsAuthenticated, contAuthResponse.ServerKeys);
continue;
}
break;
}
if (AuthBlock.ServerKeys.Length > 0)
{
AuthBlock.SendWireCryptToBuffer();
Xdr.Flush();
AuthBlock.ProcessWireCryptResponse();
}
}
}
AuthBlock.WireCryptValidate(ProtocolVersion);
}
else if (operation == IscCodes.op_response)
{
var response = (GenericResponse)ProcessOperation(operation);
response.HandleResponseException();
}
else
{
throw IscException.ForErrorCode(IscCodes.isc_connect_reject);
}
}
catch (IOException ex)
{
throw IscException.ForIOException(ex);
}
}
public async ValueTask IdentifyAsync(string database, CancellationToken cancellationToken = default)
{
try
{
await Xdr.WriteAsync(IscCodes.op_connect, cancellationToken).ConfigureAwait(false);
await Xdr.WriteAsync(IscCodes.op_attach, cancellationToken).ConfigureAwait(false);
await Xdr.WriteAsync(IscCodes.CONNECT_VERSION3, cancellationToken).ConfigureAwait(false);
await Xdr.WriteAsync(IscCodes.GenericAchitectureClient, cancellationToken).ConfigureAwait(false);
await Xdr.WriteAsync(database, cancellationToken).ConfigureAwait(false);
var protocols = ProtocolsSupported.Get(Compression);
await Xdr.WriteAsync(protocols.Count(), cancellationToken).ConfigureAwait(false);
AuthBlock = new AuthBlock(this, User, Password, WireCrypt);
await Xdr.WriteBufferAsync(AuthBlock.UserIdentificationData(), cancellationToken).ConfigureAwait(false);
var priority = 0;
foreach (var protocol in protocols)
{
await Xdr.WriteAsync(protocol.Version, cancellationToken).ConfigureAwait(false);
await Xdr.WriteAsync(IscCodes.GenericAchitectureClient, cancellationToken).ConfigureAwait(false);
await Xdr.WriteAsync(IscCodes.p_cnct_min_type, cancellationToken).ConfigureAwait(false);
await Xdr.WriteAsync(protocol.MaxPType, cancellationToken).ConfigureAwait(false);
await Xdr.WriteAsync(priority, cancellationToken).ConfigureAwait(false);
priority++;
}
await Xdr.FlushAsync(cancellationToken).ConfigureAwait(false);
var operation = await Xdr.ReadOperationAsync(cancellationToken).ConfigureAwait(false);
while (operation == IscCodes.op_crypt_key_callback)
{
var data = await Xdr.ReadBufferAsync(cancellationToken).ConfigureAwait(false);
var size = await Xdr.ReadInt32Async(cancellationToken).ConfigureAwait(false);
await Xdr.WriteAsync(IscCodes.op_crypt_key_callback, cancellationToken).ConfigureAwait(false);
await Xdr.WriteBufferAsync(CryptKey, cancellationToken).ConfigureAwait(false);
await Xdr.WriteAsync(size, cancellationToken).ConfigureAwait(false);
await Xdr.FlushAsync(cancellationToken).ConfigureAwait(false);
operation = await Xdr.ReadOperationAsync(cancellationToken).ConfigureAwait(false);
}
if (operation == IscCodes.op_accept || operation == IscCodes.op_cond_accept || operation == IscCodes.op_accept_data)
{
ProtocolVersion = await Xdr.ReadInt32Async(cancellationToken).ConfigureAwait(false);
ProtocolArchitecture = await Xdr.ReadInt32Async(cancellationToken).ConfigureAwait(false);
ProtocolMinimunType = await Xdr.ReadInt32Async(cancellationToken).ConfigureAwait(false);
if (ProtocolVersion < 0)
{
ProtocolVersion = (ushort)(ProtocolVersion & IscCodes.FB_PROTOCOL_MASK) | IscCodes.FB_PROTOCOL_FLAG;
}
if (Compression && !((ProtocolMinimunType & IscCodes.pflag_compress) != 0))
{
Compression = false;
}
if (operation == IscCodes.op_cond_accept || operation == IscCodes.op_accept_data)
{
AuthBlock.Start(
await Xdr.ReadBufferAsync(cancellationToken).ConfigureAwait(false),
await Xdr.ReadStringAsync(cancellationToken).ConfigureAwait(false),
await Xdr.ReadBooleanAsync(cancellationToken).ConfigureAwait(false),
await Xdr.ReadBufferAsync(cancellationToken).ConfigureAwait(false));
if (Compression)
{
// after reading before writing
StartCompression();
}
if (operation == IscCodes.op_cond_accept)
{
while (true)
{
await AuthBlock.SendContAuthToBufferAsync(cancellationToken).ConfigureAwait(false);
await Xdr.FlushAsync(cancellationToken).ConfigureAwait(false);
var response = await AuthBlock.ProcessContAuthResponseAsync(cancellationToken).ConfigureAwait(false);
if (response is Version13.ContAuthResponse contAuthResponse)
{
AuthBlock.Start(contAuthResponse.ServerData, contAuthResponse.AcceptPluginName, contAuthResponse.IsAuthenticated, contAuthResponse.ServerKeys);
continue;
}
break;
}
if (AuthBlock.ServerKeys.Length > 0)
{
await AuthBlock.SendWireCryptToBufferAsync(cancellationToken).ConfigureAwait(false);
await Xdr.FlushAsync(cancellationToken).ConfigureAwait(false);
await AuthBlock.ProcessWireCryptResponseAsync(cancellationToken).ConfigureAwait(false);
}
}
}
AuthBlock.WireCryptValidate(ProtocolVersion);
}
else if (operation == IscCodes.op_response)
{
var response = (GenericResponse)await ProcessOperationAsync(operation, cancellationToken).ConfigureAwait(false);
response.HandleResponseException();
}
else
{
throw IscException.ForErrorCode(IscCodes.isc_connect_reject);
}
}
catch (IOException ex)
{
throw IscException.ForIOException(ex);
}
}
public void Disconnect()
{
if (_networkStream != null)
{
_networkStream.Dispose();
_networkStream = null;
}
}
public async ValueTask DisconnectAsync(CancellationToken cancellationToken = default)
{
if (_networkStream != null)
{
await _networkStream.DisposeAsync().ConfigureAwait(false);
_networkStream = null;
}
}
internal IResponse ProcessOperation(int operation)
{
switch (operation)
{
case IscCodes.op_response:
return new GenericResponse(
Xdr.ReadInt32(),
Xdr.ReadInt64(),
Xdr.ReadBuffer(),
Xdr.ReadStatusVector());
case IscCodes.op_fetch_response:
return new FetchResponse(
Xdr.ReadInt32(),
Xdr.ReadInt32());
case IscCodes.op_sql_response:
return new SqlResponse(
Xdr.ReadInt32());
case IscCodes.op_trusted_auth:
return new Version11.AuthResponse(
Xdr.ReadBuffer());
case IscCodes.op_crypt_key_callback:
if (ProtocolVersion == IscCodes.PROTOCOL_VERSION15
|| ProtocolVersion == IscCodes.PROTOCOL_VERSION16)
{
return new Version15.CryptKeyCallbackResponse(
Xdr.ReadBuffer(),
Xdr.ReadInt32());
}
else
{
return new Version13.CryptKeyCallbackResponse(
Xdr.ReadBuffer());
}
case IscCodes.op_cont_auth:
return new Version13.ContAuthResponse(
Xdr.ReadBuffer(),
Xdr.ReadString(),
Xdr.ReadBoolean(),
Xdr.ReadBuffer());
case IscCodes.op_batch_cs:
var statementHandle = Xdr.ReadInt16();
var p_batch_reccount = Xdr.ReadInt32();
var p_batch_updates = Xdr.ReadInt32();
var p_batch_vectors = Xdr.ReadInt32();
var p_batch_errors = Xdr.ReadInt32();
var p_batch_updates_data = new int[p_batch_updates];
for (var i = 0; i < p_batch_updates; i++)
{
p_batch_updates_data[i] = Xdr.ReadInt32();
}
var p_batch_vectors_data = new (int messageNumber, IscException statusVector)[p_batch_vectors];
for (var i = 0; i < p_batch_vectors; i++)
{
var messageNumber = Xdr.ReadInt32();
var statusVector = Xdr.ReadStatusVector();
p_batch_vectors_data[i] = (messageNumber, statusVector);
}
var p_batch_errors_data = new int[p_batch_errors];
for (var i = 0; i < p_batch_errors; i++)
{
p_batch_errors_data[i] = Xdr.ReadInt32();
}
return new Version16.BatchCompletionStateResponse(
statementHandle,
p_batch_reccount,
p_batch_updates_data,
p_batch_vectors_data,
p_batch_errors_data);
default:
throw new ArgumentOutOfRangeException(nameof(operation), $"{nameof(operation)}={operation}");
}
}
internal async ValueTask<IResponse> ProcessOperationAsync(int operation, CancellationToken cancellationToken = default)
{
switch (operation)
{
case IscCodes.op_response:
return new GenericResponse(
await Xdr.ReadInt32Async(cancellationToken).ConfigureAwait(false),
await Xdr.ReadInt64Async(cancellationToken).ConfigureAwait(false),
await Xdr.ReadBufferAsync(cancellationToken).ConfigureAwait(false),
await Xdr.ReadStatusVectorAsync(cancellationToken).ConfigureAwait(false));
case IscCodes.op_fetch_response:
return new FetchResponse(
await Xdr.ReadInt32Async(cancellationToken).ConfigureAwait(false),
await Xdr.ReadInt32Async(cancellationToken).ConfigureAwait(false));
case IscCodes.op_sql_response:
return new SqlResponse(
await Xdr.ReadInt32Async(cancellationToken).ConfigureAwait(false));
case IscCodes.op_trusted_auth:
return new Version11.AuthResponse(
await Xdr.ReadBufferAsync(cancellationToken).ConfigureAwait(false));
case IscCodes.op_crypt_key_callback:
if (ProtocolVersion == IscCodes.PROTOCOL_VERSION15
|| ProtocolVersion == IscCodes.PROTOCOL_VERSION16)
{
return new Version15.CryptKeyCallbackResponse(
await Xdr.ReadBufferAsync(cancellationToken).ConfigureAwait(false),
await Xdr.ReadInt32Async(cancellationToken).ConfigureAwait(false));
}
else
{
return new Version13.CryptKeyCallbackResponse(
await Xdr.ReadBufferAsync(cancellationToken).ConfigureAwait(false));
}
case IscCodes.op_cont_auth:
return new Version13.ContAuthResponse(
await Xdr.ReadBufferAsync(cancellationToken).ConfigureAwait(false),
await Xdr.ReadStringAsync(cancellationToken).ConfigureAwait(false),
await Xdr.ReadBooleanAsync(cancellationToken).ConfigureAwait(false),
await Xdr.ReadBufferAsync(cancellationToken).ConfigureAwait(false));
case IscCodes.op_batch_cs:
var statementHandle = await Xdr.ReadInt16Async().ConfigureAwait(false);
var p_batch_reccount = await Xdr.ReadInt32Async().ConfigureAwait(false);
var p_batch_updates = await Xdr.ReadInt32Async().ConfigureAwait(false);
var p_batch_vectors = await Xdr.ReadInt32Async().ConfigureAwait(false);
var p_batch_errors = await Xdr.ReadInt32Async().ConfigureAwait(false);
var p_batch_updates_data = new int[p_batch_updates];
for (var i = 0; i < p_batch_updates; i++)
{
p_batch_updates_data[i] = await Xdr.ReadInt32Async().ConfigureAwait(false);
}
var p_batch_vectors_data = new (int messageNumber, IscException statusVector)[p_batch_vectors];
for (var i = 0; i < p_batch_vectors; i++)
{
var messageNumber = await Xdr.ReadInt32Async().ConfigureAwait(false);
var statusVector = await Xdr.ReadStatusVectorAsync().ConfigureAwait(false);
p_batch_vectors_data[i] = (messageNumber, statusVector);
}
var p_batch_errors_data = new int[p_batch_errors];
for (var i = 0; i < p_batch_errors; i++)
{
p_batch_errors_data[i] = await Xdr.ReadInt32Async().ConfigureAwait(false);
}
return new Version16.BatchCompletionStateResponse(
statementHandle,
p_batch_reccount,
p_batch_updates_data,
p_batch_vectors_data,
p_batch_errors_data);
default:
throw new ArgumentOutOfRangeException(nameof(operation), $"{nameof(operation)}={operation}");
}
}
internal void StartCompression()
{
_firebirdNetworkHandlingWrapper.StartCompression();
}
internal void StartEncryption()
{
_firebirdNetworkHandlingWrapper.StartEncryption(AuthBlock.SessionKey);
}
private static IPAddress GetIPAddress(string dataSource)
{
if (IPAddress.TryParse(dataSource, out var ipaddress))
{
return ipaddress;
}
var addresses = (Dns.GetHostEntry(dataSource)).AddressList;
foreach (var address in addresses)
{
// IPv4 priority
if (address.AddressFamily == AddressFamily.InterNetwork)
{
return address;
}
}
return addresses[0];
}
private static async ValueTask<IPAddress> GetIPAddressAsync(string dataSource, CancellationToken cancellationToken = default)
{
if (IPAddress.TryParse(dataSource, out var ipaddress))
{
return ipaddress;
}
var addresses = (await Dns.GetHostEntryAsync(dataSource).ConfigureAwait(false)).AddressList;
foreach (var address in addresses)
{
// IPv4 priority
if (address.AddressFamily == AddressFamily.InterNetwork)
{
return address;
}
}
return addresses[0];
}
}