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
|
/*
* WebApiController.cpp - implementation of WebApiController class
*
* Copyright (c) 2020-2025 Tobias Junghans <tobydox@veyon.io>
*
* This file is part of Veyon - https://veyon.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*/
#include <QTcpSocket>
#include <QBuffer>
#include <QEventLoop>
#include <QImageWriter>
#include "ComputerControlInterface.h"
#include "FeatureManager.h"
#include "PlatformNetworkFunctions.h"
#include "WebApiAuthenticationProxy.h"
#include "WebApiConfiguration.h"
#include "WebApiController.h"
static QString uuidToString( QUuid uuid )
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
return uuid.toString( QUuid::WithoutBraces );
#else
return uuid.toString().remove( QLatin1Char('{') ).remove( QLatin1Char('}') );
#endif
}
WebApiController::WebApiController( const WebApiConfiguration& configuration, QObject* parent ) :
QObject( parent ),
m_configuration( configuration ),
m_connectionsLock( QReadWriteLock::Recursive )
{
connect(&m_updateStatisticsTimer, &QTimer::timeout, this, &WebApiController::updateStatistics);
m_updateStatisticsTimer.start(StatisticsUpdateIntervalSeconds * MillisecondsPerSecond);
m_workerThread = new QThread(this);
m_workerThread->setObjectName(QStringLiteral("WebApiController Worker"));
m_workerThread->start();
m_workerObject = new QObject;
m_workerObject->moveToThread(m_workerThread);
}
WebApiController::~WebApiController()
{
QWriteLocker connectionsWriteLocker{ &m_connectionsLock };
m_connections.clear();
}
WebApiController::Response WebApiController::getHostState(const Request& request, const QString& host)
{
Q_UNUSED(request);
m_apiTotalRequestsCounter++;
QTcpSocket socket;
socket.connectToHost(host, VeyonCore::config().veyonServerPort());
if (socket.waitForConnected(3000))
{
return QVariantMap{{k2s(Key::State), QByteArrayLiteral("online")}};
}
if (VeyonCore::platform().networkFunctions().ping(host) == PlatformNetworkFunctions::PingResult::ReplyReceived)
{
return QByteArrayLiteral("up");
}
return QVariantMap{{k2s(Key::State), QByteArrayLiteral("down")}};
}
WebApiController::Response WebApiController::getAuthenticationMethods( const Request& request, const QString& host )
{
m_apiTotalRequestsCounter++;
Q_UNUSED(request)
WebApiConnection connection( host.isEmpty() ? QStringLiteral("localhost") : host );
const auto proxy = new WebApiAuthenticationProxy( m_configuration );
proxy->populateCredentials( proxy->dummyAuthenticationMethod(), {} );
connection.controlInterface()->start( {}, ComputerControlInterface::UpdateMode::Basic, proxy );
if( proxy->waitForAuthenticationMethods(
m_configuration.connectionAuthenticationTimeout() * MillisecondsPerSecond ) == false )
{
if( proxy->protocolErrorOccurred() )
{
return Error::ProtocolMismatch;
}
vWarning() << "waiting for authentication methods timed out";
return Error::ConnectionTimedOut;
}
const auto authMethodUuids = proxy->authenticationMethods();
QVariantList methods; // clazy:exclude=inefficient-qlist
methods.reserve( authMethodUuids.size() );
for( const auto& authMethodUuid : authMethodUuids )
{
methods.append( uuidToString( authMethodUuid ) );
}
return QVariantMap{ { k2s(Key::Methods), methods } };
}
WebApiController::Response WebApiController::performAuthentication( const Request& request, const QString& host )
{
m_apiTotalRequestsCounter++;
QReadLocker connectionsReadLocker{&m_connectionsLock};
if( m_connections.size() >= m_configuration.connectionLimit() )
{
return Error::ConnectionLimitReached;
}
const auto methodUuid = QUuid( request.data[k2s(Key::Method)].toString() );
if( methodUuid.isNull() )
{
return Error::InvalidData;
}
auto uuid = QUuid::createUuid();
while( m_connections.contains( uuid ) )
{
uuid = QUuid::createUuid();
}
connectionsReadLocker.unlock();
auto proxy = new WebApiAuthenticationProxy( m_configuration );
// create connection (including timer resources) in main thread
auto connection = runInWorkerThread<WebApiConnectionPointer>([this, host, proxy]() {
auto connection = new WebApiConnection{host.isEmpty() ? QStringLiteral("localhost") : host};
connection->controlInterface()->start({}, ComputerControlInterface::UpdateMode::Basic, proxy);
// make shared pointer destroy the connection in management thread again
return WebApiConnectionPointer{connection,
[this](WebApiConnection* c) { runInWorkerThreadNonBlocking([c] { delete c; }); } };
});
const auto authTimeout = m_configuration.connectionAuthenticationTimeout() * MillisecondsPerSecond;
if( proxy->waitForAuthenticationMethods( authTimeout ) == false )
{
vWarning() << "waiting for authentication methods timed out";
return Error::ConnectionTimedOut;
}
if( proxy->protocolErrorOccurred() )
{
return Error::ProtocolMismatch;
}
if( proxy->authenticationMethods().contains( methodUuid ) == false )
{
return Error::AuthenticationMethodNotAvailable;
}
if( proxy->populateCredentials( methodUuid, request.data[k2s(Key::Credentials)].toMap() ) == false )
{
return Error::InvalidCredentials;
}
QEventLoop eventLoop;
QTimer authenticationTimeoutTimer;
static constexpr auto ResultAuthSucceeded = 0;
static constexpr auto ResultAuthFailed = 1;
static constexpr auto ResultAuthTimedOut = 2;
connect( &authenticationTimeoutTimer, &QTimer::timeout, &eventLoop,
[&eventLoop]() { eventLoop.exit(ResultAuthTimedOut); } );
connect( connection->controlInterface().data(), &ComputerControlInterface::stateChanged, &eventLoop,
[&connection, &eventLoop]() { // clazy:exclude=lambda-in-connect
switch( connection->controlInterface()->state() )
{
case ComputerControlInterface::State::AuthenticationFailed:
eventLoop.exit( ResultAuthFailed );
break;
case ComputerControlInterface::State::Connected:
eventLoop.exit( ResultAuthSucceeded );
default:
break;
}
} );
authenticationTimeoutTimer.start( authTimeout );
const auto result = eventLoop.exec() == ResultAuthSucceeded;
if( result )
{
connection->lock();
m_connectionsLock.lockForWrite();
m_connections[uuid] = connection;
m_connectionsLock.unlock();
connect(connection->controlInterface().get(), &ComputerControlInterface::framebufferUpdated,
this, &WebApiController::incrementVncFramebufferUpdatesCounter);
const auto idleTimer = connection->idleTimer();
const auto lifetimeTimer = connection->lifetimeTimer();
connect( idleTimer, &QTimer::timeout, this, [this, uuid]() {
vInfo() << "idle time exceeded for connection" << uuid;
removeConnection(uuid);
} );
connect( lifetimeTimer, &QTimer::timeout, this, [this, uuid]() {
vInfo() << "lifetime exceeded for connection" << uuid;
removeConnection(uuid);
} );
const auto connectionIdleTimeout = m_configuration.connectionIdleTimeout() * MillisecondsPerSecond;
const auto connectionLifetime = m_configuration.connectionLifetime() * MillisecondsPerHour;
connection->unlock();
runInWorkerThread([=] {
idleTimer->start(connectionIdleTimeout);
lifetimeTimer->start(connectionLifetime);
});
return QVariantMap{
{ QString::fromUtf8(connectionUidHeaderFieldName().toLower()), uuidToString(uuid) },
{ k2s(Key::ValidUntil), QDateTime::currentSecsSinceEpoch() + connectionLifetime / MillisecondsPerSecond }
};
}
return Error::AuthenticationFailed;
}
WebApiController::Response WebApiController::closeConnection( const Request& request, const QString& host )
{
m_apiTotalRequestsCounter++;
Q_UNUSED(host)
Response checkResponse{};
if( ( checkResponse = checkConnection( request ) ).error != Error::NoError )
{
return checkResponse;
}
removeConnection(QUuid{lookupHeaderField(request, connectionUidHeaderFieldName())});
return {};
}
WebApiController::Response WebApiController::getFramebuffer( const Request& request )
{
m_apiTotalRequestsCounter++;
Response checkResponse{};
if( ( checkResponse = checkConnection( request ) ).error != Error::NoError )
{
return checkResponse;
}
const auto connection = lookupConnection( request );
if( connection->controlInterface()->hasValidFramebuffer() == false )
{
return Error::FramebufferNotAvailable;
}
m_framebufferRequestsCounter++;
const auto width = request.data[k2s(Key::Width)].toInt();
const auto height = request.data[k2s(Key::Height)].toInt();
const auto size = connection->scaledFramebufferSize( width, height );
const auto compression = request.data[k2s(Key::Compression)].toString().toInt();
const auto quality = request.data[k2s(Key::Quality)].toString().toInt();
auto format = request.data[k2s(Key::Format)].toString().toUtf8();
if( format.isEmpty() )
{
format = QByteArrayLiteral("png");
}
if( QImageWriter::supportedImageFormats().contains( format ) == false )
{
return Error::UnsupportedImageFormat;
}
const auto imageData = connection->encodedFramebufferData( size, format, compression, quality );
if( imageData.isNull() )
{
return { Error::FramebufferEncodingError, connection->framebufferEncodingError() };
}
return imageData;
}
WebApiController::Response WebApiController::listFeatures( const Request& request )
{
m_apiTotalRequestsCounter++;
Response checkResponse{};
if( ( checkResponse = checkConnection( request ) ).error != Error::NoError )
{
return checkResponse;
}
const auto& features = VeyonCore::featureManager().features(); // clazy:exclude=inefficient-qlist
const auto activeFeatures = lookupConnection( request )->controlInterface()->activeFeatures();
QVariantList featureList; // clazy:exclude=inefficient-qlist
featureList.reserve( features.size() );
for( const auto& feature : features )
{
QVariantMap featureObject{ { k2s(Key::Name), feature.name() },
{ k2s(Key::Uid), uuidToString(feature.uid()) },
{ k2s(Key::ParentUid), uuidToString(feature.parentUid()) },
{ k2s(Key::Active), activeFeatures.contains(feature.uid()) } };
featureList.append( featureObject );
}
return featureList;
}
WebApiController::Response WebApiController::setFeatureStatus( const Request& request, const QString& feature )
{
m_apiTotalRequestsCounter++;
Response checkResponse{};
if( ( checkResponse = checkConnection( request ) ).error != Error::NoError ||
( checkResponse = checkFeature( feature ) ).error != Error::NoError )
{
return checkResponse;
}
if( request.data.contains( k2s(Key::Active) ) == false )
{
return Error::InvalidData;
}
const auto connection = lookupConnection( request );
const auto operation = request.data[k2s(Key::Active)].toBool() ? FeatureProviderInterface::Operation::Start
: FeatureProviderInterface::Operation::Stop;
const auto arguments = request.data[k2s(Key::Arguments)].toMap();
runInWorkerThread([&] {
VeyonCore::featureManager().controlFeature(Feature::Uid{feature}, operation, arguments, {connection->controlInterface()});
});
return {};
}
WebApiController::Response WebApiController::getFeatureStatus( const Request& request, const QString& feature )
{
m_apiTotalRequestsCounter++;
Response checkResponse{};
if( ( checkResponse = checkConnection( request ) ).error != Error::NoError )
{
return checkResponse;
}
const auto connection = lookupConnection( request );
const auto controlInterface = connection->controlInterface();
const auto result = controlInterface->activeFeatures().contains(Feature::Uid{feature});
return QVariantMap{ { k2s(Key::Active), result } };
}
WebApiController::Response WebApiController::getUserInformation( const Request& request )
{
m_apiTotalRequestsCounter++;
Response checkResponse{};
if( ( checkResponse = checkConnection( request ) ).error != Error::NoError )
{
return checkResponse;
}
const auto connection = lookupConnection( request );
const auto controlInterface = connection->controlInterface();
const auto& userLoginName = controlInterface->userLoginName();
auto userFullName = controlInterface->userFullName();
if (userLoginName.isEmpty())
{
userFullName.clear();
}
return QVariantMap{
{
{k2s(Key::Login), userLoginName},
{k2s(Key::FullName), userFullName}
}
};
}
WebApiController::Response WebApiController::getSessionInformation(const Request& request)
{
m_apiTotalRequestsCounter++;
Response checkResponse{};
if((checkResponse = checkConnection(request)).error != Error::NoError)
{
return checkResponse;
}
const auto connection = lookupConnection(request);
const auto controlInterface = connection->controlInterface();
return QVariantMap{
{
{k2s(Key::SessionId), controlInterface->sessionInfo().id},
{k2s(Key::SessionUptime), controlInterface->sessionInfo().uptime},
{k2s(Key::SessionClientAddress), controlInterface->sessionInfo().clientAddress},
{k2s(Key::SessionClientName), controlInterface->sessionInfo().clientName},
{k2s(Key::SessionHostName), controlInterface->sessionInfo().hostName},
}
};
}
QString WebApiController::getStatistics()
{
QReadLocker connectionsLocker{&m_connectionsLock};
return QStringLiteral("Total API requests: %1 (%2/s in the past %3 s)\n<br/>").arg(m_apiTotalRequestsCounter).arg(m_apiTotalRequestsPerSecond).arg(StatisticsUpdateIntervalSeconds) +
QStringLiteral("Framebuffer requests: %1 (%2/s in the past %3 s)\n<br/>").arg(m_framebufferRequestsCounter).arg(m_framebufferRequestsPerSecond).arg(StatisticsUpdateIntervalSeconds) +
QStringLiteral("VNC framebuffer updates: %1 (%2/s in the past %3 s)\n<br/>").arg(m_vncFramebufferUpdatesCounter).arg(m_vncFramebufferUpdatesPerSecond).arg(StatisticsUpdateIntervalSeconds) +
QStringLiteral("Number of client connections: %1<br/>\n").arg(m_connections.count());
}
QString WebApiController::getConnectionDetails()
{
QReadLocker connectionsLocker{&m_connectionsLock};
QStringList columns {QStringLiteral("Connection UUID"),
QStringLiteral("State"),
QStringLiteral("Host"),
QStringLiteral("User"),
QStringLiteral("Server version")
};
QList<QStringList> rows;
rows.reserve(m_connections.count());
for (auto it = m_connections.constBegin(), end = m_connections.constEnd(); it != end; ++it)
{
const auto connection = it.value();
rows.append({uuidToString(it.key()),
EnumHelper::toString(connection->controlInterface()->state()),
connection->controlInterface()->computer().hostName(),
connection->controlInterface()->userLoginName(),
EnumHelper::toString(connection->controlInterface()->serverVersion()),
});
}
const auto rowToString = [](const QStringList& row, const QString& tag) {
return std::accumulate(row.constBegin(), row.constEnd(), QString{}, [&tag](const QString& acc, const QString& cell) -> QString {
return acc + QStringLiteral("<%1>%2</%1>").arg(tag, cell);
});
};
const auto tableHeader = QStringLiteral("<tr>%1</tr>\n").arg(rowToString(columns, QStringLiteral("th")));
const auto tableBody = std::accumulate(rows.constBegin(), rows.constEnd(), QString{},
[&](const QString& acc, const QStringList& row) -> QString {
return acc + QStringLiteral("<tr>%1</tr>\n").arg(rowToString(row, QStringLiteral("td")));
});
return QStringLiteral("<table border=\"1\">\n%1%2</table>\n").arg(tableHeader, tableBody);
}
WebApiController::Response WebApiController::sleep(const Request& request, const int& seconds) // clazy:exclude=function-args-by-value
{
Q_UNUSED(request)
m_apiTotalRequestsCounter++;
QThread::sleep(seconds);
return {""};
}
QString WebApiController::errorString( WebApiController::Error error )
{
switch( error )
{
case Error::NoError: return {};
case Error::InvalidData: return QStringLiteral("Invalid data");
case Error::InvalidConnection: return QStringLiteral("Invalid connection");
case Error::InvalidFeature: return QStringLiteral("Invalid feature");
case Error::AuthenticationMethodNotAvailable: return QStringLiteral("Authentication method not offered by server");
case Error::InvalidCredentials: return QStringLiteral("Invalid or incomplete credentials");
case Error::AuthenticationFailed: return QStringLiteral("Authentication failed");
case Error::ConnectionLimitReached: return QStringLiteral("Limit for maximum number of connections reached");
case Error::ConnectionTimedOut: return QStringLiteral("Connection timed out");
case Error::UnsupportedImageFormat: return QStringLiteral("Unsupported image format");
case Error::FramebufferNotAvailable: return QStringLiteral("Framebuffer not yet available");
case Error::FramebufferEncodingError: return QStringLiteral("Framebuffer encoding error");
case Error::ProtocolMismatch: return QStringLiteral("Protocol mismatch error");
}
return {};
}
void WebApiController::runInWorkerThread(const std::function<void()>& functor) const
{
QMetaObject::invokeMethod(m_workerObject, functor, Qt::BlockingQueuedConnection);
}
void WebApiController::runInWorkerThreadNonBlocking(const std::function<void()>& functor) const
{
QMetaObject::invokeMethod(m_workerObject, functor, Qt::QueuedConnection);
}
template<class T>
T WebApiController::runInWorkerThread(const std::function<T()>& functor) const
{
T retval{};
QMetaObject::invokeMethod(m_workerObject, functor, Qt::BlockingQueuedConnection, &retval );
return retval;
}
void WebApiController::removeConnection( QUuid connectionUuid )
{
QWriteLocker connectionsWriteLocker{ &m_connectionsLock };
// deleter functor automatically performs actual deletion in worker thread
m_connections.remove(connectionUuid);
}
void WebApiController::incrementVncFramebufferUpdatesCounter()
{
++m_vncFramebufferUpdatesCounter;
}
void WebApiController::updateStatistics()
{
m_apiTotalRequestsPerSecond = (m_apiTotalRequestsCounter - m_apiTotalRequestsLast) / StatisticsUpdateIntervalSeconds;
m_framebufferRequestsPerSecond = (m_framebufferRequestsCounter - m_framebufferRequestsLast) / StatisticsUpdateIntervalSeconds;
m_vncFramebufferUpdatesPerSecond = (m_vncFramebufferUpdatesCounter - m_vncFramebufferUpdatesLast) / StatisticsUpdateIntervalSeconds;
m_apiTotalRequestsLast = m_apiTotalRequestsCounter;
m_framebufferRequestsLast = m_framebufferRequestsCounter;
m_vncFramebufferUpdatesLast = m_vncFramebufferUpdatesCounter;
}
QByteArray WebApiController::lookupHeaderField(const Request& request, const QByteArray& fieldName)
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
for (const auto& h : request.headers)
{
if (h.first.compare(fieldName, Qt::CaseInsensitive) == 0)
{
return h.second;
}
}
#else
const auto fieldNameString = QString::fromUtf8(fieldName);
if (request.headers.contains(fieldNameString))
{
return request.headers[fieldNameString].toByteArray();
}
for (auto it = request.headers.constBegin(), end = request.headers.constEnd(); it != end; ++it)
{
if (it.key().compare(fieldNameString, Qt::CaseInsensitive ) == 0)
{
return it.value().toByteArray();
}
}
#endif
return {};
}
WebApiController::LockingConnectionPointer WebApiController::lookupConnection( const Request& request )
{
QReadLocker connectionsReadLocker{&m_connectionsLock};
return m_connections.value(QUuid{lookupHeaderField(request, connectionUidHeaderFieldName())});
}
WebApiController::Response WebApiController::checkConnection( const Request& request )
{
const QUuid connectionUuid{lookupHeaderField(request, connectionUidHeaderFieldName())};
return runInWorkerThread<WebApiController::Response>([=]() -> WebApiController::Response {
m_connectionsLock.lockForRead();
if( connectionUuid.isNull() || m_connections.contains( connectionUuid ) == false )
{
m_connectionsLock.unlock();
return Error::InvalidConnection;
}
const auto connection = std::as_const(m_connections)[connectionUuid];
m_connectionsLock.unlock();
connection->lock();
const auto idleTimer = connection->idleTimer();
idleTimer->stop();
idleTimer->start();
connection->unlock();
return {};
} );
}
WebApiController::Response WebApiController::checkFeature( const QString& featureUid )
{
if( VeyonCore::featureManager().feature(Feature::Uid{featureUid}).isValid() == false )
{
return Error::InvalidFeature;
}
return {};
}
|