Files
romanett 87c35b84b6 Fix Opc.Ua.Client audit findings (security fallback, reconnect, subscriptions, redundancy, browse, files, WebApi) (#4572)
## Summary

Fixes the findings of a bug audit of `Opc.Ua.Client` and
`Opc.Ua.Client.ComplexTypes`, done on master plus #4516 (now merged).

- **Audit:** 82 findings across 12 areas, each checked against the OPC
UA specification. Final severities: 2 High, 37 Medium, 43 Low.
- **Fixes:** 76 fixed, 4 partial, 2 skipped (see [Not
fixed](#not-fixed--partial)).
- **Review:** a follow-up review of the fixes found 15 more defects in
them, all fixed here.
- **Tests:** every fix has a regression test, except a few races that
cannot be reproduced deterministically; the commit messages say which.

The finding IDs (`L<area>-<n>` for the audit, `G<n>` for the review)
appear in the commit titles.

## Behaviour and user-facing changes

### Security and endpoint selection
- **Reconnect no longer drops to weaker security (L3-1, High).** When
the server rejects the configured security policy or mode during
reconnect, `SessionReconnectHandler` no longer switches to whatever
endpoint the server advertises, None included. It only picks an endpoint
at least as strong as the configured one, judged by a locally computed
security level. The server-advertised `SecurityLevel` is not trusted. If
nothing qualifies, reconnect fails with the original error (new log
event `SessionReconnectHandler + 13`) and keeps retrying with the
original settings.
- **`CoreClientUtils.SelectEndpoint(useSecurity: true)` never returns a
SecurityMode None endpoint over opc.tcp (L9-9, High).** It now returns
`null` when no secure endpoint matches.
- When the discovery URL is `https`/`opc.https`, an HTTPS endpoint with
SecurityMode None is still accepted as a last resort, because TLS
protects it (Part 6 §7.4.1) (G17).
  - Endpoints with SecurityMode `Invalid` no longer count as secure.
- `GlobalDiscoveryServerClient` and `ServerPushConfigurationClient` now
throw `BadSecurityPolicyRejected` when no secure endpoint matches,
instead of passing `null` on. The ConsoleReferenceClient sample reports
this with a clear error.
- **No Bearer/Basic credentials over `http://` (L12-2).**
`WebApiClient.Create` and WebApi channel open/reconnect reject them with
`BadSecurityChecksFailed`. The public `WebApiClient(HttpClient, …)`
constructor also rejects them when the client's `BaseAddress` is not
https, and every send checks the address it actually goes to (covers a
`BaseAddress` set later).

### Session, keep-alive and identity
- **Faster detection of a silent server (L1-1).** The keep-alive Read is
now bounded by its `TimeoutHint` (2 × `KeepAliveInterval`), which is
what Part 4 §7.32 says the client should do. It then fails with
`BadNoCommunication`, so reconnect starts after about 2 ×
`KeepAliveInterval` instead of `OperationTimeout` (120 s by default).
- **Operations fail fast during a channel-manager recovery (L1-2, G9).**
`UpdateIdentityAsync`, `TransferSubscriptionsAsync` and
`ReactivateSubscriptionsAsync` fail with `BadSecureChannelClosed`
(retryable) instead of deadlocking. This covers the operation holding
the reconnect lock and any queued behind it.
- **Closing or disposing from a handler no longer waits on itself (L1-3,
G5, G6).**
- `Session` and `ManagedSession` Close/Dispose from a Notification
handler no longer wait 30 s for their own background drain.
- Disposing a `ManagedSession` from a keep-alive `PublishStatusChanged`
handler no longer deadlocks.
- Tasks spawned by a handler no longer count as "the handler" (the owner
marker is scoped to the work item).
- **Switching to an ECC user-token policy takes two ActivateSession
calls (L1-4, G4).** This follows Part 6 §6.8.2 (fetch the ephemeral key,
then activate).
- If the server returns no key, the switch fails with
`BadSecurityPolicyRejected`.
- If the second activation is rejected, the old identity stays on the
override policy with the key just fetched. Restoring the old key was
tried: against the reference server the next reconnect then failed to
decrypt the identity token.
- **`ManagedSession.ConfiguredEndpoint` follows failover (L2-6).** It
now reports the inner session's endpoint, so it changes after a failover
or network-path rotation.
- **An explicit identity update replaces the identity provider (L2-7).**
`ManagedSession.UpdateSessionAsync(identity)` stops the provider's
refresh loop and drops the provider for good. If the update fails, the
loop is restarted.
- **Reconnect waits for in-flight calls on a healthy channel (L2-3,
G8a).** Reconnect/failover on a healthy channel (certificate or
trust-list change, manual reconnect) waits for in-flight service calls.
The wait is bounded (max(`KeepAliveInterval`, 1 s)) only once the
channel is unhealthy (keep-alive stopped, channel not Ready), so a dead
channel no longer holds recovery for `OperationTimeout`.
- **Smaller fixes:**
- Restore reads the server certificate as a chain; this failed on macOS
(L1-5).
  - Session recovery can no longer run twice at once (L1-6).
  - Identity expiries more than 49.7 days out no longer throw (L2-2).
- Keep-alive reconnect suppression is recalculated on a lease swap
(L2-4).

### Reconnect state machine and reverse connect
- **⚠ `MaxTotalReconnectTime = 0` now means "no time limit" (L3-7).
Reviewer decision needed.** Before, 0 disabled reconnect entirely.
Negative values other than `Timeout.InfiniteTimeSpan` now throw
`ArgumentOutOfRangeException` when the state machine is constructed;
before, they crashed the worker. The XML docs of
`ReconnectPolicy`/`ReconnectPolicyOptions` are updated. If 0 should keep
meaning "no reconnect", this is a one-line revert.
- **A close racing the end of the reconnect budget is no longer lost
(L3-4).** It goes through the normal close instead of switching to
failover.
- **The "reconnect worker" marker covers one step only (L2-1).** It
lasts for a single connect/reconnect/failover/close step. Keep-alive,
publish and identity loops started in a step no longer count as the
worker afterwards.
- **Reverse-connect strategies `Undefined` and `Any` alone are removed
after the first callback (L8-1).** This matches the documentation;
before, they behaved like `Always`.
- **`AddEndpoint` for a URL that is already added disposes the replaced
listener (L8-2).**

### Service calls
- **Batched calls clean up after a failed later batch (L3-2).** When a
later batch of
`Browse`/`BrowseNext`/`HistoryRead`/`CreateMonitoredItems` fails, the
continuation points and monitored items created by earlier batches are
released or deleted before the exception is rethrown. This adds one
request. `AddNodes`/`RegisterNodes` are not undone.
- **Batched diagnostic infos point at the right strings (L3-3).** The
string-table indexes are rebased when diagnostics are padded.
- **`ReadBytesAsync` rejects oversized responses (L3-5).** It throws
`BadUnknownResponse` when the server returns more bytes than requested,
and `BadEncodingLimitsExceeded` beyond `int` range.
- **`ReadByteStringInChunksAsync` handles an unknown server limit
(L3-6).** When the server's `MaxByteStringLength` is 0 (absent) or
larger than `int`, it falls back to the client's
`MessageContext.MaxByteStringLength`. It throws only when both are
unknown.

### Browse and NodeCache
- **Empty browse pages with a continuation point are followed (L9-1,
L9-4, L9-5, G16).** Part 4 §5.9.2.1 allows a server to return an empty
page with a continuation point, so browsing keeps following it. After 10
consecutive empty rounds it gives up with `BadNoData` and releases the
continuation point.
- `BrowseAsync(NodeId)` now throws instead of silently returning a
truncated list.
  - `BrowseStreamAsync` yields a `BadNoData` result for that node.
- The same cap, through one shared helper, now also protects
`RoleManagementClient.ListRolesAsync` and the FileSystem
enumerate/empty-check loops.
- **Continuation points are released on failure (L9-3).**
`BrowseAsync(NodeId)` releases them on any exception, and
`BrowseStreamAsync` releases all points of the current page when the
consumer stops early.
- **NodeCache lookups propagate cancellation (L9-6, L9-8).**
`FindAsync`, `IsKnownAsync`, `FetchNodeAsync`,
`FindReferenceTypeNameAsync`, the reference-table fill and the
type-hierarchy search now let `OperationCanceledException` through.
Before, a cancelled lookup looked like "node does not exist".
- **A NodeClass mismatch fails only that node (L9-7).** It returns
`BadNodeClassInvalid` for that node instead of throwing
`KeyNotFoundException` for the whole batch.
- **Smaller fixes:**
- `MaxNodesPerBrowse` ≥ 2^31 no longer breaks the managed browse (L9-2).
  - Null discovery URLs are skipped (L9-10).
  - `ModelChangeTracker` no longer cancels a joined start (L9-11).
- **Log changes:** `BrowserContinuationPointExistsButBrowse` (Browser +
0) was removed, and `BrowserServerReturnedEmptyReferencesBut` now
includes the round count.

### Subscriptions (default engine)
- **Recovery after a transfer delivers each message exactly once (L5-1,
G22).** Messages already dispatched are acknowledged instead of
republished and delivered again. Messages whose earlier republish failed
are now republished and delivered, with the Republish flag and after
newer messages, instead of being acknowledged and lost.
- **A keep-alive that proves a gap triggers republish at once (L5-5,
G23).** The dedup mark moves only past messages that were actually
recovered, so a failed republish is retried by the next data message.
- **Item changes that fail are retried with backoff (L5-3).** They are
retried on the next apply pass after the state manager's 250 ms–5 s
backoff, instead of six times back to back. The six attempts now span
about 13 s.
- **Extreme revised intervals no longer throw (L5-4, L6-1).** Very large
or NaN intervals and counts revised by the server are capped (NaN falls
back to the requested value). Before, the overflow could stop every
publish worker.
- **`SetTriggeringAsync` from a callback no longer hangs (L5-7, G21).**
While the subscription is deleted, recreated or disposed, it returns
`BadOperationAbandoned`. A cancelled reset no longer makes later calls
fail.
- **Publish responses for unknown subscription ids (L6-3, L6-4, G20).**
The client no longer re-sends acknowledgements the server already
processed. An unknown id seen while a creation is pending is left alone
instead of being deleted.
- **Smaller fixes:**
- A null and an empty `IndexRange` are treated as equal, and restored
snapshots use `null` (L5-6).
  - A failed partition attach during restore is rolled back (L6-2).
- `StreamingSubscription` throws `ObjectDisposedException` after dispose
(L6-6).

### Subscriptions (classic `Subscription`)
- **Republish no longer abandons other missing messages (L7-1).** A
Republish response no longer overwrites `AvailableSequenceNumbers`, so
other missing messages are not given up while the server still holds
them.
- **Late copies are no longer delivered twice (L7-2).** Copies of
already-processed sequence numbers are ignored, and creating a new
server subscription resets the sequence state.
- **Disposing from a keep-alive handler no longer deadlocks (L7-3).**
`Dispose()` from a keep-alive `PublishStatusChanged` handler can return
while that callback is still finishing.
- **Transfer of a restored subscription (L7-4, G27).**
  - It succeeds even when some saved items were never created.
- The server subscription is deleted only when this session's own
TransferSubscriptions just moved it and adoption failed definitively
(item count mismatch or a non-transient status). Transient errors and
`ReactivateSubscriptionsAsync` never delete it.
  - The public `Subscription.TransferAsync` never deletes.
- **Smaller fixes:**
  - Cloned items keep their triggering links (L7-5).
  - `CreateAsync` clears stale server ids (L7-6).
- A `Good_SubscriptionTransferred` for the client's own transfer is
ignored (L7-7).
- An item removed while its create is in flight is deleted afterwards
(L7-8).
- The publish timeout for very long keep-alives no longer overflows
(L7-9).
  - A negative `MaxMessageCount` is handled (L7-10).
  - `LastMessage` tolerates a wrong notification type (L7-11).
  - Pending acks exactly 2^31 away no longer throw (L4-1).
- **Log changes:** new log events `Subscription + 68..70`.

### Redundancy
- **Warm/Hot demotion (L4-2, G1, G3).**
- Without token reuse, the demoted leader closes its session and
reconnects as a fresh standby.
- With token reuse, it abandons the shared server session locally,
without CloseSession, so the new leader can reactivate it and keep its
subscriptions. This uses the new internal methods
`ManagedSession.AbandonServerSessionAsync` and
`Session.AbandonServerSession`.
- `RoleChanged(false)` is now raised before the standby connect and no
longer depends on it, so `CurrentSession` can briefly be `null`.
- Exceptions from `RoleChanged` handlers are logged and do not stop the
teardown.
- **Promotion (L4-3, G2).** A promoted standby that adopts the leader's
session first closes its own server session. A retried promotion keeps
the session it already adopted.
- **Client failover takeover (L4-4, partial).** Subscriptions the backup
prepared in advance (not yet created, `TransferId` set to the active
client's id) are moved through the session's own transfer and keep
publishing. `docs/HighAvailability.md` is updated.
- **`ShouldFailover` through the interface (L4-6).** Calling it through
`IServerRedundancyHandler` no longer fails over away from a server that
is still Healthy.

### Fluent / dependency injection
- **Shared DI session (L10-5).** The shared session from `AddClient` is
reconnected after a caller disposes it, and is disposed with the
container. After that the connect delegate throws
`ObjectDisposedException`.
- **New public API:
`ManagedSessionBuilder.WithServerRedundancyOptions(ServerRedundancyOptions)`
(L10-6).** This is additive. The `Session.ServerRedundancy` options are
now actually applied.
- **`AddDiscoveryAndConnect` rewrites the advertised address (L10-7).**
It replaces the host and port the server advertises with those of the
discovery URL (Part 4 §5.6.2.1, NAT/containers), and prefers endpoints
with the same scheme.

### State machines and role management
- **`GetSubStateMachineAsync` returns the instance's own sub-state
machine (L10-1).** Before, it returned the type's placeholder.
- **`WaitForStateAsync` reports failures with OPC UA status codes
(L10-2).** It throws `BadNotFound` when `CurrentState/Id` cannot be
resolved, and `BadInvalidState` when observation ends without reaching
the state. Before, both surfaced as `OperationCanceledException`.
- **`RoleManagementClient.ListRolesAsync` pages correctly (L10-3).** It
follows continuation points, releases them on any failure, and throws on
a Bad browse status instead of returning an empty list.
- **Role properties are read into the right fields (L10-4).** Properties
whose namespace cannot be resolved are skipped instead of shifting the
other values.

### File system, temporary files and alias names
- **Path escaping (L11-8, G12).**
- Path segments escape `:` and `/` with `&`, and `&` itself as `&&`
before those characters or at the end of a name.
- `Format` and `Parse` round-trip all names. Typed input ending in `&/`
now reads the slash as part of the name.
- A segment without a namespace prefix also matches a namespace-0 child
when nothing matches in the parent's namespace.
- **Stale path cache (L11-1).** When a cached lookup fails,
`GetInfoAsync` retries once from the server. `ExistsAsync` and
`GetFileAsync` report "not found" instead of throwing.
- **`GenerateFileForReadAsync` waits for the file (L11-2).** It waits
until the file-generation state machine reaches ReadTransfer (`Idle`
counts as not started yet), and throws `IOException` if it reports
Error. The wait is bounded only by the caller's token.
- **Non-recursive delete refuses hidden children (L11-3).** It refuses
when the directory holds children that the subtype options hide from
enumeration. Before, the server deleted them all.
- **Alias names (L11-5, L11-6, L11-7).**
- `BadMethodInvalid` maps to `NotSupportedException` for all alias
calls, so `UseVerbose` falls back to `FindAlias`.
  - A duplicate alias name resolves to all its targets.
- If the refresh strategy fails to start, the resolver logs a warning
and keeps working without automatic invalidation. New log event block
`AliasNameResolver = 560`.
- **Null profile entries (L11-4).** Null `ServerProfileArray` entries no
longer crash `GetConformanceInfoAsync`.

### WebApi transport
- **Failures come back as `ServiceResultException` (L12-1).**
  - A timeout becomes `BadRequestTimeout`.
- HTTP 429/503 becomes `BadServerTooBusy` with the Retry-After hint, on
every target framework. `WebApiClient` checks the status itself (reusing
`HttpsTransportChannel.CreateServerTooBusyException`), so callers of
`WebApiClient` also get a `ServiceResultException` instead of an
`HttpRequestException` for these two statuses (G15).
  - An IO error becomes `BadNotConnected`.
- **Timeouts (L12-1, G14).**
- `OperationTimeout` applies to each request. When `RequestTimeout` is
unset, HttpClient's 100 s default no longer cuts off long Publish
requests.
- The GetEndpoints call at open is bounded by `OperationTimeout`, and
cancelling the open now throws.
- **Core change:** `HttpsTransportChannel.MapRequestFailure` went from
private to internal so the WebApi channel can reuse it.

### ComplexTypes
- **Out-of-range union selector (L12-3).** A union whose SwitchField is
larger than its field count now fails with `BadDecodingError` when
decoded and `BadEncodingError` when encoded (Part 6 §5.2.8).
- **Verbose JSON unions (L12-4).** They now decode their selected field
instead of `null`.

## Not fixed / partial
- **L2-5 (skipped):** an identity provider combined with a
caller-supplied reverse connection still can't connect to an
undiscovered endpoint. Fixing it means choosing the identity after
CreateSession, a design change.
- **L4-5 (skipped):** the one-time KeyCredential token needs a fresh
token on each reactivation. Today reactivation fails and the client
falls back to a new session.
- **L4-4 (partial):** only subscriptions the backup prepared in advance
survive a takeover.
- **L3-2 (partial):** `AddNodes`/`RegisterNodes` batches are not rolled
back.
- **L2-3 (partial):** service calls still hold the session lock for
their whole round trip.
- **Known from the review, not fixed here:**
  - G7: the batch cleanup request can't be cancelled.
- G11: the DI session's close at host shutdown never reaches the server,
and a closed session keeps being handed out.
- G13: a file renamed by another client is still found under its old
path.
  - G25: a clone-based transfer doesn't mark the original subscriptions.
  - G27b: the transfer item check matches by count, not by ID.
- **Outside this PR:** the reference server ignores `ECDHPolicyUri` on
ActivateSession (`SessionSecurityPolicyHelper`), which breaks Part 6
§6.8.2. As a result, the L1-4 two-step ECC switch ends in
`BadSecurityPolicyRejected` against our own server.

## Testing
All suites on net10.0, on the branch before the master merge. Every
suite had 0 failures:

| Suite | Passed | Skipped |
|---|---|---|
| Opc.Ua.Client.Tests | 2698 | 0 |
| Opc.Ua.Redundancy.Client.Tests | 134 | 0 |
| Opc.Ua.Subscriptions.Classic.Tests | 57 | 0 |
| Opc.Ua.Bindings.Https.WebApi.Tests | 385 | 0 |
| Opc.Ua.Sessions.Tests | 782 | 379 |
| Opc.Ua.Subscriptions.Tests | 640 | 6 |
| Opc.Ua.Client.ComplexTypes.Tests | 2858 | 0 |

After merging current master (net10.0), every suite had 0 failures
except one, a flaky new test fixed in 9f52952b2:

| Suite | Passed | Skipped | Failed |
|---|---|---|---|
| Opc.Ua.Client.Tests | 2719 | 0 | 1 (the flaky test) |
| Opc.Ua.Redundancy.Client.Tests | 134 | 0 | 0 |
| Opc.Ua.Client.ComplexTypes.Tests | 2858 | 0 | 0 |
| Opc.Ua.Subscriptions.Classic.Tests | 57 | 0 | 0 |
| Opc.Ua.Bindings.Https.WebApi.Tests | 397 | 0 | 0 |
| Opc.Ua.Sessions.Tests | 790 | 379 | 0 |
| Opc.Ua.Subscriptions.Tests | 640 | 6 | 0 |

The touched test projects also build on net48 with 0 warnings.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>
Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
2026-09-29 09:34:03 +00:00

589 lines
23 KiB
C#

/* ========================================================================
* 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.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Identity;
using Opc.Ua.Security.Certificates;
using Quickstarts.ConsoleReferenceClient;
namespace Quickstarts
{
/// <summary>
/// OPC UA Client with examples of basic functionality.
/// </summary>
public class UAClient : IUAClient, IDisposable
{
/// <summary>
/// Initializes a new instance of the UAClient class.
/// </summary>
public UAClient(
ApplicationConfiguration configuration,
ITelemetryContext telemetry,
Action<Array, Array>? validateResponse)
: this(
configuration,
null,
telemetry,
validateResponse)
{
}
/// <summary>
/// Initializes a new instance of the UAClient class for reverse connections.
/// </summary>
public UAClient(
ApplicationConfiguration configuration,
ReverseConnectManager? reverseConnectManager,
ITelemetryContext telemetry,
Action<Array, Array>? validateResponse)
{
ValidateResponse = validateResponse;
m_logger = telemetry.CreateLogger<UAClient>();
m_telemetry = telemetry;
m_configuration = configuration;
// Modern global accept hook on ICertificateManager — fires for
// every certificate validation done via this manager.
m_configuration.CertificateManager.AcceptError = AcceptCertificate;
m_reverseConnectManager = reverseConnectManager;
}
/// <inheritdoc/>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Overridable Dispose pattern implementation.
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (m_disposed)
{
return;
}
if (disposing)
{
m_reconnectHandler?.Dispose();
Session?.Dispose();
m_configuration.CertificateManager.AcceptError = null;
}
m_disposed = true;
}
/// <summary>
/// Action used
/// </summary>
internal Action<Array, Array>? ValidateResponse { get; }
/// <summary>
/// Gets the client session.
/// </summary>
/// <remarks>
/// Initialized to <c>null!</c> as late-init: the value is assigned by
/// <see cref="ConnectAsync"/> before any caller observes it, and is
/// transiently set to <c>null!</c> during reconnect/dispose. The
/// non-nullable type matches the <see cref="IUAClient"/> contract.
/// </remarks>
public ISession Session { get; private set; } = null!;
/// <summary>
/// The session keepalive interval to be used in ms.
/// </summary>
public int KeepAliveInterval { get; set; } = 5000;
/// <summary>
/// The reconnect period to be used in ms.
/// </summary>
public int ReconnectPeriod { get; set; } = 1000;
/// <summary>
/// The reconnect period exponential backoff to be used in ms.
/// </summary>
public int ReconnectPeriodExponentialBackoff { get; set; } = 15000;
/// <summary>
/// The session lifetime.
/// </summary>
public uint SessionLifeTime { get; set; } = 60 * 1000;
/// <summary>
/// The user identity provider to use to connect to the server.
/// </summary>
public IClientIdentityProvider IdentityProvider { get; set; } = new AnonymousIdentityProvider();
/// <summary>
/// Auto accept untrusted certificates.
/// </summary>
public bool AutoAccept { get; set; }
/// <summary>
/// The file to use for log output.
/// </summary>
public string? LogFile { get; set; }
/// <summary>
/// Do a Durable Subscription Transfer
/// </summary>
public async Task<bool> DurableSubscriptionTransferAsync(
string serverUrl,
bool useSecurity = true,
CancellationToken ct = default)
{
bool success = false;
SubscriptionCollection subscriptions = [.. Session.Subscriptions];
// Transiently null between sessions; ConnectAsync rehydrates.
Session = null!;
if (await ConnectAsync(serverUrl, useSecurity, ct).ConfigureAwait(false) &&
subscriptions != null &&
Session != null)
{
Console.WriteLine($"Transferring {subscriptions.Count} subscriptions from old session to new session...");
success = await Session.TransferSubscriptionsAsync(
subscriptions,
true,
ct).ConfigureAwait(false);
if (success)
{
Console.WriteLine("Subscriptions transferred.");
}
}
return success;
}
/// <summary>
/// Creates a session with the UA server
/// </summary>
/// <exception cref="ObjectDisposedException"></exception>
/// <exception cref="ArgumentNullException"><paramref name="serverUrl"/> is <c>null</c>.</exception>
/// <exception cref="ServiceResultException"></exception>
public async Task<bool> ConnectAsync(
string serverUrl,
bool useSecurity = true,
CancellationToken ct = default)
{
if (m_disposed)
{
throw new ObjectDisposedException(nameof(UAClient));
}
if (serverUrl == null)
{
throw new ArgumentNullException(nameof(serverUrl));
}
try
{
if (Session != null && Session.Connected)
{
Console.WriteLine("Session already connected!");
}
else
{
ITransportWaitingConnection? connection = null;
EndpointDescription? endpointDescription = null;
if (m_reverseConnectManager != null)
{
Console.WriteLine($"Waiting for reverse connection to.... {serverUrl}");
do
{
using var cts = new CancellationTokenSource(30_000);
using var linkedCTS = CancellationTokenSource.CreateLinkedTokenSource(
ct,
cts.Token);
connection = await m_reverseConnectManager
.WaitForConnectionAsync(new Uri(serverUrl), null, linkedCTS.Token)
.ConfigureAwait(false) ??
throw new ServiceResultException(
StatusCodes.BadTimeout,
"Waiting for a reverse connection timed out.");
if (endpointDescription == null)
{
Console.WriteLine("Discover reverse connection endpoints....");
endpointDescription = await CoreClientUtils.SelectEndpointAsync(
m_configuration,
connection,
useSecurity,
m_telemetry,
ct
).ConfigureAwait(false) ??
throw NoMatchingEndpoint(useSecurity);
connection = null;
}
} while (connection == null);
}
else
{
Console.WriteLine($"Connecting to... {serverUrl}");
endpointDescription = await CoreClientUtils.SelectEndpointAsync(
m_configuration,
serverUrl,
useSecurity,
m_telemetry,
ct).ConfigureAwait(false) ??
throw NoMatchingEndpoint(useSecurity);
}
// Get the endpoint by connecting to server's discovery endpoint.
// Try to find the first endopint with security.
var endpointConfiguration = EndpointConfiguration.Create(m_configuration);
var endpoint = new ConfiguredEndpoint(
null,
endpointDescription!,
endpointConfiguration);
IUserIdentity userIdentity = await CreateUserIdentityAsync(
endpointDescription!,
ct).ConfigureAwait(false);
// Create the session factory. - we could take it as parameter or as member
var sessionFactory = new DefaultSessionFactory(m_telemetry);
// Create the session
ISession session = await sessionFactory
.CreateAsync(
m_configuration,
connection!,
endpoint,
connection == null,
false,
m_configuration.ApplicationName!,
SessionLifeTime,
userIdentity,
default,
ct)
.ConfigureAwait(false);
// Assign the created session
if (session != null && session.Connected)
{
Session = session;
// override keep alive interval
Session.KeepAliveInterval = KeepAliveInterval;
// support transfer
Session.DeleteSubscriptionsOnClose = false;
Session.TransferSubscriptionsOnReconnect = true;
// set up keep alive callback.
Session.KeepAlive += Session_KeepAlive;
// prepare a reconnect handler
m_reconnectHandler = new SessionReconnectHandler(
m_telemetry,
true,
ReconnectPeriodExponentialBackoff);
// Session created successfully.
Console.WriteLine($"New Session Created with SessionName = {Session.SessionName}");
}
}
return true;
}
catch (Exception ex)
{
// Log Error
Console.WriteLine($"Create Session Error : {ex.Message}");
return false;
}
}
/// <summary>
/// The error reported when discovery found no endpoint that satisfies
/// the security requirement (SelectEndpoint returned null).
/// </summary>
private static ServiceResultException NoMatchingEndpoint(bool useSecurity)
{
return useSecurity
? new ServiceResultException(
StatusCodes.BadSecurityPolicyRejected,
"The server offers no secure endpoint supported by this client.")
: new ServiceResultException(
StatusCodes.BadNotFound,
"The server offers no matching endpoint.");
}
private ValueTask<IUserIdentity> CreateUserIdentityAsync(
EndpointDescription endpointDescription,
CancellationToken ct)
{
return IdentityProvider.AcquireIdentityAsync(
endpointDescription,
m_configuration.CreateMessageContext(),
ct);
}
/// <summary>
/// Disconnects the session.
/// </summary>
/// <param name="leaveChannelOpen">Leaves the channel open.</param>
public async Task DisconnectAsync(bool leaveChannelOpen = false, CancellationToken ct = default)
{
try
{
if (Session != null)
{
Console.WriteLine("Disconnecting...");
lock (m_lock)
{
Session.KeepAlive -= Session_KeepAlive;
m_reconnectHandler?.Dispose();
m_reconnectHandler = null;
}
await Session.CloseAsync(!leaveChannelOpen, ct).ConfigureAwait(false);
if (leaveChannelOpen)
{
// detach the channel, so it doesn't get
// closed when the session is disposed.
#pragma warning disable CS0618 // sample legacy path
Session.DetachChannel();
#pragma warning restore CS0618
}
Session.Dispose();
// Transiently null after dispose; matches pre-NRT behavior.
Session = null!;
// Log Session Disconnected event
Console.WriteLine("Session Disconnected.");
}
else
{
Console.WriteLine("Session not created!");
}
}
catch (Exception ex)
{
// Log Error
m_logger.DisconnectError(ex);
}
}
/// <summary>
/// Handles a keep alive event from a session and triggers a reconnect if necessary.
/// </summary>
private void Session_KeepAlive(ISession session, KeepAliveEventArgs e)
{
try
{
// check for events from discarded sessions.
if (Session == null || !Session.Equals(session))
{
return;
}
// start reconnect sequence on communication error.
if (ServiceResult.IsBad(e.Status))
{
if (ReconnectPeriod <= 0)
{
m_logger.KeepAliveReconnectDisabled(e.Status);
return;
}
SessionReconnectHandler.ReconnectState state = m_reconnectHandler!
.BeginReconnect(
Session,
m_reverseConnectManager,
ReconnectPeriod,
Client_ReconnectComplete
);
if (state == SessionReconnectHandler.ReconnectState.Triggered)
{
m_logger.KeepAliveReconnectStatusWithPeriod(
e.Status,
state,
ReconnectPeriod);
}
else
{
m_logger.KeepAliveReconnectStatus(
e.Status,
state);
}
// cancel sending a new keep alive request, because reconnect is triggered.
e.CancelKeepAlive = true;
}
}
catch (Exception exception)
{
m_logger.ErrorInOnKeepAlive(exception);
}
}
/// <summary>
/// Called when the reconnect attempt was successful.
/// </summary>
private void Client_ReconnectComplete(object? sender, EventArgs e)
{
// ignore callbacks from discarded objects.
if (!ReferenceEquals(sender, m_reconnectHandler))
{
return;
}
lock (m_lock)
{
// if session recovered, Session property is null
if (m_reconnectHandler!.Session != null)
{
// ensure only a new instance is disposed
// after reactivate, the same session instance may be returned
if (!ReferenceEquals(Session, m_reconnectHandler.Session))
{
m_logger.ReconnectedToNewSession(m_reconnectHandler.Session.SessionId);
ISession session = Session;
Session = m_reconnectHandler.Session;
session?.Dispose();
}
else
{
m_logger.ReactivatedSession(m_reconnectHandler.Session.SessionId);
}
}
else
{
m_logger.ReconnectKeepAliveRecovered();
}
}
}
/// <summary>
/// Per-error accept callback invoked by the new
/// <see cref="ICertificateValidatorEx.AcceptError"/> hook every time
/// an untrusted certificate is received from the server. Returns
/// <see langword="true"/> to accept the error, <see langword="false"/>
/// to reject it.
/// </summary>
protected virtual bool AcceptCertificate(Certificate certificate, ServiceResult error)
{
// ****
// Implement a custom logic to decide if the certificate should be
// accepted or not. Return true to accept, false to reject.
// ***
m_logger.CertificateError(error);
bool certificateAccepted =
error.StatusCode == StatusCodes.BadCertificateUntrusted && AutoAccept;
if (certificateAccepted)
{
m_logger.UntrustedCertificateAccepted(certificate.Subject);
}
else
{
m_logger.UntrustedCertificateRejected(certificate.Subject);
}
return certificateAccepted;
}
private readonly Lock m_lock = new();
private readonly ReverseConnectManager? m_reverseConnectManager;
private readonly ApplicationConfiguration m_configuration;
private SessionReconnectHandler? m_reconnectHandler;
private readonly ILogger m_logger;
private readonly ITelemetryContext m_telemetry;
private bool m_disposed;
}
internal static partial class ClientCertificateLog
{
[LoggerMessage(EventId = ConsoleReferenceClientEventIds.ClientCertificate + 0, Level = LogLevel.Information,
Message = "Untrusted Certificate accepted. Subject = {Subject}")]
public static partial void UntrustedCertificateAccepted(this ILogger logger, string subject);
[LoggerMessage(EventId = ConsoleReferenceClientEventIds.ClientCertificate + 1, Level = LogLevel.Information,
Message = "Untrusted Certificate rejected. Subject = {Subject}")]
public static partial void UntrustedCertificateRejected(this ILogger logger, string subject);
}
internal static partial class ClientReconnectLog
{
[LoggerMessage(EventId = ConsoleReferenceClientEventIds.ClientReconnect + 0, Level = LogLevel.Information,
Message = "KeepAlive status {StatusCode}, reconnect status {State}, reconnect period {ReconnectPeriod}ms.")]
public static partial void KeepAliveReconnectStatusWithPeriod(
this ILogger logger,
ServiceResult? statusCode,
SessionReconnectHandler.ReconnectState state,
int reconnectPeriod);
[LoggerMessage(EventId = ConsoleReferenceClientEventIds.ClientReconnect + 1, Level = LogLevel.Information,
Message = "KeepAlive status {StatusCode}, reconnect status {State}.")]
public static partial void KeepAliveReconnectStatus(
this ILogger logger,
ServiceResult? statusCode,
SessionReconnectHandler.ReconnectState state);
[LoggerMessage(EventId = ConsoleReferenceClientEventIds.ClientReconnect + 2, Level = LogLevel.Error,
Message = "Error in OnKeepAlive.")]
public static partial void ErrorInOnKeepAlive(this ILogger logger, Exception exception);
[LoggerMessage(EventId = ConsoleReferenceClientEventIds.ClientReconnect + 3, Level = LogLevel.Information,
Message = "--- RECONNECTED TO NEW SESSION --- {SessionId}")]
public static partial void ReconnectedToNewSession(this ILogger logger, NodeId sessionId);
[LoggerMessage(EventId = ConsoleReferenceClientEventIds.ClientReconnect + 4, Level = LogLevel.Information,
Message = "--- REACTIVATED SESSION --- {SessionId}")]
public static partial void ReactivatedSession(this ILogger logger, NodeId sessionId);
[LoggerMessage(EventId = ConsoleReferenceClientEventIds.ClientReconnect + 5, Level = LogLevel.Information,
Message = "--- RECONNECT KeepAlive recovered ---")]
public static partial void ReconnectKeepAliveRecovered(this ILogger logger);
}
internal static partial class UAClientLog
{
[LoggerMessage(EventId = ConsoleReferenceClientEventIds.UAClient + 0, Level = LogLevel.Error,
Message = "Disconnect Error")]
public static partial void DisconnectError(this ILogger logger, Exception ex);
[LoggerMessage(EventId = ConsoleReferenceClientEventIds.UAClient + 1, Level = LogLevel.Warning,
Message = "KeepAlive status {StatusCode}, but reconnect is disabled.")]
public static partial void KeepAliveReconnectDisabled(this ILogger logger, ServiceResult? statusCode);
[LoggerMessage(EventId = ConsoleReferenceClientEventIds.UAClient + 2, Level = LogLevel.Information,
Message = "{Error}")]
public static partial void CertificateError(this ILogger logger, ServiceResult error);
}
}