mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-22 01:26:20 +08:00
a2782191b1
Backport of 70c74e7 from `master` to `master378`.
### Summary
Scopes `Cancel` request matching to the caller's session and adds a
regression test verifying a request handle can no longer cancel work
belonging to another session.
### Problem
Per OPC UA Part 4, `Cancel` applies to a request handle from the same
session that issued the original request. Previously
`StandardServer.CancelAsync` validated the caller's session but
forwarded only the raw `requestHandle` to
`RequestManager.CancelRequests`, which iterated the global
outstanding-request table and canceled every request whose
`ClientHandle` matched — regardless of owning session. Since request
handles are only session-scoped and different sessions can reuse the
same value, one session could cancel another session's in-flight
request.
### Changes
- Pass the validated caller session id from `StandardServer.CancelAsync`
into `RequestManager.CancelRequests`.
- Restrict `RequestManager.CancelRequests` to requests whose `SessionId`
**and** `ClientHandle` both match.
- Update the existing request-manager test call and add
`CancelRequestsDoesNotCancelMatchingHandleFromDifferentSession`
regression test.
### Notes on the backport
The `master378` branch predates the `RequestLifetime` cancellation model
and the `SessionPublishQueueTests` present on `master`, so those parts
of the original commit do not apply. The core fix and the regression
test were adapted to this branch's `SetStatusCode`/`OperationStatus`
model. `Opc.Ua.Server.Tests` builds clean and both `RequestManagerTests`
pass.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
273 lines
9.2 KiB
C#
273 lines
9.2 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.Collections.Generic;
|
|
using System.Threading;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Opc.Ua.Server
|
|
{
|
|
/// <summary>
|
|
/// An object that manages requests from within the server.
|
|
/// </summary>
|
|
public class RequestManager : IDisposable
|
|
{
|
|
/// <summary>
|
|
/// Initilizes the manager.
|
|
/// </summary>
|
|
public RequestManager(IServerInternal server)
|
|
{
|
|
m_server = server ?? throw new ArgumentNullException(nameof(server));
|
|
m_logger = server.Telemetry.CreateLogger<RequestManager>();
|
|
m_requests = [];
|
|
m_requestTimer = null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Frees any unmanaged resources.
|
|
/// </summary>
|
|
public void Dispose()
|
|
{
|
|
Dispose(true);
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
|
|
/// <summary>
|
|
/// An overrideable version of the Dispose.
|
|
/// </summary>
|
|
protected virtual void Dispose(bool disposing)
|
|
{
|
|
if (disposing)
|
|
{
|
|
List<OperationContext> operations = null;
|
|
|
|
lock (m_requestsLock)
|
|
{
|
|
operations = [.. m_requests.Values];
|
|
m_requests.Clear();
|
|
}
|
|
|
|
foreach (OperationContext operation in operations)
|
|
{
|
|
operation.SetStatusCode(StatusCodes.BadSessionClosed);
|
|
}
|
|
|
|
Utils.SilentDispose(m_requestTimer);
|
|
m_requestTimer = null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Raised when the status of an outstanding request changes.
|
|
/// </summary>
|
|
public event RequestCancelledEventHandler RequestCancelled
|
|
{
|
|
add
|
|
{
|
|
lock (m_lock)
|
|
{
|
|
m_RequestCancelled += value;
|
|
}
|
|
}
|
|
remove
|
|
{
|
|
lock (m_lock)
|
|
{
|
|
m_RequestCancelled -= value;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when a new request arrives.
|
|
/// </summary>
|
|
/// <exception cref="ArgumentNullException"><paramref name="context"/> is <c>null</c>.</exception>
|
|
public void RequestReceived(OperationContext context)
|
|
{
|
|
if (context == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(context));
|
|
}
|
|
|
|
lock (m_requestsLock)
|
|
{
|
|
m_requests.Add(context.RequestId, context);
|
|
|
|
if (context.OperationDeadline < DateTime.MaxValue && m_requestTimer == null)
|
|
{
|
|
m_requestTimer = new Timer(OnTimerExpired, null, 1000, 1000);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when a request completes (normally or abnormally).
|
|
/// </summary>
|
|
/// <exception cref="ArgumentNullException"><paramref name="context"/> is <c>null</c>.</exception>
|
|
public void RequestCompleted(OperationContext context)
|
|
{
|
|
if (context == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(context));
|
|
}
|
|
|
|
lock (m_requestsLock)
|
|
{
|
|
// remove the request.
|
|
m_requests.Remove(context.RequestId);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when the client wishes to cancel one or more requests.
|
|
/// </summary>
|
|
public void CancelRequests(NodeId sessionId, uint requestHandle, out uint cancelCount)
|
|
{
|
|
var cancelledRequests = new List<uint>();
|
|
|
|
// flag requests as cancelled.
|
|
lock (m_requestsLock)
|
|
{
|
|
foreach (OperationContext request in m_requests.Values)
|
|
{
|
|
if (request.SessionId == sessionId &&
|
|
request.ClientHandle == requestHandle)
|
|
{
|
|
request.SetStatusCode(StatusCodes.BadRequestCancelledByRequest);
|
|
cancelledRequests.Add(request.RequestId);
|
|
|
|
// report the AuditCancelEventType
|
|
m_server.ReportAuditCancelEvent(
|
|
request.SessionId,
|
|
requestHandle,
|
|
StatusCodes.Good,
|
|
m_logger);
|
|
}
|
|
}
|
|
}
|
|
|
|
// return the number of requests found.
|
|
cancelCount = (uint)cancelledRequests.Count;
|
|
|
|
// raise notifications.
|
|
lock (m_lock)
|
|
{
|
|
for (int ii = 0; ii < cancelledRequests.Count; ii++)
|
|
{
|
|
if (m_RequestCancelled != null)
|
|
{
|
|
try
|
|
{
|
|
m_RequestCancelled(
|
|
this,
|
|
cancelledRequests[ii],
|
|
StatusCodes.BadRequestCancelledByRequest);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
m_logger.LogError(e, "Unexpected error reporting RequestCancelled event.");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Checks for any expired requests and changes their status.
|
|
/// </summary>
|
|
private void OnTimerExpired(object state)
|
|
{
|
|
var expiredRequests = new List<uint>();
|
|
|
|
// flag requests as expired.
|
|
lock (m_requestsLock)
|
|
{
|
|
// find the completed request.
|
|
bool deadlineExists = false;
|
|
|
|
foreach (OperationContext request in m_requests.Values)
|
|
{
|
|
if (request.OperationDeadline < DateTime.UtcNow)
|
|
{
|
|
request.SetStatusCode(StatusCodes.BadTimeout);
|
|
expiredRequests.Add(request.RequestId);
|
|
}
|
|
else if (request.OperationDeadline < DateTime.MaxValue)
|
|
{
|
|
deadlineExists = true;
|
|
}
|
|
}
|
|
|
|
// check if the timer can be cancelled.
|
|
if (m_requestTimer != null && !deadlineExists)
|
|
{
|
|
m_requestTimer.Dispose();
|
|
m_requestTimer = null;
|
|
}
|
|
}
|
|
|
|
// raise notifications.
|
|
lock (m_lock)
|
|
{
|
|
for (int ii = 0; ii < expiredRequests.Count; ii++)
|
|
{
|
|
if (m_RequestCancelled != null)
|
|
{
|
|
try
|
|
{
|
|
m_RequestCancelled(this, expiredRequests[ii], StatusCodes.BadTimeout);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
m_logger.LogError(e, "Unexpected error reporting RequestCancelled event.");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private readonly Lock m_lock = new();
|
|
private readonly ILogger m_logger;
|
|
private readonly IServerInternal m_server;
|
|
private readonly Dictionary<uint, OperationContext> m_requests;
|
|
private readonly Lock m_requestsLock = new();
|
|
private Timer m_requestTimer;
|
|
private event RequestCancelledEventHandler m_RequestCancelled;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when a request is cancelled.
|
|
/// </summary>
|
|
public delegate void RequestCancelledEventHandler(
|
|
RequestManager source,
|
|
uint requestId,
|
|
StatusCode statusCode);
|
|
}
|