-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathNpgsqlConnector.FrontendMessages.cs
More file actions
517 lines (423 loc) · 21.2 KB
/
NpgsqlConnector.FrontendMessages.cs
File metadata and controls
517 lines (423 loc) · 21.2 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Npgsql.Internal;
partial class NpgsqlConnector
{
internal Task WriteDescribe(StatementOrPortal statementOrPortal, byte[] asciiName, bool async, CancellationToken cancellationToken = default)
{
NpgsqlWriteBuffer.AssertASCIIOnly(asciiName);
var len = sizeof(byte) + // Message code
sizeof(int) + // Length
sizeof(byte) + // Statement or portal
(asciiName.Length + 1); // Statement/portal name
var writeBuffer = WriteBuffer;
writeBuffer.StartMessage(len);
if (writeBuffer.WriteSpaceLeft < len)
return FlushAndWrite(len, statementOrPortal, asciiName, async, cancellationToken);
Write(writeBuffer, len, statementOrPortal, asciiName);
return Task.CompletedTask;
async Task FlushAndWrite(int len, StatementOrPortal statementOrPortal, byte[] name, bool async, CancellationToken cancellationToken)
{
await Flush(async, cancellationToken).ConfigureAwait(false);
Debug.Assert(len <= WriteBuffer.WriteSpaceLeft, $"Message of type {GetType().Name} has length {len} which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
Write(WriteBuffer, len, statementOrPortal, name);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void Write(NpgsqlWriteBuffer writeBuffer, int len, StatementOrPortal statementOrPortal, byte[] name)
{
writeBuffer.WriteByte(FrontendMessageCode.Describe);
writeBuffer.WriteInt32(len - 1);
writeBuffer.WriteByte((byte)statementOrPortal);
writeBuffer.WriteNullTerminatedString(name);
}
}
internal Task WriteSync(bool async, CancellationToken cancellationToken = default)
{
const int len = sizeof(byte) + // Message code
sizeof(int); // Length
var writeBuffer = WriteBuffer;
writeBuffer.StartMessage(len);
if (writeBuffer.WriteSpaceLeft < len)
return FlushAndWrite(async, cancellationToken);
Write(writeBuffer);
return Task.CompletedTask;
async Task FlushAndWrite(bool async, CancellationToken cancellationToken)
{
await Flush(async, cancellationToken).ConfigureAwait(false);
Debug.Assert(len <= WriteBuffer.WriteSpaceLeft, $"Message of type {GetType().Name} has length {len} which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
Write(WriteBuffer);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void Write(NpgsqlWriteBuffer writeBuffer)
{
writeBuffer.WriteByte(FrontendMessageCode.Sync);
writeBuffer.WriteInt32(len - 1);
}
}
internal Task WriteExecute(int maxRows, bool async, CancellationToken cancellationToken = default)
{
// Note: non-empty portal currently not supported
const int len = sizeof(byte) + // Message code
sizeof(int) + // Length
sizeof(byte) + // Null-terminated portal name (always empty for now)
sizeof(int); // Max number of rows
var writeBuffer = WriteBuffer;
writeBuffer.StartMessage(len);
if (writeBuffer.WriteSpaceLeft < len)
return FlushAndWrite(maxRows, async, cancellationToken);
Write(writeBuffer, maxRows);
return Task.CompletedTask;
async Task FlushAndWrite(int maxRows, bool async, CancellationToken cancellationToken)
{
await Flush(async, cancellationToken).ConfigureAwait(false);
Debug.Assert(10 <= WriteBuffer.WriteSpaceLeft, $"Message of type {GetType().Name} has length 10 which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
Write(WriteBuffer, maxRows);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void Write(NpgsqlWriteBuffer writeBuffer, int maxRows)
{
writeBuffer.WriteByte(FrontendMessageCode.Execute);
writeBuffer.WriteInt32(len - 1);
writeBuffer.WriteByte(0); // Portal is always empty for now
writeBuffer.WriteInt32(maxRows);
}
}
internal async Task WriteParse(string sql, byte[] asciiName, List<NpgsqlParameter> inputParameters, bool async, CancellationToken cancellationToken = default)
{
NpgsqlWriteBuffer.AssertASCIIOnly(asciiName);
int queryByteLen;
try
{
queryByteLen = TextEncoding.GetByteCount(sql);
}
catch (Exception e)
{
Break(e);
throw;
}
var writeBuffer = WriteBuffer;
var messageLength =
sizeof(byte) + // Message code
sizeof(int) + // Length
asciiName.Length + // Statement name
sizeof(byte) + // Null terminator for the statement name
queryByteLen + sizeof(byte) + // SQL query length plus null terminator
sizeof(ushort) + // Number of parameters
inputParameters.Count * sizeof(int); // Parameter OIDs
WriteBuffer.StartMessage(messageLength);
if (WriteBuffer.WriteSpaceLeft < 1 + 4 + asciiName.Length + 1)
await Flush(async, cancellationToken).ConfigureAwait(false);
WriteBuffer.WriteByte(FrontendMessageCode.Parse);
WriteBuffer.WriteInt32(messageLength - 1);
WriteBuffer.WriteNullTerminatedString(asciiName);
await writeBuffer.WriteString(sql, queryByteLen, async, cancellationToken).ConfigureAwait(false);
if (writeBuffer.WriteSpaceLeft < 1 + 2)
await Flush(async, cancellationToken).ConfigureAwait(false);
writeBuffer.WriteByte(0); // Null terminator for the query
writeBuffer.WriteUInt16((ushort)inputParameters.Count);
var databaseInfo = DatabaseInfo;
foreach (var p in inputParameters)
{
if (writeBuffer.WriteSpaceLeft < 4)
await Flush(async, cancellationToken).ConfigureAwait(false);
writeBuffer.WriteUInt32(databaseInfo.GetOid(p.PgTypeId).Value);
}
}
internal async Task WriteBind(
List<NpgsqlParameter> parameters,
string portal,
byte[] asciiName,
bool allResultTypesAreUnknown,
bool[]? unknownResultTypeList,
bool async,
CancellationToken cancellationToken = default)
{
NpgsqlWriteBuffer.AssertASCIIOnly(asciiName);
NpgsqlWriteBuffer.AssertASCIIOnly(portal);
var headerLength =
sizeof(byte) + // Message code
sizeof(int) + // Message length
sizeof(byte) + // Portal is always empty (only a null terminator)
asciiName.Length + sizeof(byte) + // Statement name plus null terminator
sizeof(ushort); // Number of parameter format codes that follow
var writeBuffer = WriteBuffer;
var formatCodesSum = 0;
var paramsLength = 0;
for (var paramIndex = 0; paramIndex < parameters.Count; paramIndex++)
{
var param = parameters[paramIndex];
param.Bind(out var format, out var size);
paramsLength += size.Value > 0 ? size.Value : 0;
formatCodesSum += format.ToFormatCode();
}
var formatCodeListLength = formatCodesSum == 0 ? 0 : formatCodesSum == parameters.Count ? 1 : parameters.Count;
var messageLength = headerLength +
sizeof(short) * formatCodeListLength + // List of format codes
sizeof(short) + // Number of parameters
sizeof(int) * parameters.Count + // Parameter lengths
paramsLength + // Parameter values
sizeof(short) + // Number of result format codes
sizeof(short) * (unknownResultTypeList?.Length ?? 1); // Result format codes
WriteBuffer.StartMessage(messageLength);
if (WriteBuffer.WriteSpaceLeft < headerLength)
{
Debug.Assert(WriteBuffer.Size >= headerLength, "Write buffer too small for Bind header");
await Flush(async, cancellationToken).ConfigureAwait(false);
}
WriteBuffer.WriteByte(FrontendMessageCode.Bind);
WriteBuffer.WriteInt32(messageLength - 1);
Debug.Assert(portal == string.Empty);
writeBuffer.WriteByte(0); // Portal is always empty
writeBuffer.WriteNullTerminatedString(asciiName);
writeBuffer.WriteInt16((short)formatCodeListLength);
// 0 length implicitly means all-text, 1 means all-binary, >1 means mix-and-match
if (formatCodeListLength == 1)
{
if (writeBuffer.WriteSpaceLeft < sizeof(short))
await Flush(async, cancellationToken).ConfigureAwait(false);
writeBuffer.WriteInt16(DataFormat.Binary.ToFormatCode());
}
else if (formatCodeListLength > 1)
{
for (var paramIndex = 0; paramIndex < parameters.Count; paramIndex++)
{
if (writeBuffer.WriteSpaceLeft < sizeof(short))
await Flush(async, cancellationToken).ConfigureAwait(false);
writeBuffer.WriteInt16(parameters[paramIndex].Format.ToFormatCode());
}
}
if (writeBuffer.WriteSpaceLeft < sizeof(ushort))
await Flush(async, cancellationToken).ConfigureAwait(false);
writeBuffer.WriteUInt16((ushort)parameters.Count);
if (parameters.Count > 0)
{
var writer = writeBuffer.GetWriter(DatabaseInfo, async ? FlushMode.NonBlocking : FlushMode.Blocking);
try
{
for (var paramIndex = 0; paramIndex < parameters.Count; paramIndex++)
{
var param = parameters[paramIndex];
await param.Write(async, writer, cancellationToken).ConfigureAwait(false);
}
}
catch(Exception ex)
{
Break(ex);
throw;
}
}
if (unknownResultTypeList != null)
{
if (writeBuffer.WriteSpaceLeft < 2 + unknownResultTypeList.Length * 2)
await Flush(async, cancellationToken).ConfigureAwait(false);
writeBuffer.WriteInt16((short)unknownResultTypeList.Length);
foreach (var t in unknownResultTypeList)
writeBuffer.WriteInt16((short)(t ? 0 : 1));
}
else
{
if (writeBuffer.WriteSpaceLeft < 4)
await Flush(async, cancellationToken).ConfigureAwait(false);
writeBuffer.WriteInt16(1);
writeBuffer.WriteInt16((short)(allResultTypesAreUnknown ? 0 : 1));
}
}
internal Task WriteClose(StatementOrPortal type, byte[] asciiName, bool async, CancellationToken cancellationToken = default)
{
var len = sizeof(byte) + // Message code
sizeof(int) + // Length
sizeof(byte) + // Statement or portal
asciiName.Length + sizeof(byte); // Statement or portal name plus null terminator
var writeBuffer = WriteBuffer;
writeBuffer.StartMessage(len);
if (writeBuffer.WriteSpaceLeft < len)
return FlushAndWrite(len, type, asciiName, async, cancellationToken);
Write(writeBuffer, len, type, asciiName);
return Task.CompletedTask;
async Task FlushAndWrite(int len, StatementOrPortal type, byte[] name, bool async, CancellationToken cancellationToken)
{
await Flush(async, cancellationToken).ConfigureAwait(false);
Debug.Assert(len <= WriteBuffer.WriteSpaceLeft, $"Message of type {GetType().Name} has length {len} which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
Write(WriteBuffer, len, type, name);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void Write(NpgsqlWriteBuffer writeBuffer, int len, StatementOrPortal type, byte[] name)
{
writeBuffer.WriteByte(FrontendMessageCode.Close);
writeBuffer.WriteInt32(len - 1);
writeBuffer.WriteByte((byte)type);
writeBuffer.WriteNullTerminatedString(name);
}
}
internal async Task WriteQuery(string sql, bool async, CancellationToken cancellationToken = default)
{
var queryByteLen = TextEncoding.GetByteCount(sql);
var len = sizeof(byte) +
sizeof(int) + // Message length (including self excluding code)
queryByteLen + // Query byte length
sizeof(byte);
WriteBuffer.StartMessage(len);
if (WriteBuffer.WriteSpaceLeft < 1 + 4)
await Flush(async, cancellationToken).ConfigureAwait(false);
WriteBuffer.WriteByte(FrontendMessageCode.Query);
WriteBuffer.WriteInt32(len - 1);
await WriteBuffer.WriteString(sql, queryByteLen, async, cancellationToken).ConfigureAwait(false);
if (WriteBuffer.WriteSpaceLeft < 1)
await Flush(async, cancellationToken).ConfigureAwait(false);
WriteBuffer.WriteByte(0); // Null terminator
}
internal async Task WriteCopyDone(bool async, CancellationToken cancellationToken = default)
{
const int len = sizeof(byte) + // Message code
sizeof(int); // Length
WriteBuffer.StartMessage(len);
if (WriteBuffer.WriteSpaceLeft < len)
await Flush(async, cancellationToken).ConfigureAwait(false);
WriteBuffer.WriteByte(FrontendMessageCode.CopyDone);
WriteBuffer.WriteInt32(len - 1);
}
internal async Task WriteCopyFail(bool async, CancellationToken cancellationToken = default)
{
// Note: error message not supported for now
const int len = sizeof(byte) + // Message code
sizeof(int) + // Length
sizeof(byte); // Error message is always empty (only a null terminator)
WriteBuffer.StartMessage(len);
if (WriteBuffer.WriteSpaceLeft < len)
await Flush(async, cancellationToken).ConfigureAwait(false);
WriteBuffer.WriteByte(FrontendMessageCode.CopyFail);
WriteBuffer.WriteInt32(len - 1);
WriteBuffer.WriteByte(0); // Error message is always empty (only a null terminator)
}
internal void WriteCancelRequest(int backendProcessId, int backendSecretKey)
{
const int len = sizeof(int) + // Length
sizeof(int) + // Cancel request code
sizeof(int) + // Backend process id
sizeof(int); // Backend secret key
Debug.Assert(backendProcessId != 0);
WriteBuffer.StartMessage(len);
if (WriteBuffer.WriteSpaceLeft < len)
Flush(false).GetAwaiter().GetResult();
WriteBuffer.WriteInt32(len);
WriteBuffer.WriteInt32(1234 << 16 | 5678);
WriteBuffer.WriteInt32(backendProcessId);
WriteBuffer.WriteInt32(backendSecretKey);
}
internal void WriteTerminate()
{
const int len = sizeof(byte) + // Message code
sizeof(int); // Length
WriteBuffer.StartMessage(len);
if (WriteBuffer.WriteSpaceLeft < len)
Flush(false).GetAwaiter().GetResult();
WriteBuffer.WriteByte(FrontendMessageCode.Terminate);
WriteBuffer.WriteInt32(len - 1);
}
internal void WriteSslRequest()
{
const int len = sizeof(int) + // Length
sizeof(int); // SSL request code
WriteBuffer.StartMessage(len);
if (WriteBuffer.WriteSpaceLeft < len)
Flush(false).GetAwaiter().GetResult();
WriteBuffer.WriteInt32(len);
WriteBuffer.WriteInt32(80877103);
}
internal void WriteGSSEncryptRequest()
{
const int len = sizeof(int) + // Length
sizeof(int); // GSSEnc request code
WriteBuffer.StartMessage(len);
if (WriteBuffer.WriteSpaceLeft < len)
Flush(false).GetAwaiter().GetResult();
WriteBuffer.WriteInt32(len);
WriteBuffer.WriteInt32(80877104);
}
internal void WriteStartup(Dictionary<string, string> parameters)
{
const int protocolVersion3 = 3 << 16; // 196608
var len = sizeof(int) + // Length
sizeof(int) + // Protocol version
sizeof(byte); // Trailing zero byte
foreach (var kvp in parameters)
len += NpgsqlWriteBuffer.UTF8Encoding.GetByteCount(kvp.Key) + 1 +
NpgsqlWriteBuffer.UTF8Encoding.GetByteCount(kvp.Value) + 1;
// Should really never happen, just in case
WriteBuffer.StartMessage(len);
if (len > WriteBuffer.Size)
throw new Exception("Startup message bigger than buffer");
WriteBuffer.WriteInt32(len);
WriteBuffer.WriteInt32(protocolVersion3);
foreach (var kv in parameters)
{
WriteBuffer.WriteString(kv.Key);
WriteBuffer.WriteByte(0);
WriteBuffer.WriteString(kv.Value);
WriteBuffer.WriteByte(0);
}
WriteBuffer.WriteByte(0);
}
#region Authentication
internal Task WritePassword(byte[] payload, bool async, CancellationToken cancellationToken = default) => WritePassword(payload, 0, payload.Length, async, cancellationToken);
internal async Task WritePassword(byte[] payload, int offset, int count, bool async, CancellationToken cancellationToken = default)
{
WriteBuffer.StartMessage(sizeof(byte) + sizeof(int) + count);
if (WriteBuffer.WriteSpaceLeft < sizeof(byte) + sizeof(int))
await WriteBuffer.Flush(async, cancellationToken).ConfigureAwait(false);
WriteBuffer.WriteByte(FrontendMessageCode.Password);
WriteBuffer.WriteInt32(sizeof(int) + count);
if (count <= WriteBuffer.WriteSpaceLeft)
{
// The entire array fits in our WriteBuffer, copy it into the WriteBuffer as usual.
WriteBuffer.WriteBytes(payload, offset, count);
return;
}
await WriteBuffer.Flush(async, cancellationToken).ConfigureAwait(false);
await WriteBuffer.DirectWrite(new ReadOnlyMemory<byte>(payload, offset, count), async, cancellationToken).ConfigureAwait(false);
}
internal async Task WriteSASLInitialResponse(string mechanism, byte[] initialResponse, bool async, CancellationToken cancellationToken = default)
{
var len = sizeof(byte) + // Message code
sizeof(int) + // Length
NpgsqlWriteBuffer.UTF8Encoding.GetByteCount(mechanism) + sizeof(byte) + // Mechanism plus null terminator
sizeof(int) + // Initial response length
(initialResponse?.Length ?? 0); // Initial response payload
WriteBuffer.StartMessage(len);
if (WriteBuffer.WriteSpaceLeft < len)
await WriteBuffer.Flush(async, cancellationToken).ConfigureAwait(false);
WriteBuffer.WriteByte(FrontendMessageCode.Password);
WriteBuffer.WriteInt32(len - 1);
WriteBuffer.WriteString(mechanism);
WriteBuffer.WriteByte(0); // null terminator
if (initialResponse == null)
WriteBuffer.WriteInt32(-1);
else
{
WriteBuffer.WriteInt32(initialResponse.Length);
WriteBuffer.WriteBytes(initialResponse);
}
}
internal Task WriteSASLResponse(byte[] payload, bool async, CancellationToken cancellationToken = default) => WritePassword(payload, async, cancellationToken);
#endregion Authentication
internal Task WritePregenerated(byte[] data, bool async = false, CancellationToken cancellationToken = default)
{
WriteBuffer.StartMessage(data.Length);
if (WriteBuffer.WriteSpaceLeft < data.Length)
return FlushAndWrite(data, async, cancellationToken);
WriteBuffer.WriteBytes(data, 0, data.Length);
return Task.CompletedTask;
async Task FlushAndWrite(byte[] data, bool async, CancellationToken cancellationToken)
{
await Flush(async, cancellationToken).ConfigureAwait(false);
Debug.Assert(data.Length <= WriteBuffer.WriteSpaceLeft, $"Pregenerated message has length {data.Length} which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
WriteBuffer.WriteBytes(data, 0, data.Length);
}
}
internal void Flush() => WriteBuffer.Flush(false).GetAwaiter().GetResult();
internal Task Flush(bool async, CancellationToken cancellationToken = default) => WriteBuffer.Flush(async, cancellationToken);
}