From 4bda78d4269cffdf174b2ee70c0d061b22beaa5e Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Mon, 9 Nov 2026 15:19:15 +0000 Subject: [PATCH 01/21] Convert host and SRV lookups to async instead of blocking Also use direct parsing of literal IP addresses. --- src/client.cpp | 63 +++++---- src/client.h | 2 +- src/clientdlg.cpp | 33 +++-- src/clientdlg.h | 1 + src/clientrpc.cpp | 36 ++++- src/connectdlg.cpp | 56 +++++--- src/connectdlg.h | 1 + src/serverdlg.cpp | 33 +++-- src/serverdlg.h | 3 + src/serverlist.cpp | 86 ++++++++---- src/serverlist.h | 3 + src/util.cpp | 328 ++++++++++++++++++++++++++++----------------- src/util.h | 38 +++++- 13 files changed, 459 insertions(+), 224 deletions(-) diff --git a/src/client.cpp b/src/client.cpp index 9b5e502bee..645da46bd2 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -619,25 +619,6 @@ void CClient::SetRemoteChanPan ( const int iId, const float fPan ) StartTimerGainOrPan(); } -bool CClient::SetServerAddr ( QString strNAddr ) -{ - CHostAddress HostAddress; - if ( NetworkUtil::ParseNetworkAddress ( strNAddr, HostAddress, bIPv6Available ) ) - { - // apply address to the channel - Channel.SetAddress ( HostAddress ); - - // By default, set server name to HostAddress. If using the Connect() method, this may be overwritten - SetConnectedServerName ( HostAddress.toString() ); - - return true; - } - else - { - return false; // invalid address - } -} - bool CClient::GetAndResetbJitterBufferOKFlag() { // get the socket buffer put status flag and reset it @@ -1162,7 +1143,7 @@ void CClient::Disconnect() /// @method /// @brief Connects to strServerAddress. If a connection is currently requested /// or established, that connection is terminated first. -/// @emit Connecting (strServerName) if SetServerAddr was valid. emit happens through Start(). +/// @emit Connecting (strServerName) if address was valid. emit happens through Start(). /// Use to set CClientDlg to show being connected /// @emit ConnectingFailed (error) if an error occurred /// Use to display error message in CClientDlg @@ -1176,24 +1157,54 @@ void CClient::Connect ( const QString& strServerAddress, const QString& strServe // different server while connected behaves as a reconnect Disconnect(); - // Set server address and connect if valid address was supplied - if ( SetServerAddr ( strServerAddress ) ) + if ( NetworkUtil::ResolveAddress ( strServerAddress, bIPv6Available, this, &CClient::OnHostResolved, true, true ) ) { - SetConnectedServerName ( strServerName ); - Start(); + SetConnectedServerName ( strServerName ); // set if resolution initiated ok } else { - throw CGenErr ( tr ( "Received invalid server address. Please check for typos in the provided server address." ) ); + emit ConnectingFailed ( tr ( "Received invalid server address. Please check for typos in the provided server address." ) ); } } catch ( const CGenErr& generr ) { - Stop(); + // Stop(); // XXX: probably not needed? emit ConnectingFailed ( generr.GetErrorText() ); } } +void CClient::OnHostResolved ( const QHostInfo& info, quint16 port ) +{ + if ( info.error() != QHostInfo::NoError ) + { + emit ConnectingFailed ( "Cannot connect: " + info.errorString() ); + return; + } + + for ( const QHostAddress& HostAddr : info.addresses() ) + { + // qInfo() << "Resolved network address to" << HostAddr << "for proto" << HostAddr.protocol(); + if ( HostAddr.protocol() == QAbstractSocket::IPv4Protocol || ( HostAddr.protocol() == QAbstractSocket::IPv6Protocol && bIPv6Available ) ) + { + CHostAddress HostAddress ( HostAddr, port ); + Channel.SetAddress ( HostAddress ); + // sound device start can throw an exception, which we must catch here + try + { + Start(); + } + catch ( const CGenErr& generr ) + { + Stop(); + emit ConnectingFailed ( generr.GetErrorText() ); + } + return; + } + } + + emit ConnectingFailed ( "Hostname returned no usable addresses" ); +} + /// @method /// @brief Updates the connection state and, if it changed, notifies observers. /// @emit ConnectionStateChanged (state) when the state actually changes diff --git a/src/client.h b/src/client.h index 1c4c4e5428..d692df8fe4 100644 --- a/src/client.h +++ b/src/client.h @@ -180,7 +180,6 @@ class CClient : public QObject bool IsRunning() { return Sound.IsRunning(); } bool IsCallbackEntered() const { return Sound.IsCallbackEntered(); } - bool SetServerAddr ( QString strNAddr ); // IPv6 Available bool IsIPv6Available() { return bIPv6Available; } @@ -514,6 +513,7 @@ protected slots: void OnMuteStateHasChangedReceived ( int iServerChanID, bool bIsMuted ); void OnCLChannelLevelListReceived ( CHostAddress InetAddr, CVector vecLevelList ); void OnConClientListMesReceived ( CVector vecChanInfo ); + void OnHostResolved ( const QHostInfo& info, quint16 port ); signals: void ConClientListMesReceived ( CVector vecChanInfo ); diff --git a/src/clientdlg.cpp b/src/clientdlg.cpp index 2c7c35f02c..34e95ff2dd 100644 --- a/src/clientdlg.cpp +++ b/src/clientdlg.cpp @@ -605,21 +605,38 @@ CClientDlg::CClientDlg ( CClient* pNCliP, // that the connection less message respond may not make it back but that // is not critical since the next time Jamulus is started we have another // chance and the update check is not time-critical at all) - CHostAddress UpdateServerHostAddress; - - // Send the request to two servers for redundancy if either or both of them - // has a higher release version number, the reply will trigger the notification. // Don't use SRV resolution when resolving update servers. + if ( !NetworkUtil::ResolveAddress ( UPDATECHECK1_ADDRESS, pClient->IsIPv6Available(), this, &CClientDlg::OnHostResolved, true, false ) ) + { + qWarning() << "Cannot start update check for" << UPDATECHECK1_ADDRESS; + } + + if ( !NetworkUtil::ResolveAddress ( UPDATECHECK2_ADDRESS, pClient->IsIPv6Available(), this, &CClientDlg::OnHostResolved, true, false ) ) + { + qWarning() << "Cannot start update check for" << UPDATECHECK2_ADDRESS; + } +} - if ( NetworkUtil::ParseNetworkAddressBare ( UPDATECHECK1_ADDRESS, UpdateServerHostAddress, pClient->IsIPv6Available() ) ) +void CClientDlg::OnHostResolved ( const QHostInfo& info, quint16 port ) +{ + if ( info.error() != QHostInfo::NoError ) { - pClient->CreateCLServerListReqVerAndOSMes ( UpdateServerHostAddress ); + qWarning() << "Update lookup failed:" << info.errorString(); + return; } - if ( NetworkUtil::ParseNetworkAddressBare ( UPDATECHECK2_ADDRESS, UpdateServerHostAddress, pClient->IsIPv6Available() ) ) + for ( const QHostAddress& HostAddr : info.addresses() ) { - pClient->CreateCLServerListReqVerAndOSMes ( UpdateServerHostAddress ); + // qInfo() << "Resolved network address to" << HostAddr << "for proto" << HostAddr.protocol(); + if ( HostAddr.protocol() == QAbstractSocket::IPv4Protocol || + ( HostAddr.protocol() == QAbstractSocket::IPv6Protocol && pClient->IsIPv6Available() ) ) + { + CHostAddress HostAddress ( HostAddr, port ); + + pClient->CreateCLServerListReqVerAndOSMes ( HostAddress ); + return; + } } } diff --git a/src/clientdlg.h b/src/clientdlg.h index b127231b27..b7da510e05 100644 --- a/src/clientdlg.h +++ b/src/clientdlg.h @@ -260,6 +260,7 @@ public slots: void SetMixerBoardDeco ( const ERecorderState newRecorderState, const EGUIDesign eNewDesign ); void OnAudioChannelsChanged() { UpdateRevSelection(); } void OnNumClientsChanged ( int iNewNumClients ); + void OnHostResolved ( const QHostInfo& info, quint16 port ); void accept() { close(); } // introduced by pljones diff --git a/src/clientrpc.cpp b/src/clientrpc.cpp index 67f46a9843..ed8d728c7a 100644 --- a/src/clientrpc.cpp +++ b/src/clientrpc.cpp @@ -187,18 +187,42 @@ CClientRpc::CClientRpc ( CClient* pClient, CClientSettings* pSettings, CRpcServe return; } - CHostAddress haDirectoryAddress; - - // Allow IPv4 only for communicating with Directories - if ( !NetworkUtil::ParseNetworkAddress ( jsonDirectoryIp.toString(), haDirectoryAddress, false ) ) + // Start asynchronous address resolution with lambda callback slot + bool accepted = NetworkUtil::ResolveAddress ( + jsonDirectoryIp.toString(), + false, // Currently IPv4 only for directories + pClient, + [pClient] ( const QHostInfo& info, quint16 port ) { + // this callback runs later, after the RPC handler has returned + if ( info.error() != QHostInfo::NoError ) + { + qWarning() << "Directory lookup failed:" << info.errorString(); + return; + } + + // select a usable IPv4 address + for ( const QHostAddress& addr : info.addresses() ) + { + if ( addr.protocol() == QAbstractSocket::IPv4Protocol ) + { + CHostAddress haDirectoryAddress ( addr, port ); + + pClient->CreateCLReqServerListMes ( haDirectoryAddress ); + return; + } + } + qWarning() << "No usable address found for directory"; + }, + true, // allow hostname lookup + true ); // allow SRV lookup + + if ( !accepted ) { response["error"] = CRpcServer::CreateJsonRpcError ( CRpcServer::iErrInvalidParams, "Invalid params: directory is not a valid socket address" ); return; } - // send the request for the server list - pClient->CreateCLReqServerListMes ( haDirectoryAddress ); response["result"] = "ok"; } ); diff --git a/src/connectdlg.cpp b/src/connectdlg.cpp index 103d4d9193..9b5a9595e2 100644 --- a/src/connectdlg.cpp +++ b/src/connectdlg.cpp @@ -312,24 +312,48 @@ void CConnectDlg::RequestServerList() } cbxDirectory->blockSignals ( false ); - // Get the IP address of the directory server (using the ParseNetworkAddress + // Get the IP address of the directory server (using the async ResolveAddress // function) when the connect dialog is opened, this seems to be the correct // time to do it. Note that in case of custom directories we // use iCustomDirectoryIndex as an index into the vector. - // Allow IPv4 only for communicating with Directories - if ( NetworkUtil::ParseNetworkAddress ( - NetworkUtil::GetDirectoryAddress ( pSettings->eDirectoryType, pSettings->vstrDirectoryAddress[pSettings->iCustomDirectoryIndex] ), - haDirectoryAddress, - false ) ) + // Currently allow only IPv4 for communicating with Directories + + const QString strDirectoryAddress = + NetworkUtil::GetDirectoryAddress ( pSettings->eDirectoryType, pSettings->vstrDirectoryAddress[pSettings->iCustomDirectoryIndex] ); + + if ( !NetworkUtil::ResolveAddress ( strDirectoryAddress, pClient->IsIPv6Available(), this, &CConnectDlg::OnHostResolved, true, true ) ) { - // send the request for the server list - emit ReqServerListQuery ( haDirectoryAddress ); + qWarning() << "Cannot start directory fetch from" << strDirectoryAddress; + } +} - // start timer, if this message did not get any respond to retransmit - // the server list request message - TimerReRequestServList.start ( SERV_LIST_REQ_UPDATE_TIME_MS ); - TimerInitialSort.start ( SERV_LIST_REQ_UPDATE_TIME_MS ); // reuse the time value +void CConnectDlg::OnHostResolved ( const QHostInfo& info, quint16 port ) +{ + if ( info.error() != QHostInfo::NoError ) + { + qWarning() << "Directory lookup failed:" << info.errorString(); + return; + } + + for ( const QHostAddress& HostAddr : info.addresses() ) + { + // qInfo() << "Resolved network address to" << HostAddr << "for proto" << HostAddr.protocol(); + if ( HostAddr.protocol() == QAbstractSocket::IPv4Protocol /* || + ( HostAddr.protocol() == QAbstractSocket::IPv6Protocol && pClient->IsIPv6Available() ) */ ) + { + haDirectoryAddress = CHostAddress ( HostAddr, port ); + + // send the request for the server list + emit ReqServerListQuery ( haDirectoryAddress ); + + // start timer, if this message did not get any respond to retransmit + // the server list request message + TimerReRequestServList.start ( SERV_LIST_REQ_UPDATE_TIME_MS ); + TimerInitialSort.start ( SERV_LIST_REQ_UPDATE_TIME_MS ); // reuse the time value + + return; + } } } @@ -855,10 +879,10 @@ void CConnectDlg::OnTimerPing() // try to parse host address string which is stored as user data // in the server list item GUI control element - // the data to be parsed is just IP:port, so no SRV discovery is needed - if ( NetworkUtil::ParseNetworkAddressBare ( pCurListViewItem->data ( LVC_NAME, Qt::UserRole ).toString(), - haServerAddress, - pClient->IsIPv6Available() ) ) + // the data to be parsed is just IP:port, so no hostname lookup is needed + if ( NetworkUtil::ParseAddressLiteral ( pCurListViewItem->data ( LVC_NAME, Qt::UserRole ).toString(), + pClient->IsIPv6Available(), + haServerAddress ) ) { // if address is valid, send ping message using a new thread #if QT_VERSION >= QT_VERSION_CHECK( 6, 0, 0 ) diff --git a/src/connectdlg.h b/src/connectdlg.h index 0b2eb8d7ae..cf77a2b9f6 100644 --- a/src/connectdlg.h +++ b/src/connectdlg.h @@ -157,6 +157,7 @@ public slots: void OnTimerPing(); void OnTimerReRequestServList(); void OnCurrentServerItemChanged ( QTreeWidgetItem* current, QTreeWidgetItem* previous ); + void OnHostResolved ( const QHostInfo& info, quint16 port ); signals: void ReqServerListQuery ( CHostAddress InetAddr ); diff --git a/src/serverdlg.cpp b/src/serverdlg.cpp index 5e1dbe5274..cc41324a0d 100644 --- a/src/serverdlg.cpp +++ b/src/serverdlg.cpp @@ -499,21 +499,38 @@ CServerDlg::CServerDlg ( CServer* pNServP, CServerSettings* pNSetP, const bool b // that the connection less message respond may not make it back but that // is not critical since the next time Jamulus is started we have another // chance and the update check is not time-critical at all) - CHostAddress UpdateServerHostAddress; - - // Send the request to two servers for redundancy if either or both of them - // has a higher release version number, the reply will trigger the notification. // Don't use SRV resolution when resolving update servers. + if ( !NetworkUtil::ResolveAddress ( UPDATECHECK1_ADDRESS, pServer->IsIPv6Available(), this, &CServerDlg::OnHostResolved, true, false ) ) + { + qWarning() << "Cannot start update check for" << UPDATECHECK1_ADDRESS; + } - if ( NetworkUtil::ParseNetworkAddressBare ( UPDATECHECK1_ADDRESS, UpdateServerHostAddress, pServer->IsIPv6Available() ) ) + if ( !NetworkUtil::ResolveAddress ( UPDATECHECK2_ADDRESS, pServer->IsIPv6Available(), this, &CServerDlg::OnHostResolved, true, false ) ) { - pServer->CreateCLServerListReqVerAndOSMes ( UpdateServerHostAddress ); + qWarning() << "Cannot start update check for" << UPDATECHECK2_ADDRESS; } +} - if ( NetworkUtil::ParseNetworkAddressBare ( UPDATECHECK2_ADDRESS, UpdateServerHostAddress, pServer->IsIPv6Available() ) ) +void CServerDlg::OnHostResolved ( const QHostInfo& info, quint16 port ) +{ + if ( info.error() != QHostInfo::NoError ) { - pServer->CreateCLServerListReqVerAndOSMes ( UpdateServerHostAddress ); + qWarning() << "Update lookup failed:" << info.errorString(); + return; + } + + for ( const QHostAddress& HostAddr : info.addresses() ) + { + // qinfo() << "Resolved network address to" << HostAddr << "for proto" << HostAddr.protocol(); + if ( HostAddr.protocol() == QAbstractSocket::IPv4Protocol || + ( HostAddr.protocol() == QAbstractSocket::IPv6Protocol && pServer->IsIPv6Available() ) ) + { + CHostAddress HostAddress ( HostAddr, port ); + + pServer->CreateCLServerListReqVerAndOSMes ( HostAddress ); + return; + } } } diff --git a/src/serverdlg.h b/src/serverdlg.h index 80d427a4fe..38cc5ee8b7 100644 --- a/src/serverdlg.h +++ b/src/serverdlg.h @@ -149,4 +149,7 @@ public slots: // Our timer void OnTimer(); + + // From ResolveAddress() + void OnHostResolved ( const QHostInfo& info, quint16 port ); }; diff --git a/src/serverlist.cpp b/src/serverlist.cpp index 0dafa73863..023bd0de31 100644 --- a/src/serverlist.cpp +++ b/src/serverlist.cpp @@ -87,15 +87,15 @@ CServerListEntry CServerListEntry::parse ( QString strHAddr, bool bIPv6Available ) { CHostAddress haServerHostAddr; - NetworkUtil::ParseNetworkAddress ( strHAddr, haServerHostAddr, bIPv6Available ); - if ( CHostAddress() == haServerHostAddr ) + CHostAddress haServerLocalAddr; + + if ( !NetworkUtil::ParseAddressLiteral ( strHAddr, bIPv6Available, haServerHostAddr ) || + !NetworkUtil::ParseAddressLiteral ( strLHAddr, bIPv6Available, haServerLocalAddr ) || CHostAddress() == haServerHostAddr ) { // do not proceed without server host address! return CServerListEntry(); } - CHostAddress haServerLocalAddr; - NetworkUtil::ParseNetworkAddress ( strLHAddr, haServerLocalAddr, bIPv6Available ); if ( haServerLocalAddr.iPort == 0 ) { haServerLocalAddr.iPort = haServerHostAddr.iPort; @@ -827,9 +827,13 @@ bool CServerListManager::Load() continue; } - // This uses ParseNetworkAddressBare because it is just parsing ip:host that was saved to the file. - // Therefore no SRV lookup is appropriate. - NetworkUtil::ParseNetworkAddressBare ( slLine[0], haServerHostAddr, pServer->IsIPv6Available() ); + // This uses ParseAddressLiteral because it is just parsing ip:host that was saved to the file. + if ( !NetworkUtil::ParseAddressLiteral ( slLine[0], pServer->IsIPv6Available(), haServerHostAddr ) ) + { + qWarning() << "Skipping invalid host entry for" << slLine[0]; + continue; + } + int iIdx = IndexOf ( haServerHostAddr ); if ( iIdx != INVALID_INDEX ) { @@ -999,6 +1003,18 @@ void CServerListManager::SetRegistered ( const bool bIsRegister ) return; } + // If we are unregistering from a directory we previously registered to, + // just use the saved address from registering, without address resolution. + + if ( !bIsRegister ) + { + // unregister server if it is registered - regardless of success of parse + SetSvrRegStatus ( SRS_NOT_REGISTERED ); + + pConnLessProtocol->CreateCLUnregisterServerMes ( DirectoryAddress ); + return; + } + // It is very important to unlock the Mutex before doing address resolution, // so that the event loop can run and any other timers that need the mutex // can obtain it. Otherwise there is the possibility of deadlock when doing @@ -1011,39 +1027,53 @@ void CServerListManager::SetRegistered ( const bool bIsRegister ) // changed in the meanwhile. // Allow IPv4 only for communicating with Directories // Use SRV DNS discovery for directory connections, fallback to A/AAAA if none. - const QString strNetworkAddress = NetworkUtil::GetDirectoryAddress ( DirectoryType, strDirectoryAddress ); - const bool bDirectoryAddressValid = NetworkUtil::ParseNetworkAddress ( strNetworkAddress, DirectoryAddress, false ); + const QString strNetworkAddress = NetworkUtil::GetDirectoryAddress ( DirectoryType, strDirectoryAddress ); + + // allow hostname resolution and SRV resolution + const bool bDirectoryAddressValid = + NetworkUtil::ResolveAddress ( strNetworkAddress, false, this, &CServerListManager::OnHostResolved, true, true ); // lock the mutex again now that the address has been resolved. locker.relock(); - if ( bIsRegister ) + if ( !bDirectoryAddressValid ) { - if ( bDirectoryAddressValid ) - { - // register server - SetSvrRegStatus ( SRS_REQUESTED ); + SetSvrRegStatus ( SRS_BAD_ADDRESS ); + } +} - // For a registered server, the server properties are stored in the - // very first item in the server list (which is actually no server list - // but just one item long for the registered server). - pConnLessProtocol->CreateCLRegisterServerExMes ( DirectoryAddress, ServerList[0].LHostAddr, ServerList[0] ); - } - else +void CServerListManager::OnHostResolved ( const QHostInfo& info, quint16 port ) +{ + QMutexLocker locker ( &Mutex ); + + if ( info.error() == QHostInfo::NoError ) + { + for ( const QHostAddress& HostAddr : info.addresses() ) { - SetSvrRegStatus ( SRS_BAD_ADDRESS ); + // qInfo() << "Resolved network address to" << HostAddr << "for proto" << HostAddr.protocol(); + if ( HostAddr.protocol() == QAbstractSocket::IPv4Protocol /* || + ( HostAddr.protocol() == QAbstractSocket::IPv6Protocol && pServer->IsIPv6Available() ) */ ) + { + DirectoryAddress = CHostAddress ( HostAddr, port ); + + // register server + SetSvrRegStatus ( SRS_REQUESTED ); + + // For a registered server, the server properties are stored in the + // very first item in the server list (which is actually no server list + // but just one item long for the registered server). + pConnLessProtocol->CreateCLRegisterServerExMes ( DirectoryAddress, ServerList[0].LHostAddr, ServerList[0] ); + return; + } } + qWarning() << "Directory lookup failed: Hostname returned no usable addresses"; } else { - // unregister server if it is registered - regardless of success of parse - SetSvrRegStatus ( SRS_NOT_REGISTERED ); - - if ( bDirectoryAddressValid ) - { - pConnLessProtocol->CreateCLUnregisterServerMes ( DirectoryAddress ); - } + qWarning() << "Directory lookup failed:" << info.errorString(); } + + SetSvrRegStatus ( SRS_BAD_ADDRESS ); } void CServerListManager::SetSvrRegStatus ( ESvrRegStatus eNSvrRegStatus ) diff --git a/src/serverlist.h b/src/serverlist.h index f18c40678d..afb3ad2b82 100644 --- a/src/serverlist.h +++ b/src/serverlist.h @@ -256,6 +256,9 @@ public slots: void OnAboutToQuit(); + // From ResolveAddress() + void OnHostResolved ( const QHostInfo& info, quint16 port ); + signals: void SvrRegStatusChanged(); }; diff --git a/src/util.cpp b/src/util.cpp index 39efa10a16..637418dac3 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -855,112 +855,57 @@ void PlayAudioAlert ( QUrl soundUrl ) * Other Classes * \******************************************************************************/ // Network utility functions --------------------------------------------------- -bool NetworkUtil::ParseNetworkAddressString ( QString strAddress, QHostAddress& InetAddr, const bool bIPv6Available ) -{ - // try to get host by name, assuming - // that the string contains a valid host name string or IP address - const QHostInfo HostInfo = QHostInfo::fromName ( strAddress ); - - if ( HostInfo.error() != QHostInfo::NoError ) - { - // qInfo() << qUtf8Printable ( QString ( "Invalid hostname" ) ); - return false; // invalid address - } - - foreach ( const QHostAddress HostAddr, HostInfo.addresses() ) - { - // qInfo() << qUtf8Printable ( QString ( "Resolved network address to %1 for proto %2" ) .arg ( HostAddr.toString() ) .arg ( - // HostAddr.protocol() ) ); - if ( HostAddr.protocol() == QAbstractSocket::IPv4Protocol || ( bIPv6Available && HostAddr.protocol() == QAbstractSocket::IPv6Protocol ) ) - { - InetAddr = HostAddr; - return true; - } - } - return false; -} -#ifndef DISABLE_SRV_DNS -bool NetworkUtil::ParseNetworkAddressSrv ( QString strAddress, CHostAddress& HostAddress, const bool bIPv6Available ) +static void resolveHostname ( const QString& strHostname, + const quint16 port, + QObject* context, + std::function slot ) { - // init requested host address with invalid address first - HostAddress = CHostAddress(); - - QRegularExpression plainHostRegex ( "^([^\\[:0-9.][^:]*)$" ); - if ( plainHostRegex.match ( strAddress ).capturedStart() != 0 ) - { - // not a plain hostname? then don't attempt SRV lookup and fail - // immediately. - return false; - } - - QDnsLookup* dns = new QDnsLookup(); - dns->setType ( QDnsLookup::SRV ); - dns->setName ( QString ( "_jamulus._udp.%1" ).arg ( strAddress ) ); - dns->lookup(); - // QDnsLookup::lookup() works asynchronously. Therefore, wait for - // it to complete here by resuming the main loop here. - // This is not nice and blocks the UI, but is similar to what - // the regular resolve function does as well. - QTime dieTime = QTime::currentTime().addMSecs ( DNS_SRV_RESOLVE_TIMEOUT_MS ); - while ( QTime::currentTime() < dieTime && !dns->isFinished() ) - { - QCoreApplication::processEvents ( QEventLoop::ExcludeUserInputEvents, 100 ); - } - QList records = dns->serviceRecords(); - dns->deleteLater(); - if ( records.length() != 1 ) - { - return false; - } - QDnsServiceRecord record = records.first(); - if ( record.target() == "." || record.target() == "" ) - { - // RFC2782 says that "." indicates that the service is not available. - // Qt strips the trailing dot, which is why we check for empty string - // as well. Therefore, the "." part might be redundant, but this would - // need further testing to confirm. - // End processing here (= return true), but pass back an - // invalid HostAddress to let the connect logic fail properly. - HostAddress = CHostAddress ( QHostAddress ( "." ), 0 ); - return true; - } - qDebug() << qUtf8Printable ( - QString ( "resolved %1 to a single SRV record: %2:%3" ).arg ( strAddress ).arg ( record.target() ).arg ( record.port() ) ); - - QHostAddress InetAddr; - if ( ParseNetworkAddressString ( record.target(), InetAddr, bIPv6Available ) ) - { - HostAddress = CHostAddress ( InetAddr, record.port() ); - return true; - } - return false; + QHostInfo::lookupHost ( strHostname, context, [slot, port] ( const QHostInfo& info ) { slot ( info, port ); } ); } -#endif -bool NetworkUtil::ParseNetworkAddress ( QString strAddress, CHostAddress& HostAddress, const bool bIPv6Available ) +static bool validateHostnameFormat ( const QString& strHostname ) { -#ifndef DISABLE_SRV_DNS - // Try SRV-based discovery first: - if ( ParseNetworkAddressSrv ( strAddress, HostAddress, bIPv6Available ) ) - { - return true; - } -#endif - // Try regular connect via plain IP or host name lookup (A/AAAA): - return ParseNetworkAddressBare ( strAddress, HostAddress, bIPv6Available ); + // Validate hostname format before trying to resolve: + // (all matches are non-greedy) + static const QRegularExpression plainHostRegex ( + // # beginning of string + "^" + // # doesn't contain underscore (this is so that we can use \w later on for [A-Za-z0-9]) + "(?!.*?_)" + // # doesn't contain two dots in a row + "(?!.*?\\.\\.)" + // # doesn't have only digits in the last element (also eliminates raw IP addresses) + "(?!.*\\.\\d+\\.?$)" + // # doesn't contain dash at the beginning of a label + "(?!(?:\\w+?\\.)?-[\\w\\.\\-]*?)" + // # doesn't contain dash at the end of a label + "(?!\\w+?-\\.(?:[\\w\\.\\-]+?))" + // # starts with an alphanumeric char + "(?=\\w)" + // # not longer than 253 chars + "(?![\\w\\.\\-]{254})" + // # doesn't contain a label longer than 63 char + "(?!.*?[\\w\\-]{64})" + // # allowed chars alphanumeric, dot and dash + "[\\w\\.\\-]+?" + // # end of string + "$" ); + + auto match = plainHostRegex.match ( strHostname ); + + return match.hasMatch(); } -bool NetworkUtil::ParseNetworkAddressBare ( QString strAddress, CHostAddress& HostAddress, const bool bIPv6Available ) +static bool parseHostAndPort ( const QString& strAddress, bool& bLiteralAddrOut, QString& strHostOut, QString& strPortOut, quint16& iNetPortOut ) { - QHostAddress InetAddr; - unsigned int iNetPort = DEFAULT_PORT_NUMBER; + quint16 iNetPort = DEFAULT_PORT_NUMBER; + QString strHost; + QString strPort; + bool bLiteralAddr = false; // qInfo() << qUtf8Printable ( QString ( "Parsing network address %1" ).arg ( strAddress ) ); - // init requested host address with invalid address first - HostAddress = CHostAddress(); - // Allow the following address formats: // [addr4or6] // [addr4or6]:port @@ -970,79 +915,212 @@ bool NetworkUtil::ParseNetworkAddressBare ( QString strAddress, CHostAddress& Ho // hostname:port // (where addr4or6 is a literal IPv4 or IPv6 address, and addr4 is a literal IPv4 address - bool bLiteralAddr = false; - QRegularExpression rx1 ( "^\\[([^]]*)\\](?::(\\d+))?$" ); // [addr4or6] or [addr4or6]:port - QRegularExpression rx2 ( "^([^:]*)(?::(\\d+))?$" ); // addr4 or addr4:port or host or host:port - - QString strPort; + static const QRegularExpression rx1 ( "^\\[([^]]+)\\](?::(\\d+))?$" ); // [addr4or6] or [addr4or6]:port + static const QRegularExpression rx2 ( "^([^:]+)(?::(\\d+))?$" ); // addr4 or addr4:port or host or host:port QRegularExpressionMatch rx1match = rx1.match ( strAddress ); QRegularExpressionMatch rx2match = rx2.match ( strAddress ); // parse input address with rx1 and rx2 in turn, capturing address/host and port - if ( rx1match.capturedStart() == 0 ) + if ( rx1match.hasMatch() ) { // literal address within [] - strAddress = rx1match.captured ( 1 ); + strHost = rx1match.captured ( 1 ); strPort = rx1match.captured ( 2 ); bLiteralAddr = true; // don't allow hostname within [] } - else if ( rx2match.capturedStart() == 0 ) + else if ( rx2match.hasMatch() ) { // hostname or IPv4 address - strAddress = rx2match.captured ( 1 ); - strPort = rx2match.captured ( 2 ); + strHost = rx2match.captured ( 1 ); + strPort = rx2match.captured ( 2 ); } else { // invalid format - // qInfo() << qUtf8Printable ( QString ( "Invalid address format" ) ); + // qInfo() << "Invalid address format"; return false; } if ( !strPort.isEmpty() ) { // a port number was given: extract port number - iNetPort = strPort.toInt(); + bool ok; + unsigned int port = strPort.toUInt ( &ok ); - if ( iNetPort >= 65536 ) + if ( !ok || port == 0 || port >= 65536 ) { // invalid port number - // qInfo() << qUtf8Printable ( QString ( "Invalid port number specified" ) ); + // qInfo() << "Invalid port number specified"; return false; } + + iNetPort = static_cast ( port ); } - // first try if this is an IP number an can directly applied to QHostAddress - if ( InetAddr.setAddress ( strAddress ) ) + // valid split and port number + bLiteralAddrOut = bLiteralAddr; + strHostOut = strHost; + strPortOut = strPort; + iNetPortOut = iNetPort; + return true; +} + +// parse literal address and optional port with no hostname lookup and address returned directly +bool NetworkUtil::ParseAddressLiteral ( const QString& strAddress, const bool bIPv6Available, CHostAddress& haHostAddress ) +{ + QHostAddress InetAddr; + quint16 iNetPort; + QString strHost; + QString strPort; + bool bLiteralAddr; + + if ( !parseHostAndPort ( strAddress, bLiteralAddr, strHost, strPort, iNetPort ) ) + { + return false; + } + + // try if this is an IP number and can directly applied to QHostAddress + if ( InetAddr.setAddress ( strHost ) ) { - if ( !bIPv6Available && InetAddr.protocol() == QAbstractSocket::IPv6Protocol ) + if ( InetAddr.protocol() == QAbstractSocket::IPv6Protocol && !bIPv6Available ) { // do not allow IPv6 addresses if not enabled - // qInfo() << qUtf8Printable ( QString ( "IPv6 addresses disabled" ) ); + // qInfo() << "IPv6 addresses disabled"; return false; } + + haHostAddress = CHostAddress ( InetAddr, iNetPort ); + return true; } - else + + // qInfo() << "Invalid literal IP address"; + return false; // invalid address +} + +// ResolveAddress() with resolved address(es) returned asynchronously in a slot function +bool NetworkUtil::ResolveAddress ( const QString& strAddress, + const bool bIPv6Available, + QObject* context, + std::function slot, + const bool allowHostname, + const bool allowSrv ) +{ + QHostAddress InetAddr; + quint16 iNetPort; + QString strHost; + QString strPort; + bool bLiteralAddr; + + if ( !parseHostAndPort ( strAddress, bLiteralAddr, strHost, strPort, iNetPort ) ) { - // it was no valid IP address. If literal required, return as invalid - if ( bLiteralAddr ) - { - // qInfo() << qUtf8Printable ( QString ( "Invalid literal IP address" ) ); - return false; // invalid address - } + return false; + } - if ( !ParseNetworkAddressString ( strAddress, InetAddr, bIPv6Available ) ) + // first try if this is an IP number and can directly applied to QHostAddress + if ( InetAddr.setAddress ( strHost ) ) + { + if ( InetAddr.protocol() == QAbstractSocket::IPv6Protocol && !bIPv6Available ) { - // no valid address found - // qInfo() << qUtf8Printable ( QString ( "No IP address found for hostname" ) ); + // do not allow IPv6 addresses if not enabled + // qInfo() << "IPv6 addresses disabled"; return false; } + + QHostInfo info; + info.setHostName ( strHost ); + info.setAddresses ( { InetAddr } ); + info.setError ( QHostInfo::NoError ); + + // call the slot directly with IP and port + QMetaObject::invokeMethod ( + context, + [slot, info, iNetPort]() { slot ( info, iNetPort ); }, + Qt::QueuedConnection ); + + return true; + } + else if ( bLiteralAddr ) + { + // it was not a valid IP address. If literal required due to [], return as invalid + // qInfo() << "Invalid literal IP address"; + return false; // invalid address + } + else if ( !allowHostname ) + { + // not allowing hostname lookup + // qInfo() << "Hostname lookup disabled"; + return false; + } + else if ( !validateHostnameFormat ( strHost ) ) + { + // invalid format for hostname + // qInfo() << "Hostname format invalid"; + return false; } +#ifndef DISABLE_SRV_DNS + else if ( allowSrv && strPort.isEmpty() ) + { + // qInfo() << "Looking up SRV record for" << strHost; + + // check for SRV record to obtain hostname and port + QDnsLookup* dns = new QDnsLookup ( context ); + dns->setType ( QDnsLookup::SRV ); + dns->setName ( QString ( "_jamulus._udp.%1" ).arg ( strHost ) ); + + QObject::connect ( dns, &QDnsLookup::finished, context, [strHost, iNetPort, context, dns, slot]() { + if ( dns->error() == QDnsLookup::NoError ) + { + const QList records = dns->serviceRecords(); + if ( records.length() == 1 ) + { + QDnsServiceRecord record = records.first(); + qInfo() << "SRV record found: target =" << record.target() << "port =" << record.port(); + + dns->deleteLater(); + + if ( record.target().isEmpty() || record.target() == "." ) + { + // RFC2782 says that "." indicates that the service is not available. + // Qt strips the trailing dot, which is why we check for empty string + // as well. Therefore, the "." part might be redundant, but this would + // need further testing to confirm. + + // SRV says unavailable - create a QHostInfo to pass error to the slot + QHostInfo info; + info.setHostName ( strHost ); + info.setError ( QHostInfo::HostNotFound ); + info.setErrorString ( "SRV record indicates service unavailable" ); + + QMetaObject::invokeMethod ( + context, + [slot, info, iNetPort]() { slot ( info, iNetPort ); }, + Qt::QueuedConnection ); + return; + } + + resolveHostname ( record.target(), record.port(), context, slot ); + return; + } + else + { + qWarning() << "SRV returned" << records.length() << "records"; + } + } + + dns->deleteLater(); - // qInfo() << qUtf8Printable ( QString ( "Parsed network address %1" ).arg ( InetAddr.toString() ) ); + // SRV failed - lookup host directly + resolveHostname ( strHost, iNetPort, context, slot ); + } ); + + dns->lookup(); + + return true; + } +#endif - HostAddress = CHostAddress ( InetAddr, iNetPort ); + resolveHostname ( strHost, iNetPort, context, slot ); return true; } diff --git a/src/util.h b/src/util.h index 08e45166cb..01e271c71b 100644 --- a/src/util.h +++ b/src/util.h @@ -48,6 +48,7 @@ #include #include #include +#include #ifdef _WIN32 # include # include @@ -1102,13 +1103,38 @@ class CNetworkTransportProps class NetworkUtil { public: - static bool ParseNetworkAddressString ( QString strAddress, QHostAddress& InetAddr, const bool bIPv6Available ); + // parse literal address and optional port with no hostname lookup and address returned directly + static bool ParseAddressLiteral ( const QString& strAddress, const bool bIPv6Available, CHostAddress& haHostAddress ); -#ifndef DISABLE_SRV_DNS - static bool ParseNetworkAddressSrv ( QString strAddress, CHostAddress& HostAddress, const bool bIPv6Available ); -#endif - static bool ParseNetworkAddress ( QString strAddress, CHostAddress& HostAddress, const bool bIPv6Available ); - static bool ParseNetworkAddressBare ( QString strAddress, CHostAddress& HostAddress, const bool bIPv6Available ); + // resolve address and optional port with possible hostname and/or SRC lookup, + // with resolved address(es) returned asynchronously in a slot function + + // ResolveAddress() with object method as slot + template + static bool ResolveAddress ( const QString& strAddress, + const bool bIPv6Available, + T* context, + void ( T::*slot ) ( const QHostInfo& info, quint16 port ), + const bool allowHostname = false, + const bool allowSrv = false ) + { + // this is not a recursive call, as the parameter types are different + return ResolveAddress ( + strAddress, + bIPv6Available, + context, + [context, slot] ( const QHostInfo& info, quint16 port ) { ( context->*slot ) ( info, port ); }, + allowHostname, + allowSrv ); + } + + // ResolveAddress() with static method or function as slot + static bool ResolveAddress ( const QString& strAddress, + const bool bIPv6Available, + QObject* context, + std::function slot, + const bool allowHostname = false, + const bool allowSrv = false ); static QString FixAddress ( const QString& strAddress ); static CHostAddress GetLocalAddress(); From c3e897aacd40772abe294bde93e132bda975b0e6 Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Mon, 9 Nov 2026 16:35:08 +0000 Subject: [PATCH 02/21] Fix typo --- src/util.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/util.h b/src/util.h index 01e271c71b..cff2a544da 100644 --- a/src/util.h +++ b/src/util.h @@ -1106,7 +1106,7 @@ class NetworkUtil // parse literal address and optional port with no hostname lookup and address returned directly static bool ParseAddressLiteral ( const QString& strAddress, const bool bIPv6Available, CHostAddress& haHostAddress ); - // resolve address and optional port with possible hostname and/or SRC lookup, + // resolve address and optional port with possible hostname and/or SRV lookup, // with resolved address(es) returned asynchronously in a slot function // ResolveAddress() with object method as slot From 4c42f3432192844e3a89eb27c3a9ed16c87e20ce Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Mon, 9 Nov 2026 16:37:04 +0000 Subject: [PATCH 03/21] Remove unused #define --- src/util.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/util.h b/src/util.h index cff2a544da..f338d4ce0e 100644 --- a/src/util.h +++ b/src/util.h @@ -108,9 +108,8 @@ class CClient; // forward declaration of CClient #endif /* Definitions ****************************************************************/ -#define METER_FLY_BACK 2 -#define INVALID_MIDI_CH -1 // invalid MIDI channel definition -#define DNS_SRV_RESOLVE_TIMEOUT_MS 500 +#define METER_FLY_BACK 2 +#define INVALID_MIDI_CH -1 // invalid MIDI channel definition /* Global functions ***********************************************************/ // converting float to short From 18fbfa1c18bd9829e2a8852af5705a0cca0e24ac Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Tue, 10 Nov 2026 22:46:54 +0000 Subject: [PATCH 04/21] Add sequence number for CClient Connect and Disconnect This prevents stale address resolver slots from firing, if Disconnect is called while a Connect is still pending resolution. --- src/client.cpp | 21 +++++++++++++++++++-- src/client.h | 3 +++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/client.cpp b/src/client.cpp index 645da46bd2..126760b402 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -93,7 +93,8 @@ CClient::CClient ( const quint16 iPortNumber, bJitterBufferOK ( true ), bMuteMeInPersonalMix ( bNMuteMeInPersonalMix ), iServerSockBufNumFrames ( DEF_NET_BUF_SIZE_NUM_BL ), - bRawAudioIsSupported ( false ) + bRawAudioIsSupported ( false ), + iResolverSeq ( 0 ) { int iOpusError; @@ -1131,6 +1132,8 @@ void CClient::Stop() /// @emit Disconnected void CClient::Disconnect() { + ++iResolverSeq; // invalidate any uncompleted resolver requests + // Key off the connection state, not IsRunning() (which tracks the audio // device): the two diverge while connecting and in headless mode, and on // SIGTERM we must still send the disconnect message to the server. @@ -1157,7 +1160,21 @@ void CClient::Connect ( const QString& strServerAddress, const QString& strServe // different server while connected behaves as a reconnect Disconnect(); - if ( NetworkUtil::ResolveAddress ( strServerAddress, bIPv6Available, this, &CClient::OnHostResolved, true, true ) ) + const int seq = iResolverSeq; // for capturing the current request + + if ( NetworkUtil::ResolveAddress ( + strServerAddress, + bIPv6Available, + this, + [this, seq] ( const QHostInfo& info, quint16 port ) { + // check that the request has not been invalidated + if ( seq == iResolverSeq ) + { + OnHostResolved ( info, port ); // handle result + } + }, + true, + true ) ) { SetConnectedServerName ( strServerName ); // set if resolution initiated ok } diff --git a/src/client.h b/src/client.h index d692df8fe4..08289d047f 100644 --- a/src/client.h +++ b/src/client.h @@ -477,6 +477,9 @@ class CClient : public QObject int maxGainOrPanId; int iCurPingTime; + // sequence number for asynchronous DNS resolver + int iResolverSeq; + protected slots: void OnHandledSignal ( int sigNum ); void OnSendProtMessage ( CVector vecMessage ); From 156cfed1d77e5e278925f9b8752791b761e13950 Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Thu, 12 Nov 2026 16:04:04 +0000 Subject: [PATCH 05/21] Add sequence number for CConnectDlg directory resolution This prevents stale address resolver slots from firing, if a new directory is selected before the current one has been resolved. --- src/connectdlg.cpp | 20 ++++++++++++++++++-- src/connectdlg.h | 3 +++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/connectdlg.cpp b/src/connectdlg.cpp index 9b5a9595e2..d8c85c9783 100644 --- a/src/connectdlg.cpp +++ b/src/connectdlg.cpp @@ -90,7 +90,8 @@ CConnectDlg::CConnectDlg ( CClient* pNCliP, CClientSettings* pNSetP, const bool bReducedServerListReceived ( false ), bServerListItemWasChosen ( false ), bListFilterWasActive ( false ), - bShowAllMusicians ( true ) + bShowAllMusicians ( true ), + iResolverSeq ( 0 ) { setupUi ( this ); @@ -322,7 +323,22 @@ void CConnectDlg::RequestServerList() const QString strDirectoryAddress = NetworkUtil::GetDirectoryAddress ( pSettings->eDirectoryType, pSettings->vstrDirectoryAddress[pSettings->iCustomDirectoryIndex] ); - if ( !NetworkUtil::ResolveAddress ( strDirectoryAddress, pClient->IsIPv6Available(), this, &CConnectDlg::OnHostResolved, true, true ) ) + // get a new sequence number for matching the resolved callback + const int seq = ++iResolverSeq; + + if ( !NetworkUtil::ResolveAddress ( + strDirectoryAddress, + pClient->IsIPv6Available(), + this, + [this, seq] ( const QHostInfo& info, quint16 port ) { + // check that the request has not been superseded + if ( seq == iResolverSeq ) + { + OnHostResolved ( info, port ); // handle result + } + }, + true, + true ) ) { qWarning() << "Cannot start directory fetch from" << strDirectoryAddress; } diff --git a/src/connectdlg.h b/src/connectdlg.h index cf77a2b9f6..6f7e29eb79 100644 --- a/src/connectdlg.h +++ b/src/connectdlg.h @@ -146,6 +146,9 @@ class CConnectDlg : public CBaseDlg, private Ui_CConnectDlgBase bool bListFilterWasActive; bool bShowAllMusicians; + // sequence number for asynchronous DNS resolver + int iResolverSeq; + public slots: void OnServerListItemDoubleClicked ( QTreeWidgetItem* Item, int ); void OnDirectoryChanged ( int iTypeIdx ); From 8687b01cf248e5c718889e40f70e8fce0e2d5f0d Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Fri, 13 Nov 2026 09:52:08 +0000 Subject: [PATCH 06/21] Add sequence number for CServerListManager directory resolution This prevents stale address resolver slots from firing, if a new directory is selected before the current one has been reoslved. Also added a few small comments. --- src/client.cpp | 4 ++-- src/connectdlg.cpp | 4 ++-- src/serverlist.cpp | 33 ++++++++++++++++++++++++++------- src/serverlist.h | 3 +++ 4 files changed, 33 insertions(+), 11 deletions(-) diff --git a/src/client.cpp b/src/client.cpp index 126760b402..d9ff9172a9 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -1173,8 +1173,8 @@ void CClient::Connect ( const QString& strServerAddress, const QString& strServe OnHostResolved ( info, port ); // handle result } }, - true, - true ) ) + true, // allow hostname resolution + true ) ) // allow SVR resolution { SetConnectedServerName ( strServerName ); // set if resolution initiated ok } diff --git a/src/connectdlg.cpp b/src/connectdlg.cpp index d8c85c9783..d9ed15853b 100644 --- a/src/connectdlg.cpp +++ b/src/connectdlg.cpp @@ -337,8 +337,8 @@ void CConnectDlg::RequestServerList() OnHostResolved ( info, port ); // handle result } }, - true, - true ) ) + true, // allow hostname resolution + true ) ) // allow SVR resolution { qWarning() << "Cannot start directory fetch from" << strDirectoryAddress; } diff --git a/src/serverlist.cpp b/src/serverlist.cpp index 023bd0de31..a4fd2b300e 100644 --- a/src/serverlist.cpp +++ b/src/serverlist.cpp @@ -159,7 +159,8 @@ CServerListManager::CServerListManager ( CServer* pServer, eSvrRegStatus ( SRS_NOT_REGISTERED ), strMinServerVersion ( "" ), // disable version check with empty version pConnLessProtocol ( pNConLProt ), - iSvrRegRetries ( 0 ) + iSvrRegRetries ( 0 ), + iResolverSeq ( 0 ) { CHostAddress haServerAddr ( NetworkUtil::GetLocalAddress().InetAddr, iNPortNum ); @@ -1008,6 +1009,9 @@ void CServerListManager::SetRegistered ( const bool bIsRegister ) if ( !bIsRegister ) { + // invalidate any pending address resolution for registration + ++iResolverSeq; + // unregister server if it is registered - regardless of success of parse SetSvrRegStatus ( SRS_NOT_REGISTERED ); @@ -1025,19 +1029,34 @@ void CServerListManager::SetRegistered ( const bool bIsRegister ) // Note that we always have to parse the server address again since if // it is an URL of a dynamic IP address, the IP address might have // changed in the meanwhile. - // Allow IPv4 only for communicating with Directories + + // Currently allow only IPv4 for communicating with Directories // Use SRV DNS discovery for directory connections, fallback to A/AAAA if none. + const QString strNetworkAddress = NetworkUtil::GetDirectoryAddress ( DirectoryType, strDirectoryAddress ); - // allow hostname resolution and SRV resolution - const bool bDirectoryAddressValid = - NetworkUtil::ResolveAddress ( strNetworkAddress, false, this, &CServerListManager::OnHostResolved, true, true ); + // get a new sequence number for matching the resolved callback + const int seq = ++iResolverSeq; - // lock the mutex again now that the address has been resolved. - locker.relock(); + // allow hostname resolution and SRV resolution + const bool bDirectoryAddressValid = NetworkUtil::ResolveAddress ( + strNetworkAddress, + false, // IPv4 only at present + this, + [this, seq] ( const QHostInfo& info, quint16 port ) { + // check that the request has not been superseded + if ( seq == iResolverSeq ) + { + OnHostResolved ( info, port ); // handle result + } + }, + true, // allow hostname resolution + true ); // allow SVR resolution if ( !bDirectoryAddressValid ) { + // lock the mutex again before calling SetSvrRegStatus() + locker.relock(); SetSvrRegStatus ( SRS_BAD_ADDRESS ); } } diff --git a/src/serverlist.h b/src/serverlist.h index afb3ad2b82..7dd4d89176 100644 --- a/src/serverlist.h +++ b/src/serverlist.h @@ -246,6 +246,9 @@ class CServerListManager : public QObject QTimer TimerCLRegisterServerResp; QTimer TimerIsPermanent; + // sequence number for asynchronous DNS resolver + int iResolverSeq; + public slots: void OnTimerPollList(); void OnTimerPingServerInList(); From 14266e0f36753a4650a5bc0d975faea351232d86 Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Fri, 13 Nov 2026 12:25:03 +0000 Subject: [PATCH 07/21] Corrections to hostname format validation --- src/util.cpp | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/src/util.cpp b/src/util.cpp index 637418dac3..b4851c7be2 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -869,27 +869,29 @@ static bool validateHostnameFormat ( const QString& strHostname ) // Validate hostname format before trying to resolve: // (all matches are non-greedy) static const QRegularExpression plainHostRegex ( - // # beginning of string + // beginning of string "^" - // # doesn't contain underscore (this is so that we can use \w later on for [A-Za-z0-9]) + // doesn't contain underscore (this is so that we can use \w later on for [A-Za-z0-9]) + // note that \w only matches ASCII as QRegularExpression::UseUnicodePropertiesOption is not set "(?!.*?_)" - // # doesn't contain two dots in a row + // doesn't contain two dots in a row "(?!.*?\\.\\.)" - // # doesn't have only digits in the last element (also eliminates raw IP addresses) - "(?!.*\\.\\d+\\.?$)" - // # doesn't contain dash at the beginning of a label - "(?!(?:\\w+?\\.)?-[\\w\\.\\-]*?)" - // # doesn't contain dash at the end of a label - "(?!\\w+?-\\.(?:[\\w\\.\\-]+?))" - // # starts with an alphanumeric char + // doesn't have only digits in the last element (also eliminates raw IP addresses) + "(?!.*?\\.\\d+\\.?$)" + // doesn't contain dash at the beginning of a label + "(?!-|(?:.*?\\.-))" + // doesn't contain dash at the end of a label + "(?!.*?-\\.)" + "(?!.*?-$)" + // starts with an alphanumeric char "(?=\\w)" - // # not longer than 253 chars - "(?![\\w\\.\\-]{254})" - // # doesn't contain a label longer than 63 char + // not longer than 253 chars + "(?!.{254})" + // doesn't contain a label longer than 63 char "(?!.*?[\\w\\-]{64})" - // # allowed chars alphanumeric, dot and dash + // allowed chars alphanumeric, dot and dash "[\\w\\.\\-]+?" - // # end of string + // end of string "$" ); auto match = plainHostRegex.match ( strHostname ); From 1039c7f0c80d3b35bdea65ef3bcd3b21dd1e54ef Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Fri, 13 Nov 2026 13:21:31 +0000 Subject: [PATCH 08/21] Only use IPv4 for directory in connectdlg --- src/connectdlg.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/connectdlg.cpp b/src/connectdlg.cpp index d9ed15853b..7e7759ac20 100644 --- a/src/connectdlg.cpp +++ b/src/connectdlg.cpp @@ -328,7 +328,7 @@ void CConnectDlg::RequestServerList() if ( !NetworkUtil::ResolveAddress ( strDirectoryAddress, - pClient->IsIPv6Available(), + false, // IPv4 only at present this, [this, seq] ( const QHostInfo& info, quint16 port ) { // check that the request has not been superseded From 13ce6f3cff56b5d2c9a73e2ae0a15baf39ba4153 Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Fri, 13 Nov 2026 13:22:52 +0000 Subject: [PATCH 09/21] Improve DirectoryAddress handling --- src/serverlist.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/serverlist.cpp b/src/serverlist.cpp index a4fd2b300e..e46185516b 100644 --- a/src/serverlist.cpp +++ b/src/serverlist.cpp @@ -1015,7 +1015,10 @@ void CServerListManager::SetRegistered ( const bool bIsRegister ) // unregister server if it is registered - regardless of success of parse SetSvrRegStatus ( SRS_NOT_REGISTERED ); - pConnLessProtocol->CreateCLUnregisterServerMes ( DirectoryAddress ); + if ( !( DirectoryAddress == CHostAddress() ) ) + { + pConnLessProtocol->CreateCLUnregisterServerMes ( DirectoryAddress ); + } return; } @@ -1035,6 +1038,9 @@ void CServerListManager::SetRegistered ( const bool bIsRegister ) const QString strNetworkAddress = NetworkUtil::GetDirectoryAddress ( DirectoryType, strDirectoryAddress ); + // invalidate current directory address until resolved + DirectoryAddress = CHostAddress(); + // get a new sequence number for matching the resolved callback const int seq = ++iResolverSeq; From 31ac5236ab9d2ca40b3a069d53ea1c37b8346c8f Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Fri, 13 Nov 2026 13:23:51 +0000 Subject: [PATCH 10/21] Return status from resolveHostname() --- src/util.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/util.cpp b/src/util.cpp index b4851c7be2..b705f6fd14 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -856,12 +856,13 @@ void PlayAudioAlert ( QUrl soundUrl ) \******************************************************************************/ // Network utility functions --------------------------------------------------- -static void resolveHostname ( const QString& strHostname, +static bool resolveHostname ( const QString& strHostname, const quint16 port, QObject* context, std::function slot ) { - QHostInfo::lookupHost ( strHostname, context, [slot, port] ( const QHostInfo& info ) { slot ( info, port ); } ); + // lookupHost returns -1 if it fails to initiate a lookup, otherwise an ID that we do not use + return -1 != QHostInfo::lookupHost ( strHostname, context, [slot, port] ( const QHostInfo& info ) { slot ( info, port ); } ); } static bool validateHostnameFormat ( const QString& strHostname ) @@ -1122,9 +1123,7 @@ bool NetworkUtil::ResolveAddress ( const QString& } #endif - resolveHostname ( strHost, iNetPort, context, slot ); - - return true; + return resolveHostname ( strHost, iNetPort, context, slot ); } CHostAddress NetworkUtil::GetLocalAddress() From 1ec14e17ba20b16238bb941153f50152d6bcc19e Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Sat, 14 Nov 2026 14:14:02 +0000 Subject: [PATCH 11/21] Add CS_RESOLVING client state and emit signal for it --- src/client.cpp | 5 +++++ src/client.h | 6 ++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/client.cpp b/src/client.cpp index d9ff9172a9..a01dd2eb76 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -1160,6 +1160,11 @@ void CClient::Connect ( const QString& strServerAddress, const QString& strServe // different server while connected behaves as a reconnect Disconnect(); + // note that we are resolving the address + SetConnectionState ( CS_RESOLVING ); + + emit Resolving ( GetConnectedServerName() ); + const int seq = iResolverSeq; // for capturing the current request if ( NetworkUtil::ResolveAddress ( diff --git a/src/client.h b/src/client.h index 08289d047f..608f0ffc7a 100644 --- a/src/client.h +++ b/src/client.h @@ -96,8 +96,9 @@ enum EConnectionState // stream towards the configured server and "established" once the server // has assigned a channel ID to the client CS_DISCONNECTED = 0, // no connection requested or established - CS_CONNECTING = 1, // connection requested but not yet established - CS_CONNECTED = 2 // connection established and current + CS_RESOLVING = 1, // resolving address + CS_CONNECTING = 2, // connection requested but not yet established + CS_CONNECTED = 3 // connection established and current }; // audio in fader range @@ -541,6 +542,7 @@ protected slots: void CLChannelLevelListReceived ( CHostAddress InetAddr, CVector vecLevelList ); void ConnectionStateChanged ( EConnectionState eConnectionState ); + void Resolving ( const QString& strServerName ); void Connecting ( const QString& strServerName ); void ConnectingFailed ( const QString& errorMessage ); void Disconnected(); From 39be89cb211ce40ea0446ea96261896082a995db Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Sat, 14 Nov 2026 14:16:44 +0000 Subject: [PATCH 12/21] In connect dialog, handle CS_RESOLVING state Set Connect button to Disconnect when resolving starts. Use connection state rather than sound state for Connect button. --- src/clientdlg.cpp | 12 +++++++++++- src/clientdlg.h | 1 + 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/clientdlg.cpp b/src/clientdlg.cpp index 34e95ff2dd..a10ee5506f 100644 --- a/src/clientdlg.cpp +++ b/src/clientdlg.cpp @@ -498,6 +498,8 @@ CClientDlg::CClientDlg ( CClient* pNCliP, // other QObject::connect ( pClient, &CClient::ConClientListMesReceived, this, &CClientDlg::OnConClientListMesReceived ); + QObject::connect ( pClient, &CClient::Resolving, this, &CClientDlg::OnResolving ); + QObject::connect ( pClient, &CClient::Connecting, this, &CClientDlg::OnConnecting ); QObject::connect ( pClient, &CClient::ConnectingFailed, this, &CClientDlg::OnConnectingFailed ); @@ -788,7 +790,7 @@ void CClientDlg::OnConnectDlgAccepted() void CClientDlg::OnConnectDisconBut() { // the connect/disconnect button implements a toggle functionality - if ( pClient->IsRunning() ) + if ( pClient->GetConnectionState() != CS_DISCONNECTED ) { pClient->Disconnect(); } @@ -1237,6 +1239,14 @@ void CClientDlg::OnCLPingTimeWithNumClientsReceived ( CHostAddress InetAddr, int ConnectDlg.SetPingTimeAndNumClientsResult ( InetAddr, iPingTime, iNumClients ); } +void CClientDlg::OnResolving ( const QString& strMixerBoardLabel ) +{ + Q_UNUSED ( strMixerBoardLabel ); // might want to use it in the future + + // change connect button text to "disconnect" while resolving too + butConnect->setText ( tr ( "&Disconnect" ) ); +} + void CClientDlg::OnConnecting ( const QString& strMixerBoardLabel ) { diff --git a/src/clientdlg.h b/src/clientdlg.h index b7da510e05..087e082be6 100644 --- a/src/clientdlg.h +++ b/src/clientdlg.h @@ -145,6 +145,7 @@ class CClientDlg : public CBaseDlg, private Ui_CClientDlgBase CAnalyzerConsole AnalyzerConsole; public slots: + void OnResolving ( const QString& strServerName ); void OnConnecting ( const QString& strServerName ); void OnConnectingFailed ( const QString& strErrorText ); void OnDisconnect(); From f79deed82cf042b600971d6514e1f9fda45215f1 Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Sat, 14 Nov 2026 16:17:44 +0000 Subject: [PATCH 13/21] Change client state to CD_DISCONNECTED after failure to resolve --- src/client.cpp | 3 +++ src/clientdlg.cpp | 8 +++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/client.cpp b/src/client.cpp index a01dd2eb76..8db4f79197 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -1199,6 +1199,9 @@ void CClient::OnHostResolved ( const QHostInfo& info, quint16 port ) { if ( info.error() != QHostInfo::NoError ) { + SetConnectionState ( CS_DISCONNECTED ); // no longer CS_RESOLVING + + // emit ConnectingFailed to inform UI emit ConnectingFailed ( "Cannot connect: " + info.errorString() ); return; } diff --git a/src/clientdlg.cpp b/src/clientdlg.cpp index a10ee5506f..52bb638cba 100644 --- a/src/clientdlg.cpp +++ b/src/clientdlg.cpp @@ -1275,7 +1275,13 @@ void CClientDlg::OnConnecting ( const QString& strMixerBoardLabel ) } } -void CClientDlg::OnConnectingFailed ( const QString& strError ) { QMessageBox::critical ( this, APP_NAME, strError, tr ( "Close" ), nullptr ); } +void CClientDlg::OnConnectingFailed ( const QString& strError ) +{ + // change connect button text back to "connect" + butConnect->setText ( tr ( "C&onnect" ) ); + + QMessageBox::critical ( this, APP_NAME, strError, tr ( "Close" ), nullptr ); +} void CClientDlg::OnDisconnect() { From 1a7d0d5a01f3ed27aceec9da9e23684cc5fccfd6 Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Sat, 14 Nov 2026 17:45:20 +0000 Subject: [PATCH 14/21] Set state to disconnected on every kind of failure --- src/client.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/client.cpp b/src/client.cpp index 8db4f79197..d326dac181 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -1162,8 +1162,7 @@ void CClient::Connect ( const QString& strServerAddress, const QString& strServe // note that we are resolving the address SetConnectionState ( CS_RESOLVING ); - - emit Resolving ( GetConnectedServerName() ); + emit Resolving ( strServerAddress ); const int seq = iResolverSeq; // for capturing the current request @@ -1185,12 +1184,15 @@ void CClient::Connect ( const QString& strServerAddress, const QString& strServe } else { + SetConnectionState ( CS_DISCONNECTED ); // no longer CS_RESOLVING emit ConnectingFailed ( tr ( "Received invalid server address. Please check for typos in the provided server address." ) ); } } catch ( const CGenErr& generr ) { // Stop(); // XXX: probably not needed? + + SetConnectionState ( CS_DISCONNECTED ); // no longer CS_RESOLVING emit ConnectingFailed ( generr.GetErrorText() ); } } @@ -1200,8 +1202,6 @@ void CClient::OnHostResolved ( const QHostInfo& info, quint16 port ) if ( info.error() != QHostInfo::NoError ) { SetConnectionState ( CS_DISCONNECTED ); // no longer CS_RESOLVING - - // emit ConnectingFailed to inform UI emit ConnectingFailed ( "Cannot connect: " + info.errorString() ); return; } @@ -1221,12 +1221,14 @@ void CClient::OnHostResolved ( const QHostInfo& info, quint16 port ) catch ( const CGenErr& generr ) { Stop(); + // Stop() sets the connection state to CS_DISCONNECTED emit ConnectingFailed ( generr.GetErrorText() ); } return; } } + SetConnectionState ( CS_DISCONNECTED ); // no longer CS_RESOLVING emit ConnectingFailed ( "Hostname returned no usable addresses" ); } From bc1aa0d69b937fb5029a489dbcd1e276cb64f8e7 Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Sat, 14 Nov 2026 21:05:14 +0000 Subject: [PATCH 15/21] Suppress warning for zero SVR records --- src/util.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/util.cpp b/src/util.cpp index b705f6fd14..049adb9568 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -1105,8 +1105,9 @@ bool NetworkUtil::ResolveAddress ( const QString& resolveHostname ( record.target(), record.port(), context, slot ); return; } - else + else if ( !records.isEmpty() ) { + // Jamulus doesn't handle multiple SRV records, so warn if they are found qWarning() << "SRV returned" << records.length() << "records"; } } From d119ccc703cab62f0bd11630a3f0cb7f6fa1ee2e Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Sat, 14 Nov 2026 22:50:21 +0000 Subject: [PATCH 16/21] Ensure slot is always called within ResolveAddress() --- src/util.cpp | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/util.cpp b/src/util.cpp index 049adb9568..03f6dca376 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -1102,7 +1102,18 @@ bool NetworkUtil::ResolveAddress ( const QString& return; } - resolveHostname ( record.target(), record.port(), context, slot ); + if ( !resolveHostname ( record.target(), record.port(), context, slot ) ) + { + QHostInfo info; + info.setHostName ( strHost ); + info.setError ( QHostInfo::HostNotFound ); + info.setErrorString ( "Host in SRV record not found" ); + + QMetaObject::invokeMethod ( + context, + [slot, info, iNetPort]() { slot ( info, iNetPort ); }, + Qt::QueuedConnection ); + } return; } else if ( !records.isEmpty() ) @@ -1115,7 +1126,18 @@ bool NetworkUtil::ResolveAddress ( const QString& dns->deleteLater(); // SRV failed - lookup host directly - resolveHostname ( strHost, iNetPort, context, slot ); + if ( !resolveHostname ( strHost, iNetPort, context, slot ) ) + { + QHostInfo info; + info.setHostName ( strHost ); + info.setError ( QHostInfo::HostNotFound ); + info.setErrorString ( "Host not found" ); + + QMetaObject::invokeMethod ( + context, + [slot, info, iNetPort]() { slot ( info, iNetPort ); }, + Qt::QueuedConnection ); + } } ); dns->lookup(); From 863c0d735c9e31dfa02b18d3cbdfd9cc21339603 Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Sun, 15 Nov 2026 22:12:28 +0000 Subject: [PATCH 17/21] Stop TimerReRequestServList before resolving a new directory --- src/connectdlg.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/connectdlg.cpp b/src/connectdlg.cpp index 7e7759ac20..5c96d2876e 100644 --- a/src/connectdlg.cpp +++ b/src/connectdlg.cpp @@ -284,6 +284,9 @@ void CConnectDlg::RequestServerList() // ensure ping timer is stopped TimerPing.stop(); + // also ensure rerequest timer is stopped + TimerReRequestServList.stop(); + // reset flags bServerListReceived = false; bReducedServerListReceived = false; From 488b20721c0e63c57a91ff2770dd0c838f98a62a Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Mon, 16 Nov 2026 14:30:53 +0000 Subject: [PATCH 18/21] A few robustness improvements and simplification --- src/client.cpp | 72 ++++++++++++++++++++++------------------------ src/connectdlg.cpp | 3 ++ src/serverlist.cpp | 3 ++ 3 files changed, 40 insertions(+), 38 deletions(-) diff --git a/src/client.cpp b/src/client.cpp index d326dac181..96cafa73a9 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -1137,7 +1137,13 @@ void CClient::Disconnect() // Key off the connection state, not IsRunning() (which tracks the audio // device): the two diverge while connecting and in headless mode, and on // SIGTERM we must still send the disconnect message to the server. - if ( GetConnectionState() != CS_DISCONNECTED ) + if ( eConnectionState == CS_RESOLVING ) + { + // no need to Stop, as we haven't Started, but need to update connection state + SetConnectionState ( CS_DISCONNECTED ); + emit Disconnected(); + } + else if ( eConnectionState != CS_DISCONNECTED ) { Stop(); } @@ -1154,46 +1160,36 @@ void CClient::Disconnect() /// @param strServerName - the human readable server name passed to Connecting() void CClient::Connect ( const QString& strServerAddress, const QString& strServerName ) { - try - { - // disconnect from any current server first so that connecting to a - // different server while connected behaves as a reconnect - Disconnect(); - - // note that we are resolving the address - SetConnectionState ( CS_RESOLVING ); - emit Resolving ( strServerAddress ); - - const int seq = iResolverSeq; // for capturing the current request - - if ( NetworkUtil::ResolveAddress ( - strServerAddress, - bIPv6Available, - this, - [this, seq] ( const QHostInfo& info, quint16 port ) { - // check that the request has not been invalidated - if ( seq == iResolverSeq ) - { - OnHostResolved ( info, port ); // handle result - } - }, - true, // allow hostname resolution - true ) ) // allow SVR resolution - { - SetConnectedServerName ( strServerName ); // set if resolution initiated ok - } - else - { - SetConnectionState ( CS_DISCONNECTED ); // no longer CS_RESOLVING - emit ConnectingFailed ( tr ( "Received invalid server address. Please check for typos in the provided server address." ) ); - } + // disconnect from any current server first so that connecting to a + // different server while connected behaves as a reconnect + Disconnect(); + + // note that we are resolving the address + SetConnectionState ( CS_RESOLVING ); + emit Resolving ( strServerAddress ); + + const int seq = iResolverSeq; // for capturing the current request + + if ( NetworkUtil::ResolveAddress ( + strServerAddress, + bIPv6Available, + this, + [this, seq] ( const QHostInfo& info, quint16 port ) { + // check that the request has not been invalidated + if ( seq == iResolverSeq ) + { + OnHostResolved ( info, port ); // handle result + } + }, + true, // allow hostname resolution + true ) ) // allow SVR resolution + { + SetConnectedServerName ( strServerName ); // set if resolution initiated ok } - catch ( const CGenErr& generr ) + else { - // Stop(); // XXX: probably not needed? - SetConnectionState ( CS_DISCONNECTED ); // no longer CS_RESOLVING - emit ConnectingFailed ( generr.GetErrorText() ); + emit ConnectingFailed ( tr ( "Received invalid server address. Please check for typos in the provided server address." ) ); } } diff --git a/src/connectdlg.cpp b/src/connectdlg.cpp index 5c96d2876e..0eaf4b515e 100644 --- a/src/connectdlg.cpp +++ b/src/connectdlg.cpp @@ -287,6 +287,9 @@ void CConnectDlg::RequestServerList() // also ensure rerequest timer is stopped TimerReRequestServList.stop(); + // clear current directory address to ignore any late server list + haDirectoryAddress = CHostAddress(); + // reset flags bServerListReceived = false; bReducedServerListReceived = false; diff --git a/src/serverlist.cpp b/src/serverlist.cpp index e46185516b..a8329a7800 100644 --- a/src/serverlist.cpp +++ b/src/serverlist.cpp @@ -448,6 +448,9 @@ void CServerListManager::SetIsDirectory() // When we unregister, set the status and stop timers void CServerListManager::Unregister() { + // invalidate any stale registration response + ++iResolverSeq; + // if not currently registered, nothing needs doing if ( DirectoryType == AT_NONE || ( DirectoryType == AT_CUSTOM && strDirectoryAddress.isEmpty() ) || eSvrRegStatus == SRS_NOT_REGISTERED ) { From a4ea676bf61fddded0ab3125e3ffe0dbc289817c Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Mon, 16 Nov 2026 17:25:31 +0000 Subject: [PATCH 19/21] Add connection state check to OnCLDisconnection() Also tidy up by moving that function definition from .h to .cpp --- src/client.cpp | 9 +++++++++ src/client.h | 9 +-------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/client.cpp b/src/client.cpp index 96cafa73a9..4c7c420878 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -335,6 +335,15 @@ void CClient::OnNewConnection() //### TODO: END ###// } +void CClient::OnCLDisconnection ( CHostAddress InetAddr ) +{ + if ( eConnectionState != CS_RESOLVING && InetAddr == Channel.GetAddress() ) + { + // Stop client in case it received a Disconnection request + Stop(); + } +} + void CClient::OnMuteStateHasChangedReceived ( int iServerChanID, bool bIsMuted ) { // map iChanID from server channel ID to client channel ID diff --git a/src/client.h b/src/client.h index 608f0ffc7a..e7bf45ae5e 100644 --- a/src/client.h +++ b/src/client.h @@ -492,14 +492,7 @@ protected slots: void OnJittBufSizeChanged ( int iNewJitBufSize ); void OnReqChanInfo() { Channel.SetRemoteInfo ( ChannelInfo ); } void OnNewConnection(); - void OnCLDisconnection ( CHostAddress InetAddr ) - { - if ( InetAddr == Channel.GetAddress() ) - { - // Stop client in case it received a Disconnection request - Stop(); - } - } + void OnCLDisconnection ( CHostAddress InetAddr ); void OnCLPingReceived ( CHostAddress InetAddr, int iMs ); void OnSendCLProtMessage ( CHostAddress InetAddr, CVector vecMessage ); From f44aecf082f0cfcd202505b334eeb50fea944386 Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Tue, 17 Nov 2026 09:57:21 +0000 Subject: [PATCH 20/21] Tidy up a comment --- src/client.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/client.cpp b/src/client.cpp index 4c7c420878..74822de0ce 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -1225,8 +1225,7 @@ void CClient::OnHostResolved ( const QHostInfo& info, quint16 port ) } catch ( const CGenErr& generr ) { - Stop(); - // Stop() sets the connection state to CS_DISCONNECTED + Stop(); // sets the connection state to CS_DISCONNECTED emit ConnectingFailed ( generr.GetErrorText() ); } return; From ab23b92db5275bd58172bef2cde7ea920e3bead1 Mon Sep 17 00:00:00 2001 From: Tony Mountifield Date: Wed, 18 Nov 2026 11:17:33 +0000 Subject: [PATCH 21/21] Refactor server registration timers for correct operation --- src/serverlist.cpp | 137 +++++++++++++++++++++------------------------ 1 file changed, 65 insertions(+), 72 deletions(-) diff --git a/src/serverlist.cpp b/src/serverlist.cpp index a8329a7800..e2fcb43aea 100644 --- a/src/serverlist.cpp +++ b/src/serverlist.cpp @@ -459,24 +459,6 @@ void CServerListManager::Unregister() // Update server registration status - sets the lock SetRegistered ( false ); - - // this is called without the lock set - QMutexLocker locker ( &Mutex ); - - // disable service -> stop timer - if ( bIsDirectory ) - { - TimerPollList.stop(); - TimerPingServerInList.stop(); - } - else - { - TimerCLRegisterServerResp.stop(); - TimerRefreshRegistration.stop(); - TimerPingServers.stop(); - TimerIsPermanent.stop(); - } - ServerList[0].bPermanentOnline = false; } // When we register, set the status and start timers @@ -490,49 +472,16 @@ void CServerListManager::Register() return; } - // Update server registration status - sets the lock - SetRegistered ( true ); - - // this is called without the lock set - QMutexLocker locker ( &Mutex ); - - if ( bIsDirectory ) + if ( !bIsDirectory ) { - // start timer for polling the server list if enabled - // 1 minute = 60 * 1000 ms - TimerPollList.start ( SERVLIST_POLL_TIME_MINUTES * 60000 ); - - // start timer for sending ping messages to servers in the list - TimerPingServerInList.start ( SERVLIST_UPDATE_PING_SERVERS_MS ); + QMutexLocker locker ( &Mutex ); - // directory is permanent - ServerList[0].bPermanentOnline = true; - } - else - { // reset the retry counter to zero because update was called iSvrRegRetries = 0; - - // start timer for registration timeout - this gets restarted - // in OnTimerCLRegisterServerResp on failure - TimerCLRegisterServerResp.start(); - - // start timer for registering this server at the directory - // 1 minute = 60 * 1000 ms - TimerRefreshRegistration.start ( SERVLIST_REGIST_INTERV_MINUTES * 60000 ); - - // Start timer for ping the directory in short intervals to - // keep the port open at the NAT router. - // If no NAT is used, we send the messages anyway since they do - // not hurt (very low traffic). We also reuse the same update - // time as used in the directory for pinging the registered - // servers. - TimerPingServers.start ( SERVLIST_UPDATE_PING_SERVERS_MS ); - - // start the one shot timer for determining if this is a - // permanent registered server - TimerIsPermanent.start(); } + + // Update server registration status - sets the lock + SetRegistered ( true ); } /* Server list functionality **************************************************/ @@ -966,13 +915,7 @@ void CServerListManager::OnTimerCLRegisterServerResp() else { locker.unlock(); - { - OnTimerRefreshRegistration(); - } - locker.relock(); - - // re-start timer for registration timeout - TimerCLRegisterServerResp.start(); + OnTimerRefreshRegistration(); } } } @@ -1000,13 +943,6 @@ void CServerListManager::SetRegistered ( const bool bIsRegister ) return; } - if ( bIsDirectory ) - { - // this IS the directory, no network message to worry about - SetSvrRegStatus ( bIsRegister ? SRS_REGISTERED : SRS_NOT_REGISTERED ); - return; - } - // If we are unregistering from a directory we previously registered to, // just use the saved address from registering, without address resolution. @@ -1018,10 +954,46 @@ void CServerListManager::SetRegistered ( const bool bIsRegister ) // unregister server if it is registered - regardless of success of parse SetSvrRegStatus ( SRS_NOT_REGISTERED ); - if ( !( DirectoryAddress == CHostAddress() ) ) + // disable service -> unregister and stop timers + if ( bIsDirectory ) + { + TimerPollList.stop(); + TimerPingServerInList.stop(); + } + else { - pConnLessProtocol->CreateCLUnregisterServerMes ( DirectoryAddress ); + // send registration message if we are not our own directory + if ( !( DirectoryAddress == CHostAddress() ) ) + { + pConnLessProtocol->CreateCLUnregisterServerMes ( DirectoryAddress ); + } + + TimerCLRegisterServerResp.stop(); + TimerRefreshRegistration.stop(); + TimerPingServers.stop(); + TimerIsPermanent.stop(); } + ServerList[0].bPermanentOnline = false; + + return; + } + + // if we are our own directory, set status directly and start timers + + if ( bIsDirectory ) + { + // this IS the directory, no network message to worry about + SetSvrRegStatus ( SRS_REGISTERED ); + + // start timer for polling the server list if enabled + // 1 minute = 60 * 1000 ms + TimerPollList.start ( SERVLIST_POLL_TIME_MINUTES * 60000 ); + + // start timer for sending ping messages to servers in the list + TimerPingServerInList.start ( SERVLIST_UPDATE_PING_SERVERS_MS ); + + // directory is permanent + ServerList[0].bPermanentOnline = true; return; } @@ -1091,6 +1063,27 @@ void CServerListManager::OnHostResolved ( const QHostInfo& info, quint16 port ) // very first item in the server list (which is actually no server list // but just one item long for the registered server). pConnLessProtocol->CreateCLRegisterServerExMes ( DirectoryAddress, ServerList[0].LHostAddr, ServerList[0] ); + + // start timer for registration timeout - this gets restarted + // in OnTimerCLRegisterServerResp on failure + TimerCLRegisterServerResp.start(); + + // start timer for registering this server at the directory + // 1 minute = 60 * 1000 ms + TimerRefreshRegistration.start ( SERVLIST_REGIST_INTERV_MINUTES * 60000 ); + + // Start timer for ping the directory in short intervals to + // keep the port open at the NAT router. + // If no NAT is used, we send the messages anyway since they do + // not hurt (very low traffic). We also reuse the same update + // time as used in the directory for pinging the registered + // servers. + TimerPingServers.start ( SERVLIST_UPDATE_PING_SERVERS_MS ); + + // start the one shot timer for determining if this is a + // permanent registered server + TimerIsPermanent.start(); + return; } }