summaryrefslogtreecommitdiffstats
path: root/src/BobinkClient.cpp
blob: 565868c24c656e0bb1c2afdf3b871bd089b6a1ea (plain)
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
/**
 * @file   BobinkClient.cpp
 * @brief  BobinkClient implementation.
 */
#include "BobinkClient.h"
#include "BobinkAuth.h"

#include <QDir>
#include <QOpcUaUserTokenPolicy>
#include <QStandardPaths>

BobinkClient *BobinkClient::s_instance = nullptr;

static QString defaultPkiDir()
{
    return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)
           + QStringLiteral("/pki");
}

/** @brief Create the standard OPC UA PKI directory tree. */
static void ensurePkiDirs(const QString &base)
{
    for (const auto *sub : {"own/certs", "own/private",
                            "trusted/certs", "trusted/crl",
                            "issuers/certs", "issuers/crl"}) {
        QDir().mkpath(base + QLatin1Char('/') + QLatin1String(sub));
    }
}

BobinkClient::BobinkClient(QObject *parent)
    : QObject(parent)
    , m_provider(new QOpcUaProvider(this))
    , m_pkiDir(defaultPkiDir())
{
    ensurePkiDirs(m_pkiDir);
    setupClient();
    autoDetectPki();
    applyPki();
    connect(&m_discoveryTimer, &QTimer::timeout, this, &BobinkClient::doDiscovery);
}

BobinkClient::~BobinkClient()
{
    if (s_instance == this)
        s_instance = nullptr;
}

BobinkClient *BobinkClient::instance()
{
    return s_instance;
}

BobinkClient *BobinkClient::create(QQmlEngine *, QJSEngine *)
{
    if (!s_instance) {
        s_instance = new BobinkClient;
        QJSEngine::setObjectOwnership(s_instance, QJSEngine::CppOwnership);
    }
    return s_instance;
}

void BobinkClient::setupClient()
{
    m_client = m_provider->createClient(QStringLiteral("open62541"));
    if (!m_client) {
        qWarning() << "BobinkClient: failed to create open62541 backend";
        return;
    }

    connect(m_client, &QOpcUaClient::stateChanged,
            this, &BobinkClient::handleStateChanged);
    connect(m_client, &QOpcUaClient::endpointsRequestFinished,
            this, &BobinkClient::handleEndpointsReceived);
    connect(m_client, &QOpcUaClient::connectError,
            this, &BobinkClient::handleConnectError);
    connect(m_client, &QOpcUaClient::findServersFinished,
            this, &BobinkClient::handleFindServersFinished);
}

/* ======================================
 *  Connection properties
 * ====================================== */

bool BobinkClient::connected() const { return m_connected; }

QString BobinkClient::serverUrl() const { return m_serverUrl; }

void BobinkClient::setServerUrl(const QString &url)
{
    if (m_serverUrl == url)
        return;
    m_serverUrl = url;
    emit serverUrlChanged();
}

BobinkAuth *BobinkClient::auth() const { return m_auth; }

void BobinkClient::setAuth(BobinkAuth *auth)
{
    if (m_auth == auth)
        return;
    m_auth = auth;
    emit authChanged();
}

QOpcUaClient *BobinkClient::opcuaClient() const { return m_client; }

/* ======================================
 *  Connection methods
 * ====================================== */

void BobinkClient::connectToServer()
{
    if (!m_client) {
        emit connectionError(QStringLiteral("OPC UA backend not available"));
        return;
    }
    if (m_serverUrl.isEmpty()) {
        emit connectionError(QStringLiteral("No server URL set"));
        return;
    }
    if (m_client->state() != QOpcUaClient::Disconnected) {
        emit connectionError(QStringLiteral("Already connected or connecting"));
        return;
    }

    QUrl url(m_serverUrl);
    if (!url.isValid()) {
        emit connectionError(QStringLiteral("Invalid server URL: %1").arg(m_serverUrl));
        return;
    }
    m_client->requestEndpoints(url);
}

static QString securityPolicyUri(BobinkClient::SecurityPolicy policy)
{
    switch (policy) {
    case BobinkClient::Basic256Sha256:
        return QStringLiteral(
            "http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256");
    case BobinkClient::Aes128_Sha256_RsaOaep:
        return QStringLiteral(
            "http://opcfoundation.org/UA/SecurityPolicy#Aes128_Sha256_RsaOaep");
    case BobinkClient::Aes256_Sha256_RsaPss:
        return QStringLiteral(
            "http://opcfoundation.org/UA/SecurityPolicy#Aes256_Sha256_RsaPss");
    }
    return {};
}

void BobinkClient::connectDirect(SecurityPolicy policy, SecurityMode mode)
{
    if (!m_client) {
        emit connectionError(QStringLiteral("OPC UA backend not available"));
        return;
    }
    if (m_serverUrl.isEmpty()) {
        emit connectionError(QStringLiteral("No server URL set"));
        return;
    }
    if (m_client->state() != QOpcUaClient::Disconnected) {
        emit connectionError(QStringLiteral("Already connected or connecting"));
        return;
    }

    QOpcUaEndpointDescription endpoint;
    endpoint.setEndpointUrl(m_serverUrl);
    endpoint.setSecurityPolicy(securityPolicyUri(policy));
    endpoint.setSecurityMode(
        static_cast<QOpcUaEndpointDescription::MessageSecurityMode>(mode));

    QOpcUaUserTokenPolicy tokenPolicy;
    if (m_auth) {
        switch (m_auth->mode()) {
        case BobinkAuth::Anonymous:
            tokenPolicy.setTokenType(QOpcUaUserTokenPolicy::TokenType::Anonymous);
            break;
        case BobinkAuth::UserPass:
            tokenPolicy.setTokenType(QOpcUaUserTokenPolicy::TokenType::Username);
            break;
        case BobinkAuth::Certificate:
            tokenPolicy.setTokenType(QOpcUaUserTokenPolicy::TokenType::Certificate);
            break;
        }
        m_client->setAuthenticationInformation(m_auth->toAuthenticationInformation());
    } else {
        tokenPolicy.setTokenType(QOpcUaUserTokenPolicy::TokenType::Anonymous);
    }
    endpoint.setUserIdentityTokens({tokenPolicy});

    m_client->connectToEndpoint(endpoint);
}

void BobinkClient::disconnectFromServer()
{
    if (m_client)
        m_client->disconnectFromEndpoint();
}

void BobinkClient::acceptCertificate()
{
    m_certAccepted = true;
    if (m_certLoop)
        m_certLoop->quit();
}

void BobinkClient::rejectCertificate()
{
    m_certAccepted = false;
    if (m_certLoop)
        m_certLoop->quit();
}

/* ======================================
 *  Discovery properties
 * ====================================== */

QString BobinkClient::discoveryUrl() const { return m_discoveryUrl; }

void BobinkClient::setDiscoveryUrl(const QString &url)
{
    if (m_discoveryUrl == url)
        return;
    m_discoveryUrl = url;
    emit discoveryUrlChanged();
}

int BobinkClient::discoveryInterval() const { return m_discoveryInterval; }

void BobinkClient::setDiscoveryInterval(int ms)
{
    if (m_discoveryInterval == ms)
        return;
    m_discoveryInterval = ms;
    emit discoveryIntervalChanged();

    if (m_discoveryTimer.isActive())
        m_discoveryTimer.setInterval(ms);
}

bool BobinkClient::discovering() const { return m_discovering; }

const QList<QOpcUaApplicationDescription> &BobinkClient::discoveredServers() const
{
    return m_discoveredServers;
}

QVariantList BobinkClient::servers() const
{
    return m_serversCache;
}

/* ======================================
 *  PKI
 * ====================================== */

QString BobinkClient::pkiDir() const { return m_pkiDir; }

void BobinkClient::setPkiDir(const QString &path)
{
    if (m_pkiDir == path)
        return;
    m_pkiDir = path;
    ensurePkiDirs(m_pkiDir);
    emit pkiDirChanged();
}

QString BobinkClient::certFile() const { return m_certFile; }

void BobinkClient::setCertFile(const QString &path)
{
    if (m_certFile == path)
        return;
    m_certFile = path;
    emit certFileChanged();
}

QString BobinkClient::keyFile() const { return m_keyFile; }

void BobinkClient::setKeyFile(const QString &path)
{
    if (m_keyFile == path)
        return;
    m_keyFile = path;
    emit keyFileChanged();
}

void BobinkClient::autoDetectPki()
{
    if (m_pkiDir.isEmpty())
        return;

    QDir certDir(m_pkiDir + QStringLiteral("/own/certs"));
    QStringList certs = certDir.entryList({QStringLiteral("*.der")}, QDir::Files);
    if (!certs.isEmpty())
        setCertFile(certDir.filePath(certs.first()));

    QDir keyDir(m_pkiDir + QStringLiteral("/own/private"));
    QStringList keys = keyDir.entryList(
        {QStringLiteral("*.pem"), QStringLiteral("*.crt")}, QDir::Files);
    if (!keys.isEmpty())
        setKeyFile(keyDir.filePath(keys.first()));
}

void BobinkClient::applyPki()
{
    if (!m_client || m_pkiDir.isEmpty())
        return;

    QOpcUaPkiConfiguration pki;
    if (!m_certFile.isEmpty())
        pki.setClientCertificateFile(m_certFile);
    if (!m_keyFile.isEmpty())
        pki.setPrivateKeyFile(m_keyFile);
    pki.setTrustListDirectory(m_pkiDir + QStringLiteral("/trusted/certs"));
    pki.setRevocationListDirectory(m_pkiDir + QStringLiteral("/trusted/crl"));
    pki.setIssuerListDirectory(m_pkiDir + QStringLiteral("/issuers/certs"));
    pki.setIssuerRevocationListDirectory(m_pkiDir + QStringLiteral("/issuers/crl"));

    m_client->setPkiConfiguration(pki);

    if (pki.isKeyAndCertificateFileSet())
        m_client->setApplicationIdentity(pki.applicationIdentity());
}

/* ======================================
 *  Discovery methods
 * ====================================== */

void BobinkClient::startDiscovery()
{
    if (m_discoveryUrl.isEmpty() || !m_client)
        return;

    doDiscovery();
    m_discoveryTimer.start(m_discoveryInterval);

    if (!m_discovering) {
        m_discovering = true;
        emit discoveringChanged();
    }
}

void BobinkClient::stopDiscovery()
{
    m_discoveryTimer.stop();

    if (m_discovering) {
        m_discovering = false;
        emit discoveringChanged();
    }
}

void BobinkClient::doDiscovery()
{
    if (!m_client || m_discoveryUrl.isEmpty())
        return;
    QUrl url(m_discoveryUrl);
    if (!url.isValid())
        return;
    m_client->findServers(url);
}

/* ======================================
 *  Private slots
 * ====================================== */

void BobinkClient::handleStateChanged(QOpcUaClient::ClientState state)
{
    bool nowConnected = (state == QOpcUaClient::Connected);
    if (m_connected != nowConnected) {
        m_connected = nowConnected;
        emit connectedChanged();
    }
}

void BobinkClient::handleEndpointsReceived(
    const QList<QOpcUaEndpointDescription> &endpoints,
    QOpcUa::UaStatusCode statusCode, const QUrl &)
{
    if (statusCode != QOpcUa::Good || endpoints.isEmpty()) {
        emit connectionError(QStringLiteral("Failed to retrieve endpoints"));
        return;
    }

    QOpcUaEndpointDescription best = endpoints.first();
    for (const auto &ep : endpoints) {
        if (ep.securityLevel() > best.securityLevel())
            best = ep;
    }

    if (m_auth)
        m_client->setAuthenticationInformation(m_auth->toAuthenticationInformation());

    m_client->connectToEndpoint(best);
}

void BobinkClient::handleConnectError(QOpcUaErrorState *errorState)
{
    if (errorState->connectionStep() ==
        QOpcUaErrorState::ConnectionStep::CertificateValidation) {
        // connectError uses BlockingQueuedConnection — the backend thread is
        // blocked waiting for us to return.  The errorState pointer is stack-
        // allocated in the backend, so it is only valid during this call.
        // Spin a local event loop so QML can show a dialog and call
        // acceptCertificate() / rejectCertificate() while we stay in scope.
        m_certAccepted = false;
        emit certificateTrustRequested(
            QStringLiteral("The server certificate is not trusted. Accept?"));

        QEventLoop loop;
        m_certLoop = &loop;
        QTimer::singleShot(30000, &loop, &QEventLoop::quit);
        loop.exec();
        m_certLoop = nullptr;

        errorState->setIgnoreError(m_certAccepted);
    } else {
        emit connectionError(
            QStringLiteral("Connection error at step %1, code 0x%2")
                .arg(static_cast<int>(errorState->connectionStep()))
                .arg(static_cast<uint>(errorState->errorCode()), 8, 16, QLatin1Char('0')));
    }
}

void BobinkClient::handleFindServersFinished(
    const QList<QOpcUaApplicationDescription> &servers,
    QOpcUa::UaStatusCode statusCode, const QUrl &)
{
    if (statusCode != QOpcUa::Good)
        return;

    m_discoveredServers = servers;
    m_serversCache.clear();
    for (const auto &s : m_discoveredServers) {
        QVariantMap entry;
        entry[QStringLiteral("serverName")] = s.applicationName().text();
        entry[QStringLiteral("applicationUri")] = s.applicationUri();
        entry[QStringLiteral("discoveryUrls")] = QVariant::fromValue(s.discoveryUrls());
        m_serversCache.append(entry);
    }
    emit serversChanged();
}