-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathSession.cs
More file actions
5347 lines (4770 loc) · 213 KB
/
Session.cs
File metadata and controls
5347 lines (4770 loc) · 213 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
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ========================================================================
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Extensions.Logging;
using Opc.Ua.Bindings;
namespace Opc.Ua.Client
{
/// <summary>
/// Manages a session with a server.
/// </summary>
public partial class Session : SessionClientBatched, ISession,
ISnapshotRestore<SessionState>, ISnapshotRestore<SessionConfiguration>
{
private const int kReconnectTimeout = 15000;
private const int kMinPublishRequestCountMax = 100;
private const int kMaxPublishRequestCountMax = ushort.MaxValue;
private const int kDefaultPublishRequestCount = 1;
private const int kPublishRequestSequenceNumberOutOfOrderThreshold = 10;
private const int kPublishRequestSequenceNumberOutdatedThreshold = 100;
/// <summary>
/// Constructs a new instance of the <see cref="Session"/> class.
/// </summary>
/// <param name="channel">The channel used to communicate with the server.</param>
/// <param name="configuration">The configuration for the client application.</param>
/// <param name="endpoint">The endpoint use to initialize the channel.</param>
[Obsolete("Use constructor with ITransportChannel instead of ISessionChannel.")]
public Session(
ISessionChannel channel,
ApplicationConfiguration configuration,
ConfiguredEndpoint endpoint)
: this(
channel is ITransportChannel transportChannel ?
transportChannel :
throw new ArgumentException("not a transport channel"),
configuration,
endpoint)
{
}
/// <summary>
/// Constructs a new instance of the <see cref="ISession"/> class.
/// </summary>
/// <param name="channel">The channel used to communicate with the server.</param>
/// <param name="configuration">The configuration for the client application.</param>
/// <param name="endpoint">The endpoint used to initialize the channel.</param>
/// <param name="clientCertificate">The certificate to use for the client.</param>
/// <param name="clientCertificateChain">The certificate chain of the client
/// certificate.</param>
/// <param name="availableEndpoints">The list of available endpoints returned
/// by server in GetEndpoints() response.</param>
/// <param name="discoveryProfileUris">The value of profileUris used in
/// GetEndpoints() request.</param>
/// <remarks>
/// The application configuration is used to look up the certificate if none
/// is provided. The clientCertificate must have the private key. This will
/// require that the certificate be loaded from a certicate store. Converting
/// a DER encoded blob to a X509Certificate2 will not include a private key.
/// The <i>availableEndpoints</i> and <i>discoveryProfileUris</i> parameters are
/// used to validate that the list of EndpointDescriptions returned at GetEndpoints
/// matches the list returned at CreateSession.
/// </remarks>
public Session(
ITransportChannel channel,
ApplicationConfiguration configuration,
ConfiguredEndpoint endpoint,
X509Certificate2? clientCertificate = null,
X509Certificate2Collection? clientCertificateChain = null,
EndpointDescriptionCollection? availableEndpoints = null,
StringCollection? discoveryProfileUris = null)
: this(
channel,
configuration,
endpoint,
channel.MessageContext ?? configuration.CreateMessageContext())
{
m_instanceCertificate = clientCertificate;
m_instanceCertificateChain = clientCertificateChain;
m_discoveryServerEndpoints = availableEndpoints;
m_discoveryProfileUris = discoveryProfileUris;
}
/// <summary>
/// Initializes a new instance of the <see cref="ISession"/> class.
/// </summary>
/// <param name="channel">The channel.</param>
/// <param name="template">The template session.</param>
/// <param name="copyEventHandlers">if set to <c>true</c> the event handlers are copied.</param>
public Session(ITransportChannel channel, Session template, bool copyEventHandlers)
: this(
channel,
template.m_configuration,
template.ConfiguredEndpoint,
channel.MessageContext ?? template.m_configuration.CreateMessageContext())
{
m_instanceCertificate = template.m_instanceCertificate;
m_instanceCertificateChain = template.m_instanceCertificateChain;
m_effectiveEndpoint = template.m_effectiveEndpoint;
SessionFactory = template.SessionFactory;
m_defaultSubscription = template.m_defaultSubscription;
DeleteSubscriptionsOnClose = template.DeleteSubscriptionsOnClose;
TransferSubscriptionsOnReconnect = template.TransferSubscriptionsOnReconnect;
PublishRequestCancelDelayOnCloseSession = template.PublishRequestCancelDelayOnCloseSession;
m_sessionTimeout = template.m_sessionTimeout;
m_maxRequestMessageSize = template.m_maxRequestMessageSize;
m_minPublishRequestCount = template.m_minPublishRequestCount;
m_maxPublishRequestCount = template.m_maxPublishRequestCount;
m_preferredLocales = template.PreferredLocales;
m_sessionName = template.SessionName;
Handle = template.Handle;
m_identity = template.Identity;
m_keepAliveInterval = template.KeepAliveInterval;
// Create timer for keep alive event triggering but in off state
m_keepAliveTimer = new Timer(_ => m_keepAliveEvent.Set(), this, Timeout.Infinite, Timeout.Infinite);
m_checkDomain = template.m_checkDomain;
ContinuationPointPolicy = template.ContinuationPointPolicy;
ReturnDiagnostics = template.ReturnDiagnostics;
if (template.OperationTimeout > 0)
{
OperationTimeout = template.OperationTimeout;
}
if (copyEventHandlers)
{
m_KeepAlive = template.m_KeepAlive;
m_Publish = template.m_Publish;
m_PublishError = template.m_PublishError;
m_PublishSequenceNumbersToAcknowledge = template
.m_PublishSequenceNumbersToAcknowledge;
m_SubscriptionsChanged = template.m_SubscriptionsChanged;
m_SessionClosing = template.m_SessionClosing;
m_SessionConfigurationChanged = template.m_SessionConfigurationChanged;
m_RenewUserIdentity = template.m_RenewUserIdentity;
}
foreach (Subscription subscription in template.Subscriptions)
{
AddSubscription(subscription.CloneSubscription(copyEventHandlers));
}
}
/// <summary>
/// Initializes the session.
/// </summary>
private Session(
ITransportChannel channel,
ApplicationConfiguration configuration,
ConfiguredEndpoint endpoint,
IServiceMessageContext messageContext)
: base(channel, messageContext.Telemetry)
{
if (messageContext == null)
{
throw new ArgumentNullException(nameof(messageContext));
}
m_telemetry = messageContext.Telemetry;
m_logger = m_telemetry.CreateLogger<Session>();
SessionFactory ??= new DefaultSessionFactory(m_telemetry)
{
ReturnDiagnostics = ReturnDiagnostics
};
NamespaceUris = new NamespaceTable();
ServerUris = new StringTable();
Factory = EncodeableFactory.Create();
m_keepAliveInterval = 5000;
m_minPublishRequestCount = kDefaultPublishRequestCount;
m_maxPublishRequestCount = kMaxPublishRequestCountMax;
m_sessionName = string.Empty;
DeleteSubscriptionsOnClose = true;
PublishRequestCancelDelayOnCloseSession = 5000; // 5 seconds default
ValidateClientConfiguration(configuration);
// save configuration information.
m_configuration = configuration;
m_effectiveEndpoint = m_endpoint = endpoint;
m_identity = new UserIdentity();
// update the default subscription.
DefaultSubscription.MinLifetimeInterval = (uint)m_configuration.ClientConfiguration
.MinSubscriptionLifetime;
// initialize operation limits from client configuration.
if (m_configuration.ClientConfiguration.OperationLimits != null)
{
OperationLimits clientLimits = m_configuration.ClientConfiguration.OperationLimits;
OperationLimits.MaxNodesPerRead = clientLimits.MaxNodesPerRead;
OperationLimits.MaxNodesPerHistoryReadData = clientLimits.MaxNodesPerHistoryReadData;
OperationLimits.MaxNodesPerHistoryReadEvents = clientLimits.MaxNodesPerHistoryReadEvents;
OperationLimits.MaxNodesPerWrite = clientLimits.MaxNodesPerWrite;
OperationLimits.MaxNodesPerHistoryUpdateData = clientLimits.MaxNodesPerHistoryUpdateData;
OperationLimits.MaxNodesPerHistoryUpdateEvents = clientLimits.MaxNodesPerHistoryUpdateEvents;
OperationLimits.MaxNodesPerMethodCall = clientLimits.MaxNodesPerMethodCall;
OperationLimits.MaxNodesPerBrowse = clientLimits.MaxNodesPerBrowse;
OperationLimits.MaxNodesPerRegisterNodes = clientLimits.MaxNodesPerRegisterNodes;
OperationLimits.MaxNodesPerTranslateBrowsePathsToNodeIds =
clientLimits.MaxNodesPerTranslateBrowsePathsToNodeIds;
OperationLimits.MaxNodesPerNodeManagement = clientLimits.MaxNodesPerNodeManagement;
OperationLimits.MaxMonitoredItemsPerCall = clientLimits.MaxMonitoredItemsPerCall;
}
NamespaceUris = messageContext.NamespaceUris;
ServerUris = messageContext.ServerUris;
Factory = messageContext.Factory;
// initialize the NodeCache late, it needs references to the namespaceUris
m_nodeCache = new NodeCache(new NodeCacheContext(this), m_telemetry);
// Create timer for keep alive event triggering but in off state
m_keepAliveTimer = new Timer(_ => m_keepAliveEvent.Set(), this, Timeout.Infinite, Timeout.Infinite);
// set the default preferred locales.
m_preferredLocales = new string[] { CultureInfo.CurrentCulture.Name };
// create a context to use.
m_systemContext = new SessionSystemContext(m_telemetry)
{
SystemHandle = this,
EncodeableFactory = Factory,
NamespaceUris = NamespaceUris,
ServerUris = ServerUris,
TypeTable = TypeTree,
PreferredLocales = null,
SessionId = default,
UserIdentity = null
};
}
/// <summary>
/// Check if all required configuration fields are populated.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="configuration"/> is <c>null</c>.</exception>
/// <exception cref="ServiceResultException"></exception>
private static void ValidateClientConfiguration(ApplicationConfiguration configuration)
{
string configurationField;
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
if (configuration.ClientConfiguration == null)
{
configurationField = "ClientConfiguration";
}
else if (configuration.SecurityConfiguration == null)
{
configurationField = "SecurityConfiguration";
}
else if (configuration.CertificateValidator == null)
{
configurationField = "CertificateValidator";
}
else
{
return;
}
throw ServiceResultException.ConfigurationError(
"The client configuration does not specify the configuration field {0}.",
configurationField);
}
/// <summary>
/// Validates the server nonce and security parameters of user identity.
/// </summary>
/// <exception cref="ServiceResultException"></exception>
private void ValidateServerNonce(
IUserIdentity identity,
byte[]? serverNonce,
string? securityPolicyUri,
byte[]? previousServerNonce,
MessageSecurityMode channelSecurityMode = MessageSecurityMode.None)
{
// skip validation if server nonce is not used for encryption.
if (string.IsNullOrEmpty(securityPolicyUri) ||
securityPolicyUri == SecurityPolicies.None)
{
return;
}
if (identity != null && identity.TokenType != UserTokenType.Anonymous)
{
// the server nonce should be validated if the token includes a secret.
if (!Nonce.ValidateNonce(
serverNonce,
MessageSecurityMode.SignAndEncrypt,
m_configuration.SecurityConfiguration.NonceLength))
{
if (channelSecurityMode == MessageSecurityMode.SignAndEncrypt ||
m_configuration.SecurityConfiguration.SuppressNonceValidationErrors)
{
m_logger.LogWarning(
Utils.TraceMasks.Security,
"Warning: The server nonce has not the correct length or is not random enough. " +
"The error is suppressed by user setting or because the channel is encrypted.");
}
else
{
throw ServiceResultException.Create(
StatusCodes.BadNonceInvalid,
"The server nonce has not the correct length or is not random enough.");
}
}
// check that new nonce is different from the previously returned server nonce.
if (previousServerNonce != null &&
Nonce.CompareNonce(serverNonce, previousServerNonce))
{
if (channelSecurityMode == MessageSecurityMode.SignAndEncrypt ||
m_configuration.SecurityConfiguration.SuppressNonceValidationErrors)
{
m_logger.LogWarning(
Utils.TraceMasks.Security,
"Warning: The Server nonce is equal with previously returned nonce. " +
"The error is suppressed by user setting or because the channel is encrypted.");
}
else
{
throw ServiceResultException.Create(
StatusCodes.BadNonceInvalid,
"Server nonce is equal with previously returned nonce.");
}
}
}
}
/// <summary>
/// Closes the session and the underlying channel.
/// </summary>
protected override void Dispose(bool disposing)
{
if (Disposed && disposing)
{
return;
}
if (disposing)
{
StopKeepAliveTimerAsync().AsTask().GetAwaiter().GetResult();
Utils.SilentDispose(m_defaultSubscription);
Utils.SilentDispose(m_nodeCache);
List<Subscription>? subscriptions;
lock (m_lock)
{
subscriptions = [.. m_subscriptions];
m_subscriptions.Clear();
}
foreach (Subscription subscription in subscriptions)
{
Utils.SilentDispose(subscription);
}
subscriptions.Clear();
}
base.Dispose(disposing);
if (disposing)
{
m_keepAliveTimer.Dispose();
// suppress spurious events
m_KeepAlive = null;
m_Publish = null;
m_PublishError = null;
m_PublishSequenceNumbersToAcknowledge = null;
m_SubscriptionsChanged = null;
m_SessionClosing = null;
m_SessionConfigurationChanged = null;
Debug.Assert(Disposed);
}
}
/// <summary>
/// Raised when a keep alive arrives from the server or an error is detected.
/// </summary>
/// <remarks>
/// Once a session is created a timer will periodically read the server state and current time.
/// If this read operation succeeds this event will be raised each time the keep alive period elapses.
/// If an error is detected (KeepAliveStopped == true) then this event will be raised as well.
/// </remarks>
public event KeepAliveEventHandler KeepAlive
{
add => m_KeepAlive += value;
remove => m_KeepAlive -= value;
}
/// <summary>
/// Raised when a notification message arrives in a publish response.
/// </summary>
/// <remarks>
/// All publish requests are managed by the Session object. When a response arrives it is
/// validated and passed to the appropriate Subscription object and this event is raised.
/// </remarks>
public event NotificationEventHandler Notification
{
add => m_Publish += value;
remove => m_Publish -= value;
}
/// <summary>
/// Raised when an exception occurs while processing a publish response.
/// </summary>
/// <remarks>
/// Exceptions in a publish response are not necessarily fatal and the Session will
/// attempt to recover by issuing Republish requests if missing messages are detected.
/// That said, timeout errors may be a symptom of a OperationTimeout that is too short
/// when compared to the shortest PublishingInterval/KeepAliveCount amount the current
/// Subscriptions. The OperationTimeout should be twice the minimum value for
/// PublishingInterval*KeepAliveCount.
/// </remarks>
public event PublishErrorEventHandler PublishError
{
add => m_PublishError += value;
remove => m_PublishError -= value;
}
/// <inheritdoc/>
public event PublishSequenceNumbersToAcknowledgeEventHandler PublishSequenceNumbersToAcknowledge
{
add => m_PublishSequenceNumbersToAcknowledge += value;
remove => m_PublishSequenceNumbersToAcknowledge -= value;
}
/// <summary>
/// Raised when a subscription is added or removed
/// </summary>
public event EventHandler SubscriptionsChanged
{
add => m_SubscriptionsChanged += value;
remove => m_SubscriptionsChanged -= value;
}
/// <summary>
/// Raised to indicate the session is closing.
/// </summary>
public event EventHandler SessionClosing
{
add => m_SessionClosing += value;
remove => m_SessionClosing -= value;
}
/// <inheritdoc/>
public event EventHandler SessionConfigurationChanged
{
add => m_SessionConfigurationChanged += value;
remove => m_SessionConfigurationChanged -= value;
}
/// <summary>
/// A session factory that was used to create the session.
/// </summary>
public ISessionFactory SessionFactory { get; set; }
/// <summary>
/// Gets the endpoint used to connect to the server.
/// </summary>
public ConfiguredEndpoint ConfiguredEndpoint => m_endpoint;
/// <summary>
/// Gets the name assigned to the session.
/// </summary>
public string SessionName => m_sessionName;
/// <summary>
/// Whether the session is reconnecting
/// </summary>
public bool Reconnecting { get; private set; }
/// <summary>
/// Whether the session is closing
/// </summary>
public bool Closing { get; private set; }
/// <summary>
/// Gets the period for wich the server will maintain the session if
/// there is no communication from the client.
/// </summary>
public double SessionTimeout => m_sessionTimeout;
/// <summary>
/// Gets the local handle assigned to the session.
/// </summary>
public object? Handle { get; set; }
/// <summary>
/// Gets the user identity currently used for the session.
/// </summary>
public IUserIdentity Identity => m_identity;
/// <summary>
/// Gets a list of user identities that can be used to connect to the server.
/// </summary>
public IEnumerable<IUserIdentity> IdentityHistory => m_identityHistory;
/// <summary>
/// Gets the table of namespace uris known to the server.
/// </summary>
public NamespaceTable NamespaceUris { get; private set; }
/// <summary>
/// Gets the table of remote server uris known to the server.
/// </summary>
public StringTable ServerUris { get; private set; }
/// <summary>
/// Gets the system context for use with the session.
/// </summary>
public ISystemContext SystemContext => m_systemContext;
/// <summary>
/// Gets the factory used to create encodeable objects that the server understands.
/// </summary>
public IEncodeableFactory Factory { get; private set; }
/// <summary>
/// Gets the cache of the server's type tree.
/// </summary>
public ITypeTable TypeTree => m_nodeCache.TypeTree;
/// <summary>
/// Gets the cache of nodes fetched from the server.
/// </summary>
public INodeCache NodeCache => m_nodeCache;
/// <summary>
/// Gets the context to use for filter operations.
/// </summary>
public IFilterContext FilterContext
=> new FilterContext(NamespaceUris, m_nodeCache.TypeTree, m_preferredLocales, m_telemetry);
/// <summary>
/// Gets the locales that the server should use when returning localized text.
/// </summary>
public StringCollection PreferredLocales => m_preferredLocales;
/// <summary>
/// Gets the subscriptions owned by the session.
/// </summary>
public IEnumerable<Subscription> Subscriptions
{
get
{
lock (m_lock)
{
return [.. m_subscriptions];
}
}
}
/// <summary>
/// Gets the number of subscriptions owned by the session.
/// </summary>
public int SubscriptionCount
{
get
{
lock (m_lock)
{
return m_subscriptions.Count;
}
}
}
/// <summary>
/// If the subscriptions are deleted when a session is closed.
/// </summary>
/// <remarks>
/// Default <c>true</c>, set to <c>false</c> if subscriptions need to
/// be transferred or for durable subscriptions.
/// </remarks>
public bool DeleteSubscriptionsOnClose { get; set; }
/// <inheritdoc/>
public int PublishRequestCancelDelayOnCloseSession { get; set; }
/// <summary>
/// If the subscriptions are transferred when a session is reconnected.
/// </summary>
/// <remarks>
/// Default <c>false</c>, set to <c>true</c> if subscriptions should
/// be transferred after reconnect. Service must be supported by server.
/// </remarks>
public bool TransferSubscriptionsOnReconnect { get; set; }
/// <summary>
/// Whether the endpoint Url domain is checked in the certificate.
/// </summary>
public bool CheckDomain => m_checkDomain;
/// <summary>
/// Gets or Sets the default subscription for the session.
/// </summary>
public Subscription DefaultSubscription
{
get => m_defaultSubscription ??= CreateSubscription(new SubscriptionOptions
{
DisplayName = "Subscription",
PublishingInterval = 1000,
KeepAliveCount = 10,
LifetimeCount = 1000,
Priority = 255,
PublishingEnabled = true,
MinLifetimeInterval = (uint)m_configuration.ClientConfiguration
.MinSubscriptionLifetime
});
set
{
Utils.SilentDispose(m_defaultSubscription);
m_defaultSubscription = value;
}
}
/// <summary>
/// Gets or Sets how frequently the server is pinged to see if communication is still working.
/// </summary>
/// <remarks>
/// This interval controls how much time elaspes before a communication error is detected.
/// If everything is ok the KeepAlive event will be raised each time this period elapses.
/// </remarks>
public int KeepAliveInterval
{
get => m_keepAliveInterval;
set
{
m_keepAliveInterval = value;
ResetKeepAliveTimer();
}
}
/// <summary>
/// Returns true if the session is not receiving keep alives.
/// </summary>
/// <remarks>
/// Set to true if the server does not respond for the
/// KeepAliveInterval * 1 (KeepAliveIntervalFactor) + 1 Second (KeepAliveGuardBand) *
/// To change the sensitivity of the keep alive check, set the
/// <see cref="m_keepAliveIntervalFactor"/> / <see cref="m_keepAliveGuardBand"/> fields.
/// or if another error was reported.
/// Set to false is communication is ok or recovered.
/// </remarks>
public bool KeepAliveStopped
{
get
{
StatusCode lastKeepAliveErrorStatusCode = m_lastKeepAliveErrorStatusCode;
if (StatusCode.IsGood(lastKeepAliveErrorStatusCode) ||
lastKeepAliveErrorStatusCode == StatusCodes.BadNoCommunication)
{
int delta = HiResClock.TickCount - LastKeepAliveTickCount;
// add a guard band to allow for network lag.
return ((m_keepAliveInterval * m_keepAliveIntervalFactor) +
m_keepAliveGuardBand) <= delta;
}
// another error was reported which caused keep alive to stop.
return true;
}
}
/// <summary>
/// Gets the time of the last keep alive.
/// </summary>
public DateTime LastKeepAliveTime
{
get
{
long ticks = Interlocked.Read(ref m_lastKeepAliveTime);
return new DateTime(ticks, DateTimeKind.Utc);
}
}
/// <summary>
/// Gets the TickCount in ms of the last keep alive based on <see cref="HiResClock.TickCount"/>.
/// Independent of system time changes.
/// </summary>
public int LastKeepAliveTickCount { get; private set; }
/// <summary>
/// Gets the number of outstanding publish or keep alive requests.
/// </summary>
public int OutstandingRequestCount
{
get
{
lock (m_outstandingRequests)
{
return m_outstandingRequests.Count;
}
}
}
/// <summary>
/// Gets the number of outstanding publish or keep alive requests which appear to be missing.
/// </summary>
public int DefunctRequestCount
{
get
{
lock (m_outstandingRequests)
{
int count = 0;
for (LinkedListNode<AsyncRequestState>? ii = m_outstandingRequests.First;
ii != null;
ii = ii.Next)
{
if (ii.Value.Defunct)
{
count++;
}
}
return count;
}
}
}
/// <summary>
/// Gets the number of good outstanding publish requests.
/// </summary>
public int GoodPublishRequestCount
{
get
{
lock (m_outstandingRequests)
{
int count = 0;
for (LinkedListNode<AsyncRequestState>? ii = m_outstandingRequests.First;
ii != null;
ii = ii.Next)
{
if (!ii.Value.Defunct && ii.Value.RequestTypeId == DataTypes.PublishRequest)
{
count++;
}
}
return count;
}
}
}
/// <summary>
/// Gets and sets the minimum number of publish requests to be used in the session.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public int MinPublishRequestCount
{
get => m_minPublishRequestCount;
set
{
lock (m_lock)
{
if (value is >= kDefaultPublishRequestCount and <= kMinPublishRequestCountMax)
{
m_minPublishRequestCount = value;
}
else
{
throw new ArgumentOutOfRangeException(
nameof(MinPublishRequestCount),
$"Minimum publish request count must be between {kDefaultPublishRequestCount} and {kMinPublishRequestCountMax}.");
}
}
}
}
/// <summary>
/// Gets and sets the maximum number of publish requests to be used in the session.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public int MaxPublishRequestCount
{
get => Math.Max(m_minPublishRequestCount, m_maxPublishRequestCount);
set
{
lock (m_lock)
{
if (value is >= kDefaultPublishRequestCount and <= kMaxPublishRequestCountMax)
{
m_maxPublishRequestCount = value;
}
else
{
throw new ArgumentOutOfRangeException(
nameof(MaxPublishRequestCount),
$"Maximum publish request count must be between {kDefaultPublishRequestCount} and {kMaxPublishRequestCountMax}.");
}
}
}
}
/// <inheritdoc/>
public ContinuationPointPolicy ContinuationPointPolicy { get; set; }
= ContinuationPointPolicy.Default;
/// <inheritdoc/>
public event RenewUserIdentityEventHandler RenewUserIdentity
{
add => m_RenewUserIdentity += value;
remove => m_RenewUserIdentity -= value;
}
private event RenewUserIdentityEventHandler? m_RenewUserIdentity;
/// <inheritdoc/>
public virtual void Snapshot(out SessionState state)
{
using Activity? activity = m_telemetry.StartActivity();
Snapshot(out SessionConfiguration configuration);
// Snapshot subscription state
var subscriptionStateCollection = new SubscriptionStateCollection(SubscriptionCount);
foreach (Subscription subscription in Subscriptions)
{
subscription.Snapshot(out SubscriptionState subscriptionState);
subscriptionStateCollection.Add(subscriptionState);
}
state = new SessionState(configuration)
{
Subscriptions = subscriptionStateCollection
};
}
/// <inheritdoc/>
public virtual void Restore(SessionState state)
{
using Activity? activity = m_telemetry.StartActivity();
ThrowIfDisposed();
Restore((SessionConfiguration)state);
if (state.Subscriptions == null)
{
return;
}
foreach (SubscriptionState subscriptionState in state.Subscriptions)
{
// Restore subscription from state
Subscription subscription = CreateSubscription(subscriptionState);
subscription.Restore(subscriptionState);
AddSubscription(subscription);
}
}
/// <inheritdoc/>
public void Snapshot(out SessionConfiguration sessionConfiguration)
{
byte[]? serverNonce = m_serverNonce != null ? [.. m_serverNonce] : null;
byte[]? clientNonce = m_clientNonce != null ? [.. m_clientNonce] : null;
byte[]? serverEccEphemeralKey = m_eccServerEphemeralKey?.Data != null
? [.. m_eccServerEphemeralKey.Data]
: null;
sessionConfiguration = new SessionConfiguration
{
SessionName = SessionName,
SessionId = SessionId,
AuthenticationToken = AuthenticationToken,
Identity = Identity,
ConfiguredEndpoint = ConfiguredEndpoint,
CheckDomain = CheckDomain,
ServerNonce = serverNonce,
ClientNonce = clientNonce,
ServerEccEphemeralKey = serverEccEphemeralKey,
UserIdentityTokenPolicy = m_userTokenSecurityPolicyUri
};
}
/// <inheritdoc/>
public void Restore(SessionConfiguration sessionConfiguration)
{
ThrowIfDisposed();
byte[]? serverCertificate = m_endpoint.Description?.ServerCertificate;
m_sessionName = sessionConfiguration.SessionName ?? "SessionName";
m_serverCertificate =
serverCertificate != null
? CertificateFactory.Create(serverCertificate)
: null;
m_identity = sessionConfiguration.Identity ?? new UserIdentity();
m_checkDomain = sessionConfiguration.CheckDomain;
m_serverNonce = sessionConfiguration.ServerNonce != null
? [.. sessionConfiguration.ServerNonce]
: null;
m_clientNonce = sessionConfiguration.ClientNonce != null
? [.. sessionConfiguration.ClientNonce]
: null;
m_userTokenSecurityPolicyUri = sessionConfiguration.UserIdentityTokenPolicy;
if (sessionConfiguration.ServerEccEphemeralKey?.Length > 0)
{
string? ephemeralKeyPolicyUri = !string.IsNullOrEmpty(m_userTokenSecurityPolicyUri)
? m_userTokenSecurityPolicyUri
: m_endpoint.Description?.SecurityPolicyUri ?? SecurityPolicies.None;
SecurityPolicyInfo ephemeralKeyPolicy = SecurityPolicies.GetInfo(ephemeralKeyPolicyUri);
m_eccServerEphemeralKey = Nonce.CreateNonce(
ephemeralKeyPolicy,
sessionConfiguration.ServerEccEphemeralKey);
}
else
{
m_eccServerEphemeralKey = null;
}
lock (m_lock)
{
SessionCreated(
sessionConfiguration.SessionId,
sessionConfiguration.AuthenticationToken);
}
}
/// <inheritdoc/>
public bool ApplySessionConfiguration(SessionConfiguration sessionConfiguration)
{
if (sessionConfiguration == null)
{
throw new ArgumentNullException(nameof(sessionConfiguration));
}
Restore(sessionConfiguration);
return true;
}
/// <inheritdoc/>
public SessionConfiguration SaveSessionConfiguration(Stream? stream = null)
{
Snapshot(out SessionConfiguration sessionConfiguration);
if (stream != null)
{
DataContractSerializer serializer =
CoreUtils.CreateDataContractSerializer<SessionConfiguration>(MessageContext);
using IDisposable scope = AmbientMessageContext.SetScopedContext(MessageContext);
using var writer = XmlWriter.Create(stream, Utils.DefaultXmlWriterSettings());
serializer.WriteObject(writer, sessionConfiguration);
}
return sessionConfiguration;
}
/// <inheritdoc/>
public virtual void Save(
Stream stream,
IEnumerable<Subscription> subscriptions,
IEnumerable<Type>? knownTypes = null)
{
using Activity? activity = m_telemetry.StartActivity();
// Snapshot subscription state
var subscriptionStateCollection = new SubscriptionStateCollection();
foreach (Subscription subscription in subscriptions)
{
subscription.Snapshot(out SubscriptionState state);
subscriptionStateCollection.Add(state);
}
DataContractSerializer serializer =