-
Notifications
You must be signed in to change notification settings - Fork 956
/
Copy pathSession.cs
4925 lines (4196 loc) · 190 KB
/
Session.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
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-2020 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.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
namespace Opc.Ua.Client
{
/// <summary>
/// Manages a session with a server.
/// </summary>
public partial class Session : SessionClient, IDisposable
{
#region Constructors
/// <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>
public Session(
ISessionChannel channel,
ApplicationConfiguration configuration,
ConfiguredEndpoint endpoint)
:
this(channel as ITransportChannel, configuration, endpoint, null)
{
}
/// <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 used to initialize the channel.</param>
/// <param name="clientCertificate">The certificate to use for the client.</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,
EndpointDescriptionCollection availableEndpoints = null,
StringCollection discoveryProfileUris = null)
:
base(channel)
{
Initialize(channel, configuration, endpoint, clientCertificate);
m_discoveryServerEndpoints = availableEndpoints;
m_discoveryProfileUris = discoveryProfileUris;
}
/// <summary>
/// Initializes a new instance of the <see cref="Session"/> 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)
:
base(channel)
{
Initialize(channel, template.m_configuration, template.m_endpoint, template.m_instanceCertificate);
m_defaultSubscription = template.m_defaultSubscription;
m_deleteSubscriptionsOnClose = template.m_deleteSubscriptionsOnClose;
m_sessionTimeout = template.m_sessionTimeout;
m_maxRequestMessageSize = template.m_maxRequestMessageSize;
m_preferredLocales = template.m_preferredLocales;
m_sessionName = template.m_sessionName;
m_handle = template.m_handle;
m_identity = template.m_identity;
m_keepAliveInterval = template.m_keepAliveInterval;
m_checkDomain = template.m_checkDomain;
if (copyEventHandlers)
{
m_KeepAlive = template.m_KeepAlive;
m_Publish = template.m_Publish;
m_PublishError = template.m_PublishError;
m_SubscriptionsChanged = template.m_SubscriptionsChanged;
m_SessionClosing = template.m_SessionClosing;
}
foreach (Subscription subscription in template.Subscriptions)
{
AddSubscription(new Subscription(subscription, copyEventHandlers));
}
}
#endregion
#region Private Methods
/// <summary>
/// Initializes the channel.
/// </summary>
private void Initialize(
ITransportChannel channel,
ApplicationConfiguration configuration,
ConfiguredEndpoint endpoint,
X509Certificate2 clientCertificate)
{
Initialize();
ValidateClientConfiguration(configuration);
// save configuration information.
m_configuration = configuration;
m_endpoint = endpoint;
// update the default subscription.
m_defaultSubscription.MinLifetimeInterval = (uint)configuration.ClientConfiguration.MinSubscriptionLifetime;
if (m_endpoint.Description.SecurityPolicyUri != SecurityPolicies.None)
{
// update client certificate.
m_instanceCertificate = clientCertificate;
if (clientCertificate == null)
{
// load the application instance certificate.
if (m_configuration.SecurityConfiguration.ApplicationCertificate == null)
{
throw new ServiceResultException(
StatusCodes.BadConfigurationError,
"The client configuration does not specify an application instance certificate.");
}
m_instanceCertificate = m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true).Result;
}
// check for valid certificate.
if (m_instanceCertificate == null)
{
var cert = m_configuration.SecurityConfiguration.ApplicationCertificate;
throw ServiceResultException.Create(
StatusCodes.BadConfigurationError,
"Cannot find the application instance certificate. Store={0}, SubjectName={1}, Thumbprint={2}.",
cert.StorePath, cert.SubjectName, cert.Thumbprint);
}
// check for private key.
if (!m_instanceCertificate.HasPrivateKey)
{
throw ServiceResultException.Create(
StatusCodes.BadConfigurationError,
"No private key for the application instance certificate. Subject={0}, Thumbprint={1}.",
m_instanceCertificate.Subject,
m_instanceCertificate.Thumbprint);
}
// load certificate chain.
m_instanceCertificateChain = new X509Certificate2Collection(m_instanceCertificate);
List<CertificateIdentifier> issuers = new List<CertificateIdentifier>();
configuration.CertificateValidator.GetIssuers(m_instanceCertificate, issuers).Wait();
for (int i = 0; i < issuers.Count; i++)
{
m_instanceCertificateChain.Add(issuers[i].Certificate);
}
}
// initialize the message context.
IServiceMessageContext messageContext = channel.MessageContext;
if (messageContext != null)
{
m_namespaceUris = messageContext.NamespaceUris;
m_serverUris = messageContext.ServerUris;
m_factory = messageContext.Factory;
}
else
{
m_namespaceUris = new NamespaceTable();
m_serverUris = new StringTable();
m_factory = new EncodeableFactory(EncodeableFactory.GlobalFactory);
}
// set the default preferred locales.
m_preferredLocales = new string[] { CultureInfo.CurrentCulture.Name };
// create a context to use.
m_systemContext = new SystemContext();
m_systemContext.SystemHandle = this;
m_systemContext.EncodeableFactory = m_factory;
m_systemContext.NamespaceUris = m_namespaceUris;
m_systemContext.ServerUris = m_serverUris;
m_systemContext.TypeTable = TypeTree;
m_systemContext.PreferredLocales = null;
m_systemContext.SessionId = null;
m_systemContext.UserIdentity = null;
}
/// <summary>
/// Sets the object members to default values.
/// </summary>
private void Initialize()
{
m_sessionTimeout = 0;
m_namespaceUris = new NamespaceTable();
m_serverUris = new StringTable();
m_factory = EncodeableFactory.GlobalFactory;
m_nodeCache = new NodeCache(this);
m_configuration = null;
m_instanceCertificate = null;
m_endpoint = null;
m_subscriptions = new List<Subscription>();
m_dictionaries = new Dictionary<NodeId, DataDictionary>();
m_acknowledgementsToSend = new SubscriptionAcknowledgementCollection();
m_latestAcknowledgementsSent = new Dictionary<uint, uint>();
m_identityHistory = new List<IUserIdentity>();
m_outstandingRequests = new LinkedList<AsyncRequestState>();
m_keepAliveInterval = 50000;
m_tooManyPublishRequests = 0;
m_sessionName = "";
m_deleteSubscriptionsOnClose = true;
m_defaultSubscription = new Subscription {
DisplayName = "Subscription",
PublishingInterval = 1000,
KeepAliveCount = 10,
LifetimeCount = 1000,
Priority = 255,
PublishingEnabled = true
};
}
/// <summary>
/// Check if all required configuration fields are populated.
/// </summary>
private 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 new ServiceResultException(
StatusCodes.BadConfigurationError,
$"The client configuration does not specify the {configurationField}.");
}
/// <summary>
/// Validates the server nonce and security parameters of user identity.
/// </summary>
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 (!Utils.Nonce.ValidateNonce(serverNonce, MessageSecurityMode.SignAndEncrypt, (uint)m_configuration.SecurityConfiguration.NonceLength))
{
if (channelSecurityMode == MessageSecurityMode.SignAndEncrypt ||
m_configuration.SecurityConfiguration.SuppressNonceValidationErrors)
{
Utils.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 && Utils.CompareNonce(serverNonce, previousServerNonce))
{
if (channelSecurityMode == MessageSecurityMode.SignAndEncrypt ||
m_configuration.SecurityConfiguration.SuppressNonceValidationErrors)
{
Utils.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>
/// Dispose and stop the keep alive timer.
/// </summary>
private void DisposeKeepAliveTimer()
{
lock (SyncRoot)
{
// stop the keep alive timer.
if (m_keepAliveTimer != null)
{
Utils.SilentDispose(m_keepAliveTimer);
m_keepAliveTimer = null;
}
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Closes the session and the underlying channel.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
DisposeKeepAliveTimer();
Utils.SilentDispose(m_defaultSubscription);
m_defaultSubscription = null;
foreach (Subscription subscription in m_subscriptions)
{
Utils.SilentDispose(subscription);
}
m_subscriptions.Clear();
}
base.Dispose(disposing);
}
#endregion
#region Events
/// <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>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")]
public event KeepAliveEventHandler KeepAlive
{
add
{
lock (m_eventLock)
{
m_KeepAlive += value;
}
}
remove
{
lock (m_eventLock)
{
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>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")]
public event NotificationEventHandler Notification
{
add
{
lock (m_eventLock)
{
m_Publish += value;
}
}
remove
{
lock (m_eventLock)
{
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>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")]
public event PublishErrorEventHandler PublishError
{
add
{
lock (m_eventLock)
{
m_PublishError += value;
}
}
remove
{
lock (m_eventLock)
{
m_PublishError -= 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;
}
}
#endregion
#region Public Properties
/// <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>
/// 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 { return m_handle; }
set { m_handle = value; }
}
/// <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 => m_namespaceUris;
/// <summary>
/// Gest the table of remote server uris known to the server.
/// </summary>
public StringTable ServerUris => m_serverUris;
/// <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 => m_factory;
/// <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 FilterContext FilterContext => new FilterContext(m_namespaceUris, m_nodeCache.TypeTree, m_preferredLocales);
/// <summary>
/// Gets the locales that the server should use when returning localized text.
/// </summary>
public StringCollection PreferredLocales => m_preferredLocales;
/// <summary>
/// Gets the data type system dictionaries in use.
/// </summary>
public IReadOnlyDictionary<NodeId, DataDictionary> DataTypeSystem => m_dictionaries;
/// <summary>
/// Gets the subscriptions owned by the session.
/// </summary>
public IEnumerable<Subscription> Subscriptions
{
get
{
lock (SyncRoot)
{
return new ReadOnlyList<Subscription>(m_subscriptions);
}
}
}
/// <summary>
/// Gets the number of subscriptions owned by the session.
/// </summary>
public int SubscriptionCount
{
get
{
lock (SyncRoot)
{
return m_subscriptions.Count;
}
}
}
/// <summary>
/// If the subscriptions are deleted when a session is closed.
/// </summary>
public bool DeleteSubscriptionsOnClose
{
get { return m_deleteSubscriptionsOnClose; }
set { m_deleteSubscriptionsOnClose = value; }
}
/// <summary>
/// Gets or Sets the default subscription for the session.
/// </summary>
public Subscription DefaultSubscription
{
get { return m_defaultSubscription; }
set { 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
{
return m_keepAliveInterval;
}
set
{
m_keepAliveInterval = value;
StartKeepAliveTimer();
}
}
/// <summary>
/// Returns true if the session is not receiving keep alives.
/// </summary>
/// <remarks>
/// Set to true if the server does not respond for 2 times the KeepAliveInterval.
/// Set to false is communication recovers.
/// </remarks>
public bool KeepAliveStopped
{
get
{
lock (m_eventLock)
{
long delta = DateTime.UtcNow.Ticks - m_lastKeepAliveTime.Ticks;
// add a 1000ms guard band to allow for network lag.
return (m_keepAliveInterval * 2) * TimeSpan.TicksPerMillisecond <= delta;
}
}
}
/// <summary>
/// Gets the time of the last keep alive.
/// </summary>
public DateTime LastKeepAliveTime => m_lastKeepAliveTime;
/// <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;
}
}
}
#endregion
#region Public Static Methods
/// <summary>
/// Creates a new communication session with a server by invoking the CreateSession service
/// </summary>
/// <param name="configuration">The configuration for the client application.</param>
/// <param name="endpoint">The endpoint for the server.</param>
/// <param name="updateBeforeConnect">If set to <c>true</c> the discovery endpoint is used to update the endpoint description before connecting.</param>
/// <param name="sessionName">The name to assign to the session.</param>
/// <param name="sessionTimeout">The timeout period for the session.</param>
/// <param name="identity">The identity.</param>
/// <param name="preferredLocales">The user identity to associate with the session.</param>
/// <returns>The new session object</returns>
public static Task<Session> Create(
ApplicationConfiguration configuration,
ConfiguredEndpoint endpoint,
bool updateBeforeConnect,
string sessionName,
uint sessionTimeout,
IUserIdentity identity,
IList<string> preferredLocales)
{
return Create(configuration, endpoint, updateBeforeConnect, false, sessionName, sessionTimeout, identity, preferredLocales);
}
/// <summary>
/// Creates a new communication session with a server by invoking the CreateSession service
/// </summary>
/// <param name="configuration">The configuration for the client application.</param>
/// <param name="endpoint">The endpoint for the server.</param>
/// <param name="updateBeforeConnect">If set to <c>true</c> the discovery endpoint is used to update the endpoint description before connecting.</param>
/// <param name="checkDomain">If set to <c>true</c> then the domain in the certificate must match the endpoint used.</param>
/// <param name="sessionName">The name to assign to the session.</param>
/// <param name="sessionTimeout">The timeout period for the session.</param>
/// <param name="identity">The user identity to associate with the session.</param>
/// <param name="preferredLocales">The preferred locales.</param>
/// <returns>The new session object.</returns>
public static Task<Session> Create(
ApplicationConfiguration configuration,
ConfiguredEndpoint endpoint,
bool updateBeforeConnect,
bool checkDomain,
string sessionName,
uint sessionTimeout,
IUserIdentity identity,
IList<string> preferredLocales)
{
return Create(configuration, null, endpoint, updateBeforeConnect, checkDomain, sessionName, sessionTimeout, identity, preferredLocales);
}
/// <summary>
/// Creates a new communication session with a server using a reverse connection.
/// </summary>
/// <param name="configuration">The configuration for the client application.</param>
/// <param name="connection">The client endpoint for the reverse connect.</param>
/// <param name="endpoint">The endpoint for the server.</param>
/// <param name="updateBeforeConnect">If set to <c>true</c> the discovery endpoint is used to update the endpoint description before connecting.</param>
/// <param name="checkDomain">If set to <c>true</c> then the domain in the certificate must match the endpoint used.</param>
/// <param name="sessionName">The name to assign to the session.</param>
/// <param name="sessionTimeout">The timeout period for the session.</param>
/// <param name="identity">The user identity to associate with the session.</param>
/// <param name="preferredLocales">The preferred locales.</param>
/// <returns>The new session object.</returns>
public static async Task<Session> Create(
ApplicationConfiguration configuration,
ITransportWaitingConnection connection,
ConfiguredEndpoint endpoint,
bool updateBeforeConnect,
bool checkDomain,
string sessionName,
uint sessionTimeout,
IUserIdentity identity,
IList<string> preferredLocales)
{
endpoint.UpdateBeforeConnect = updateBeforeConnect;
EndpointDescription endpointDescription = endpoint.Description;
// create the endpoint configuration (use the application configuration to provide default values).
EndpointConfiguration endpointConfiguration = endpoint.Configuration;
if (endpointConfiguration == null)
{
endpoint.Configuration = endpointConfiguration = EndpointConfiguration.Create(configuration);
}
// create message context.
IServiceMessageContext messageContext = configuration.CreateMessageContext(true);
// update endpoint description using the discovery endpoint.
if (endpoint.UpdateBeforeConnect && connection == null)
{
endpoint.UpdateFromServer();
endpointDescription = endpoint.Description;
endpointConfiguration = endpoint.Configuration;
}
// checks the domains in the certificate.
if (checkDomain &&
endpoint.Description.ServerCertificate != null &&
endpoint.Description.ServerCertificate.Length > 0)
{
configuration.CertificateValidator?.ValidateDomains(
new X509Certificate2(endpoint.Description.ServerCertificate),
endpoint);
checkDomain = false;
}
X509Certificate2 clientCertificate = null;
X509Certificate2Collection clientCertificateChain = null;
if (endpointDescription.SecurityPolicyUri != SecurityPolicies.None)
{
clientCertificate = await LoadCertificate(configuration).ConfigureAwait(false);
clientCertificateChain = await LoadCertificateChain(configuration, clientCertificate).ConfigureAwait(false);
}
// initialize the channel which will be created with the server.
ITransportChannel channel;
if (connection != null)
{
channel = SessionChannel.CreateUaBinaryChannel(
configuration,
connection,
endpointDescription,
endpointConfiguration,
clientCertificate,
clientCertificateChain,
messageContext);
}
else
{
channel = SessionChannel.Create(
configuration,
endpointDescription,
endpointConfiguration,
clientCertificate,
clientCertificateChain,
messageContext);
}
// create the session object.
Session session = new Session(channel, configuration, endpoint, null);
// create the session.
try
{
session.Open(sessionName, sessionTimeout, identity, preferredLocales, checkDomain);
}
catch (Exception)
{
session.Dispose();
throw;
}
return session;
}
/// <summary>
/// Creates a new communication session with a server using a reverse connect manager.
/// </summary>
/// <param name="configuration">The configuration for the client application.</param>
/// <param name="reverseConnectManager">The reverse connect manager for the client connection.</param>
/// <param name="endpoint">The endpoint for the server.</param>
/// <param name="updateBeforeConnect">If set to <c>true</c> the discovery endpoint is used to update the endpoint description before connecting.</param>
/// <param name="checkDomain">If set to <c>true</c> then the domain in the certificate must match the endpoint used.</param>
/// <param name="sessionName">The name to assign to the session.</param>
/// <param name="sessionTimeout">The timeout period for the session.</param>
/// <param name="userIdentity">The user identity to associate with the session.</param>
/// <param name="preferredLocales">The preferred locales.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>The new session object.</returns>
public static async Task<Session> Create(
ApplicationConfiguration configuration,
ReverseConnectManager reverseConnectManager,
ConfiguredEndpoint endpoint,
bool updateBeforeConnect,
bool checkDomain,
string sessionName,
uint sessionTimeout,
IUserIdentity userIdentity,
IList<string> preferredLocales,
CancellationToken ct = default(CancellationToken)
)
{
if (reverseConnectManager == null)
{
return await Create(configuration, endpoint, updateBeforeConnect,
checkDomain, sessionName, sessionTimeout, userIdentity, preferredLocales).ConfigureAwait(false);
}
ITransportWaitingConnection connection = null;
do
{
connection = await reverseConnectManager.WaitForConnection(
endpoint.EndpointUrl,
endpoint.ReverseConnect?.ServerUri,
ct).ConfigureAwait(false);
if (updateBeforeConnect)
{
await endpoint.UpdateFromServerAsync(
endpoint.EndpointUrl, connection,
endpoint.Description.SecurityMode,
endpoint.Description.SecurityPolicyUri).ConfigureAwait(false);
updateBeforeConnect = false;
connection = null;
}
} while (connection == null);
return await Create(
configuration,
connection,
endpoint,
false,
checkDomain,
sessionName,
sessionTimeout,
userIdentity,
preferredLocales).ConfigureAwait(false);
}
/// <summary>
/// Recreates a session based on a specified template.
/// </summary>
/// <param name="template">The Session object to use as template</param>
/// <returns>The new session object.</returns>
public static Session Recreate(Session template)
{
var messageContext = template.m_configuration.CreateMessageContext();
messageContext.Factory = template.Factory;
// create the channel object used to connect to the server.
ITransportChannel channel = SessionChannel.Create(
template.m_configuration,
template.m_endpoint.Description,
template.m_endpoint.Configuration,
template.m_instanceCertificate,
template.m_configuration.SecurityConfiguration.SendCertificateChain ?
template.m_instanceCertificateChain : null,
messageContext);
// create the session object.
Session session = new Session(channel, template, true);
try
{
// open the session.
session.Open(
template.m_sessionName,
(uint)template.m_sessionTimeout,
template.m_identity,
template.m_preferredLocales,
template.m_checkDomain);