/* ========================================================================
* Copyright (c) 2005-2017 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.IO;
using Opc.Ua.Client;
using Opc.Ua.Configuration;
using System.Security.Cryptography.X509Certificates;
namespace Opc.Ua.Gds.Client
{
///
/// A class used to access the Push Configuration information model.
///
public class ServerPushConfigurationClient
{
#region Constructors
///
/// Initializes a new instance of the class.
///
/// The application.
public ServerPushConfigurationClient(ApplicationInstance application)
{
m_application = application;
}
#endregion
#region Public Properties
///
/// Gets the application instance.
///
///
/// The application instance.
///
public ApplicationInstance Application
{
get { return m_application; }
}
///
/// Gets or sets the admin credentials.
///
///
/// The admin credentials.
///
public UserIdentity AdminCredentials
{
get { return m_adminCredentials; }
set { m_adminCredentials = value; }
}
///
/// Gets or sets the endpoint URL.
///
///
/// The endpoint URL.
///
public string EndpointUrl
{
get { return m_endpointUrl; }
set { m_endpointUrl = value; }
}
///
/// Raised when admin credentials are required.
///
public event AdminCredentialsRequiredEventHandler AdminCredentialsRequired;
///
/// Raised when the connection status changes.
///
public event EventHandler ConnectionStatusChanged;
///
/// Gets or sets the preferred locales.
///
///
/// The preferred locales.
///
public string[] PreferredLocales
{
get { return m_preferredLocales; }
set { m_preferredLocales = value; }
}
///
/// Gets a value indicating whether the session is connected.
///
///
/// true if the session is connected; otherwise, false.
///
public bool IsConnected
{
get { return m_session != null && m_session.Connected; }
}
///
/// Gets the session.
///
///
/// The session.
///
public Session Session
{
get { return m_session; }
}
///
/// Gets the endpoint.
///
///
/// The endpoint.
///
public ConfiguredEndpoint Endpoint
{
get
{
if (m_session != null && m_session.ConfiguredEndpoint != null)
{
return m_session.ConfiguredEndpoint;
}
return m_endpoint;
}
set
{
if (m_session != null)
{
throw new InvalidOperationException("Session must be closed before changing endpoint.");
}
if (value == null || m_endpoint == null || value.EndpointUrl != m_endpoint.EndpointUrl)
{
m_adminCredentials = null;
}
m_endpoint = value;
}
}
///
/// Occurs when keep alive occurs.
///
public event KeepAliveEventHandler KeepAlive;
///
/// Occurs when the server status changes.
///
public event MonitoredItemNotificationEventHandler ServerStatusChanged;
#endregion
#region Public Methods
///
/// Connects using the default endpoint.
///
public void Connect()
{
Connect(EndpointUrl);
}
///
/// Connects the specified endpoint URL.
///
/// The endpoint URL.
/// endpointUrl
/// endpointUrl
public void Connect(string endpointUrl)
{
if (String.IsNullOrEmpty(endpointUrl))
{
throw new ArgumentNullException("endpointUrl");
}
if (!Uri.IsWellFormedUriString(endpointUrl, UriKind.Absolute))
{
throw new ArgumentException(endpointUrl + " is not a valid URL.", "endpointUrl");
}
EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(endpointUrl, true);
EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_application.ApplicationConfiguration);
ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);
Connect(endpoint);
}
///
/// Connects the specified endpoint.
///
/// The endpoint.
public async void Connect(ConfiguredEndpoint endpoint)
{
if (endpoint != null && m_endpoint != null && endpoint.EndpointUrl != m_endpoint.EndpointUrl)
{
m_adminCredentials = null;
}
if (endpoint == null)
{
endpoint = m_endpoint;
if (endpoint == null)
{
throw new ArgumentNullException("endpoint");
}
}
if (m_session != null)
{
m_session.Dispose();
m_session = null;
}
m_session = await Session.Create(
m_application.ApplicationConfiguration,
endpoint,
true,
false,
m_application.ApplicationName,
60000,
null,
m_preferredLocales);
m_endpoint = m_session.ConfiguredEndpoint;
if (m_session.Factory.GetSystemType(Opc.Ua.DataTypeIds.TrustListDataType) == null)
{
m_session.Factory.AddEncodeableTypes(typeof(Opc.Ua.DataTypeIds).Assembly);
}
RaiseConnectionStatusChangedEvent();
m_session.ReturnDiagnostics = DiagnosticsMasks.SymbolicIdAndText;
m_session.KeepAlive += Session_KeepAlive;
Subscription subscription = new Subscription
{
Handle = this,
DisplayName = null,
PublishingInterval = 1000,
KeepAliveCount = 10,
LifetimeCount = 100,
MaxNotificationsPerPublish = 1000,
PublishingEnabled = true,
TimestampsToReturn = TimestampsToReturn.Neither
};
m_session.AddSubscription(subscription);
subscription.Create();
MonitoredItem monitoredItem = new MonitoredItem
{
StartNodeId = Opc.Ua.VariableIds.Server_ServerStatus,
AttributeId = Attributes.Value,
SamplingInterval = 1000,
QueueSize = 0,
DiscardOldest = true,
Handle = typeof(ServerStatusDataType)
};
monitoredItem.Notification += ServerStatus_Notification;
subscription.AddItem(monitoredItem);
subscription.ApplyChanges();
}
///
/// Disconnects this instance.
///
public void Disconnect()
{
if (m_session != null)
{
m_session.Close();
m_session = null;
RaiseConnectionStatusChangedEvent();
}
}
private void RaiseConnectionStatusChangedEvent()
{
var Callback = ConnectionStatusChanged;
if (Callback != null)
{
try
{
Callback(this, new EventArgs());
}
catch (Exception exception)
{
Utils.Trace(exception, "Unexpected error raising ConnectionStatusChanged event.");
}
}
}
///
/// Gets the supported key formats.
///
/// Connection to server is not active.
public string[] GetSupportedKeyFormats()
{
if (AdminCredentials == null || Endpoint == null)
{
return null;
}
if (!IsConnected)
{
Connect();
}
ReadValueIdCollection nodesToRead = new ReadValueIdCollection
{
new ReadValueId()
{
NodeId = ExpandedNodeId.ToNodeId(Opc.Ua.VariableIds.ServerConfiguration_SupportedPrivateKeyFormats, m_session.NamespaceUris),
AttributeId = Attributes.Value
}
};
DataValueCollection results = null;
DiagnosticInfoCollection diagnosticInfos = null;
m_session.Read(
null,
0,
TimestampsToReturn.Neither,
nodesToRead,
out results,
out diagnosticInfos);
ClientBase.ValidateResponse(results, nodesToRead);
ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
return results[0].GetValue(null);
}
///
/// Reads the trust list.
///
public TrustListDataType ReadTrustList()
{
if (!IsConnected)
{
Connect();
}
IUserIdentity oldUser = ElevatePermissions();
try
{
var outputArguments = m_session.Call(
ExpandedNodeId.ToNodeId(Opc.Ua.ObjectIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList, m_session.NamespaceUris),
ExpandedNodeId.ToNodeId(Opc.Ua.MethodIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList_Open, m_session.NamespaceUris),
(byte)1);
uint fileHandle = (uint)outputArguments[0];
MemoryStream ostrm = new MemoryStream();
try
{
while (true)
{
int length = 256;
outputArguments = m_session.Call(
ExpandedNodeId.ToNodeId(Opc.Ua.ObjectIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList, m_session.NamespaceUris),
ExpandedNodeId.ToNodeId(Opc.Ua.MethodIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList_Read, m_session.NamespaceUris),
fileHandle,
length);
byte[] bytes = (byte[])outputArguments[0];
ostrm.Write(bytes, 0, bytes.Length);
if (length != bytes.Length)
{
break;
}
}
m_session.Call(
ExpandedNodeId.ToNodeId(Opc.Ua.ObjectIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList, m_session.NamespaceUris),
ExpandedNodeId.ToNodeId(Opc.Ua.MethodIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList_Close, m_session.NamespaceUris),
fileHandle);
}
catch (Exception)
{
if (IsConnected)
{
m_session.Call(
ExpandedNodeId.ToNodeId(Opc.Ua.ObjectIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList, m_session.NamespaceUris),
ExpandedNodeId.ToNodeId(Opc.Ua.MethodIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList_Close, m_session.NamespaceUris),
fileHandle);
}
throw;
}
ostrm.Position = 0;
BinaryDecoder decoder = new BinaryDecoder(ostrm, m_session.MessageContext);
TrustListDataType trustList = new TrustListDataType();
trustList.Decode(decoder);
decoder.Close();
ostrm.Close();
return trustList;
}
finally
{
RevertPermissions(oldUser);
}
}
///
/// Updates the trust list.
///
public bool UpdateTrustList(TrustListDataType trustList)
{
if (!IsConnected)
{
Connect();
}
IUserIdentity oldUser = ElevatePermissions();
try
{
MemoryStream strm = new MemoryStream();
BinaryEncoder encoder = new BinaryEncoder(strm, m_session.MessageContext);
encoder.WriteEncodeable(null, trustList, null);
strm.Position = 0;
var outputArguments = m_session.Call(
ExpandedNodeId.ToNodeId(Opc.Ua.ObjectIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList, m_session.NamespaceUris),
ExpandedNodeId.ToNodeId(Opc.Ua.MethodIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList_Open, m_session.NamespaceUris),
(byte)6);
uint fileHandle = (uint)outputArguments[0];
try
{
bool writing = true;
byte[] buffer = new byte[256];
while (writing)
{
int bytesWritten = strm.Read(buffer, 0, buffer.Length);
if (bytesWritten != buffer.Length)
{
byte[] copy = new byte[bytesWritten];
Array.Copy(buffer, copy, bytesWritten);
buffer = copy;
writing = false;
}
m_session.Call(
ExpandedNodeId.ToNodeId(Opc.Ua.ObjectIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList, m_session.NamespaceUris),
ExpandedNodeId.ToNodeId(Opc.Ua.MethodIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList_Write, m_session.NamespaceUris),
fileHandle,
buffer);
}
outputArguments = m_session.Call(
ExpandedNodeId.ToNodeId(Opc.Ua.ObjectIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList, m_session.NamespaceUris),
ExpandedNodeId.ToNodeId(Opc.Ua.MethodIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList_CloseAndUpdate, m_session.NamespaceUris),
fileHandle);
return (bool)outputArguments[0];
}
catch (Exception)
{
if (IsConnected)
{
m_session.Call(
ExpandedNodeId.ToNodeId(Opc.Ua.ObjectIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList, m_session.NamespaceUris),
ExpandedNodeId.ToNodeId(Opc.Ua.MethodIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup_TrustList_Close, m_session.NamespaceUris),
fileHandle);
}
throw;
}
}
finally
{
RevertPermissions(oldUser);
}
}
///
/// Creates the CSR.
///
/// The certificate group identifier.
/// The certificate type identifier.
/// Name of the subject.
/// if set to true [regenerate private key].
/// The nonce.
///
public byte[] CreateCertificateRequest(NodeId certificateGroupId, NodeId certificateTypeId, string subjectName, bool regeneratePrivateKey, byte[] nonce)
{
if (!IsConnected)
{
Connect();
}
IUserIdentity oldUser = ElevatePermissions();
try
{
var outputArguments = m_session.Call(
ExpandedNodeId.ToNodeId(Opc.Ua.ObjectIds.ServerConfiguration, m_session.NamespaceUris),
ExpandedNodeId.ToNodeId(Opc.Ua.MethodIds.ServerConfiguration_CreateSigningRequest, m_session.NamespaceUris),
certificateGroupId,
certificateTypeId,
subjectName,
regeneratePrivateKey,
nonce);
if (outputArguments.Count > 0)
{
return (byte[])outputArguments[0];
}
return null;
}
finally
{
RevertPermissions(oldUser);
}
}
///
/// Updates the certificate.
///
/// The certificate.
public bool UpdateCertificate(NodeId certificateGroupId, NodeId certificateTypeId, byte[] certificate, string privateKeyFormat, byte[] privateKey, byte[][] issuerCertificates)
{
if (!IsConnected)
{
Connect();
}
IUserIdentity oldUser = ElevatePermissions();
try
{
var outputArguments = m_session.Call(
ExpandedNodeId.ToNodeId(Opc.Ua.ObjectIds.ServerConfiguration, m_session.NamespaceUris),
ExpandedNodeId.ToNodeId(Opc.Ua.MethodIds.ServerConfiguration_UpdateCertificate, m_session.NamespaceUris),
certificateGroupId,
certificateTypeId,
certificate,
issuerCertificates,
privateKeyFormat,
privateKey);
if (outputArguments.Count > 0)
{
return (bool)outputArguments[0];
}
return false;
}
finally
{
RevertPermissions(oldUser);
}
}
///
/// Reads the rejected list.
///
public X509Certificate2Collection GetRejectedList()
{
if (!IsConnected)
{
Connect();
}
IUserIdentity oldUser = ElevatePermissions();
try
{
var outputArguments = m_session.Call(
ExpandedNodeId.ToNodeId(Opc.Ua.ObjectIds.ServerConfiguration, m_session.NamespaceUris),
ExpandedNodeId.ToNodeId(Opc.Ua.MethodIds.ServerConfiguration_GetRejectedList, m_session.NamespaceUris)
);
byte[][] rawCertificates = (byte[][])outputArguments[0];
X509Certificate2Collection collection = new X509Certificate2Collection();
foreach (var rawCertificate in rawCertificates)
{
collection.Add(new X509Certificate(rawCertificate));
}
return collection;
}
finally
{
RevertPermissions(oldUser);
}
}
///
/// Restarts this instance.
///
public void ApplyChanges()
{
if (!IsConnected)
{
Connect();
}
ElevatePermissions();
m_session.Call(
ExpandedNodeId.ToNodeId(Opc.Ua.ObjectIds.ServerConfiguration, m_session.NamespaceUris),
ExpandedNodeId.ToNodeId(Opc.Ua.MethodIds.ServerConfiguration_ApplyChanges, m_session.NamespaceUris));
}
#endregion
#region Private Methods
private IUserIdentity ElevatePermissions()
{
IUserIdentity oldUser = m_session.Identity;
if (m_adminCredentials == null || !Object.ReferenceEquals(m_session.Identity, m_adminCredentials))
{
IUserIdentity newCredentials = null;
if (m_adminCredentials == null)
{
var handle = AdminCredentialsRequired;
if (handle == null)
{
throw new InvalidOperationException("The operation requires administrator credentials.");
}
var args = new AdminCredentialsRequiredEventArgs();
handle(this, args);
newCredentials = args.Credentials;
if (args.CacheCredentials)
{
m_adminCredentials = args.Credentials;
}
}
else
{
newCredentials = m_adminCredentials;
}
try
{
m_session.UpdateSession(newCredentials, m_preferredLocales);
}
catch (Exception)
{
m_adminCredentials = null;
throw;
}
}
return oldUser;
}
private void RevertPermissions(IUserIdentity oldUser)
{
try
{
if (Object.ReferenceEquals(m_session.Identity, m_adminCredentials))
{
m_session.UpdateSession(oldUser, m_preferredLocales);
}
}
catch (Exception e)
{
Utils.Trace(e, "Error reverting to normal permissions.");
}
}
private void Session_KeepAlive(Session session, KeepAliveEventArgs e)
{
if (!Object.ReferenceEquals(session, m_session))
{
return;
}
var Callback = KeepAlive;
if (Callback != null)
{
try
{
Callback(session, e);
}
catch (Exception exception)
{
Utils.Trace(exception, "Unexpected error raising KeepAlive event.");
}
}
}
private void ServerStatus_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
{
if (!Object.ReferenceEquals(monitoredItem.Subscription.Session, m_session))
{
return;
}
var Callback = ServerStatusChanged;
if (Callback != null)
{
try
{
Callback(monitoredItem, e);
}
catch (Exception exception)
{
Utils.Trace(exception, "Unexpected error raising KeepAlive event.");
}
}
}
#endregion
#region Private Fields
private ApplicationInstance m_application;
private ConfiguredEndpoint m_endpoint;
private string[] m_preferredLocales;
private string m_endpointUrl;
private Session m_session;
private UserIdentity m_adminCredentials;
#endregion
}
}