/
TcpListenerChannel.cs
583 lines (498 loc) · 19.9 KB
/
TcpListenerChannel.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
/* Copyright (c) 1996-2022 The OPC Foundation. All rights reserved.
The source code in this file is covered under a dual-license scenario:
- RCL: for OPC Foundation Corporate Members in good-standing
- GPL V2: everybody else
RCL license terms accompanied with this source code. See http://opcfoundation.org/License/RCL/1.00/
GNU General Public License as published by the Free Software Foundation;
version 2 of the License are accompanied with this source code. See http://opcfoundation.org/License/GPLv2
This source code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
using System;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.Logging;
namespace Opc.Ua.Bindings
{
/// <summary>
/// Manages the listening side of a UA TCP channel.
/// </summary>
public class TcpListenerChannel : UaSCUaBinaryChannel
{
#region Constructors
/// <summary>
/// Attaches the object to an existing socket.
/// </summary>
public TcpListenerChannel(
string contextId,
ITcpChannelListener listener,
BufferManager bufferManager,
ChannelQuotas quotas,
X509Certificate2 serverCertificate,
EndpointDescriptionCollection endpoints)
:
this(contextId, listener, bufferManager, quotas, serverCertificate, null, endpoints)
{
}
/// <summary>
/// Attaches the object to an existing socket.
/// </summary>
public TcpListenerChannel(
string contextId,
ITcpChannelListener listener,
BufferManager bufferManager,
ChannelQuotas quotas,
X509Certificate2 serverCertificate,
X509Certificate2Collection serverCertificateChain,
EndpointDescriptionCollection endpoints)
:
base(contextId, bufferManager, quotas, serverCertificate, serverCertificateChain, endpoints, MessageSecurityMode.None, SecurityPolicies.None)
{
m_listener = listener;
}
#endregion
#region IDisposable Members
/// <summary>
/// An overrideable version of the Dispose.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region Public Methods
/// <summary>
/// The channel name used in trace output.
/// </summary>
public virtual string ChannelName => "TCPLISTENERCHANNEL";
/// <summary>
/// The TCP channel listener.
/// </summary>
protected ITcpChannelListener Listener => m_listener;
/// <summary>
/// Sets the callback used to receive notifications of new events.
/// </summary>
public void SetRequestReceivedCallback(TcpChannelRequestEventHandler callback)
{
lock (DataLock)
{
m_requestReceived = callback;
}
}
/// <summary>
/// Sets the callback used to raise channel audit events.
/// </summary>
public void SetReportOpenSecureChannelAuditCallback(ReportAuditOpenSecureChannelEventHandler callback)
{
lock (DataLock)
{
m_reportAuditOpenSecureChannelEvent = callback;
}
}
/// <summary>
/// Sets the callback used to raise channel audit events.
/// </summary>
public void SetReportCloseSecureChannelAuditCallback(ReportAuditCloseSecureChannelEventHandler callback)
{
lock (DataLock)
{
m_reportAuditCloseSecureChannelEvent = callback;
}
}
/// <summary>
/// Sets the callback used to raise channel audit events.
/// </summary>
public void SetReportCertificateAuditCallback(ReportAuditCertificateEventHandler callback)
{
lock (DataLock)
{
m_reportAuditCertificateEvent = callback;
}
}
/// <summary>
/// Attaches the channel to an existing socket.
/// </summary>
public void Attach(uint channelId, Socket socket)
{
if (socket == null) throw new ArgumentNullException(nameof(socket));
lock (DataLock)
{
// check for existing socket.
if (Socket != null)
{
throw new InvalidOperationException("Channel is already attached to a socket.");
}
ChannelId = channelId;
State = TcpChannelState.Connecting;
Socket = new TcpMessageSocket(this, socket, BufferManager, Quotas.MaxBufferSize);
Utils.LogTrace("{0} SOCKET ATTACHED: {1:X8}, ChannelId={2}", ChannelName, Socket.Handle, ChannelId);
Socket.ReadNextMessage();
}
}
/// <summary>
/// Clean up an Opening or Open channel that has been idle for too long.
/// </summary>
public void IdleCleanup()
{
TcpChannelState state;
lock (DataLock)
{
state = State;
if (state == TcpChannelState.Open)
{
state = State = TcpChannelState.Closing;
}
}
if (state == TcpChannelState.Closing || state == TcpChannelState.Opening || state == TcpChannelState.Faulted)
{
OnCleanup(new ServiceResult(StatusCodes.BadNoCommunication, "Channel closed due to inactivity."));
}
}
/// <summary>
/// The time in milliseconds elapsed since the channel received or sent messages
/// or received a keep alive.
/// </summary>
public int ElapsedSinceLastActiveTime => (HiResClock.TickCount - LastActiveTickCount);
#endregion
#region Socket Event Handlers
#endregion
#region Error Handling Functions
/// <summary>
/// Handles a socket error.
/// </summary>
protected override void HandleSocketError(ServiceResult result)
{
lock (DataLock)
{
// channel fault.
if (ServiceResult.IsBad(result))
{
ForceChannelFault(result);
return;
}
// gracefully shutdown the channel.
ChannelClosed();
}
}
/// <summary>
/// Forces the channel into a faulted state as a result of a fatal error.
/// </summary>
protected void ForceChannelFault(uint statusCode, string format, params object[] args)
{
ForceChannelFault(ServiceResult.Create(statusCode, format, args));
}
/// <summary>
/// Forces the channel into a faulted state as a result of a fatal error.
/// </summary>
protected void ForceChannelFault(Exception exception, uint defaultCode, string format, params object[] args)
{
ForceChannelFault(ServiceResult.Create(exception, defaultCode, format, args));
}
/// <summary>
/// Forces the channel into a faulted state as a result of a fatal error.
/// </summary>
protected void ForceChannelFault(ServiceResult reason)
{
lock (DataLock)
{
CompleteReverseHello(new ServiceResultException(reason));
// nothing to do if channel already in a faulted state.
if (State == TcpChannelState.Faulted)
{
return;
}
bool close = false;
if (State != TcpChannelState.Connecting)
{
int socketHandle = (Socket != null) ? Socket.Handle : 0;
if (socketHandle != -1)
{
Utils.LogError(
"{0} ForceChannelFault Socket={1:X8}, ChannelId={2}, TokenId={3}, Reason={4}",
ChannelName,
socketHandle,
(CurrentToken != null) ? CurrentToken.ChannelId : 0,
(CurrentToken != null) ? CurrentToken.TokenId : 0,
reason);
}
}
else
{
// Close immediately if the client never got out of connecting state
close = true;
}
// send error and close response.
if (Socket != null)
{
if (m_responseRequired)
{
SendErrorMessage(reason);
}
}
State = TcpChannelState.Faulted;
m_responseRequired = false;
if (close)
{
// close channel immediately.
ChannelClosed();
}
else
{
// notify any monitors.
NotifyMonitors(reason, false);
}
}
}
/// <summary>
/// Called when the channel needs to be cleaned up.
/// </summary>
private void OnCleanup(object state)
{
lock (DataLock)
{
// nothing to do if the channel is now open or closed.
if (State == TcpChannelState.Closed || State == TcpChannelState.Open)
{
return;
}
// get reason for cleanup.
if (!(state is ServiceResult reason))
{
reason = new ServiceResult(StatusCodes.BadTimeout);
}
Utils.LogInfo(
"{0} Cleanup Socket={1:X8}, ChannelId={2}, TokenId={3}, Reason={4}",
ChannelName,
(Socket != null) ? Socket.Handle : 0,
(CurrentToken != null) ? CurrentToken.ChannelId : 0,
(CurrentToken != null) ? CurrentToken.TokenId : 0,
reason.ToString());
// close channel.
ChannelClosed();
}
}
/// <summary>
/// Closes the channel and releases resources.
/// </summary>
protected void ChannelClosed()
{
try
{
if (Socket != null)
{
Socket.Close();
}
}
finally
{
State = TcpChannelState.Closed;
m_listener.ChannelClosed(ChannelId);
// notify any monitors.
NotifyMonitors(new ServiceResult(StatusCodes.BadConnectionClosed), true);
}
}
/// <summary>
/// Sends an error message over the socket.
/// </summary>
protected void SendErrorMessage(ServiceResult error)
{
Utils.LogTrace("ChannelId {0}: SendErrorMessage={1}", ChannelId, error.StatusCode);
byte[] buffer = BufferManager.TakeBuffer(SendBufferSize, "SendErrorMessage");
try
{
using (BinaryEncoder encoder = new BinaryEncoder(buffer, 0, SendBufferSize, Quotas.MessageContext))
{
encoder.WriteUInt32(null, TcpMessageType.Error);
encoder.WriteUInt32(null, 0);
WriteErrorMessageBody(encoder, error);
int size = encoder.Close();
UpdateMessageSize(buffer, 0, size);
BeginWriteMessage(new ArraySegment<byte>(buffer, 0, size), null);
buffer = null;
}
}
finally
{
if (buffer != null)
{
BufferManager.ReturnBuffer(buffer, "SendErrorMessage");
}
}
}
/// <summary>
/// Sends a fault response secured with the symmetric keys.
/// </summary>
protected void SendServiceFault(ChannelToken token, uint requestId, ServiceResult fault)
{
Utils.LogTrace("ChannelId {0}: Request {1}: SendServiceFault={2}", ChannelId, requestId, fault.StatusCode);
BufferCollection buffers = null;
try
{
// construct fault.
ServiceFault response = new ServiceFault();
response.ResponseHeader.ServiceResult = fault.Code;
StringTable stringTable = new StringTable();
response.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo(
fault,
DiagnosticsMasks.NoInnerStatus,
true,
stringTable);
response.ResponseHeader.StringTable = stringTable.ToArray();
// the limits should never be exceeded when sending a fault.
bool limitsExceeded = false;
// secure message.
buffers = WriteSymmetricMessage(
TcpMessageType.Message,
requestId,
token,
response,
false,
out limitsExceeded);
// send message.
BeginWriteMessage(buffers, null);
buffers = null;
}
catch (Exception e)
{
if (buffers != null)
{
buffers.Release(BufferManager, "SendServiceFault");
}
ForceChannelFault(ServiceResult.Create(e, StatusCodes.BadTcpInternalError, "Unexpected error sending a service fault."));
}
}
/// <summary>
/// Notify if the channel status changed.
/// </summary>
protected virtual void NotifyMonitors(ServiceResult status, bool closed)
{
// intentionally left empty
}
/// <summary>
/// Called to indicate an error or success if the listener
/// channel initiated a reverse hello connection.
/// </summary>
/// <remarks>
/// The callback is only used by the server channel.
/// The listener channel uses the callback to indicate
/// an error condition to the server channel.
/// </remarks>
protected virtual void CompleteReverseHello(Exception e)
{
// intentionally left empty
}
/// <summary>
/// Sends a fault response secured with the asymmetric keys.
/// </summary>
protected void SendServiceFault(uint requestId, ServiceResult fault)
{
Utils.LogTrace("ChannelId {0}: Request {1}: SendServiceFault={2}", ChannelId, requestId, fault.StatusCode);
BufferCollection chunksToSend = null;
try
{
// construct fault.
ServiceFault response = new ServiceFault();
response.ResponseHeader.ServiceResult = fault.Code;
StringTable stringTable = new StringTable();
response.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo(
fault,
DiagnosticsMasks.NoInnerStatus,
true,
stringTable);
response.ResponseHeader.StringTable = stringTable.ToArray();
// serialize fault.
byte[] buffer = BinaryEncoder.EncodeMessage(response, Quotas.MessageContext);
// secure message.
chunksToSend = WriteAsymmetricMessage(
TcpMessageType.Open,
requestId,
ServerCertificate,
ClientCertificate,
new ArraySegment<byte>(buffer, 0, buffer.Length));
// write the message to the server.
BeginWriteMessage(chunksToSend, null);
chunksToSend = null;
}
catch (Exception e)
{
if (chunksToSend != null)
{
chunksToSend.Release(BufferManager, "SendServiceFault");
}
ForceChannelFault(ServiceResult.Create(e, StatusCodes.BadTcpInternalError, "Unexpected error sending a service fault."));
}
}
/// <summary>
/// Handles a reconnect request.
/// </summary>
public virtual void Reconnect(IMessageSocket socket, uint requestId, uint sequenceNumber, X509Certificate2 clientCertificate, ChannelToken token, OpenSecureChannelRequest request)
{
throw new NotImplementedException();
}
/// <summary>
/// Set the flag if a response is required for the use case of reverse connect.
/// </summary>
protected void SetResponseRequired(bool responseRequired)
{
m_responseRequired = responseRequired;
}
#endregion
#region Connect/Reconnect Sequence
/// <summary>
/// Returns a new token id.
/// </summary>
protected uint GetNewTokenId()
{
return Utils.IncrementIdentifier(ref m_lastTokenId);
}
#endregion
#region Protected Functions
/// <summary>
/// The channel request event handler.
/// </summary>
protected TcpChannelRequestEventHandler RequestReceived => m_requestReceived;
/// <summary>
/// The report open secure channel audit event handler.
/// </summary>
protected ReportAuditOpenSecureChannelEventHandler ReportAuditOpenSecureChannelEvent => m_reportAuditOpenSecureChannelEvent;
/// <summary>
/// The report close secure channel audit event handler.
/// </summary>
protected ReportAuditCloseSecureChannelEventHandler ReportAuditCloseSecureChannelEvent => m_reportAuditCloseSecureChannelEvent;
/// <summary>
/// The report certificate audit event handler.
/// </summary>
protected ReportAuditCertificateEventHandler ReportAuditCertificateEvent => m_reportAuditCertificateEvent;
#endregion
#region Private Fields
private ITcpChannelListener m_listener;
private bool m_responseRequired;
private TcpChannelRequestEventHandler m_requestReceived;
private ReportAuditOpenSecureChannelEventHandler m_reportAuditOpenSecureChannelEvent;
private ReportAuditCloseSecureChannelEventHandler m_reportAuditCloseSecureChannelEvent;
private ReportAuditCertificateEventHandler m_reportAuditCertificateEvent;
private long m_lastTokenId;
#endregion
}
/// <summary>
/// Used to report an incoming request.
/// </summary>
public delegate void TcpChannelRequestEventHandler(TcpListenerChannel channel, uint requestId, IServiceRequest request);
/// <summary>
/// Used to report the status of the channel.
/// </summary>
public delegate void TcpChannelStatusEventHandler(TcpServerChannel channel, ServiceResult status, bool closed);
/// <summary>
/// Used to report an open secure channel audit event.
/// </summary>
public delegate void ReportAuditOpenSecureChannelEventHandler(TcpServerChannel channel, OpenSecureChannelRequest request, X509Certificate2 clientCertificate, Exception exception);
/// <summary>
/// Used to report a close secure channel audit event
/// </summary>
public delegate void ReportAuditCloseSecureChannelEventHandler(TcpServerChannel channel, Exception exception);
/// <summary>
/// Used to report an open secure channel audit event.
/// </summary>
public delegate void ReportAuditCertificateEventHandler(X509Certificate2 clientCertificate, Exception exception);
}