diff --git a/src/client.cpp b/src/client.cpp index 9b5e502bee..74822de0ce 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; @@ -334,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 @@ -619,25 +629,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 @@ -1150,10 +1141,18 @@ 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. - 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(); } @@ -1162,7 +1161,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 @@ -1170,28 +1169,71 @@ 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 { - // disconnect from any current server first so that connecting to a - // different server while connected behaves as a reconnect - Disconnect(); + SetConnectionState ( CS_DISCONNECTED ); // no longer CS_RESOLVING + emit ConnectingFailed ( tr ( "Received invalid server address. Please check for typos in the provided server address." ) ); + } +} - // Set server address and connect if valid address was supplied - if ( SetServerAddr ( strServerAddress ) ) - { - SetConnectedServerName ( strServerName ); - Start(); - } - else - { - throw CGenErr ( tr ( "Received invalid server address. Please check for typos in the provided server address." ) ); - } +void CClient::OnHostResolved ( const QHostInfo& info, quint16 port ) +{ + if ( info.error() != QHostInfo::NoError ) + { + SetConnectionState ( CS_DISCONNECTED ); // no longer CS_RESOLVING + emit ConnectingFailed ( "Cannot connect: " + info.errorString() ); + return; } - catch ( const CGenErr& generr ) + + for ( const QHostAddress& HostAddr : info.addresses() ) { - Stop(); - emit ConnectingFailed ( generr.GetErrorText() ); + // 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(); // 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" ); } /// @method diff --git a/src/client.h b/src/client.h index 1c4c4e5428..e7bf45ae5e 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 @@ -180,7 +181,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; } @@ -478,6 +478,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 ); @@ -489,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 ); @@ -514,6 +510,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 ); @@ -538,6 +535,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(); diff --git a/src/clientdlg.cpp b/src/clientdlg.cpp index 2c7c35f02c..52bb638cba 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 ); @@ -605,21 +607,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::ParseNetworkAddressBare ( UPDATECHECK1_ADDRESS, UpdateServerHostAddress, pClient->IsIPv6Available() ) ) + if ( !NetworkUtil::ResolveAddress ( UPDATECHECK2_ADDRESS, pClient->IsIPv6Available(), this, &CClientDlg::OnHostResolved, true, false ) ) { - pClient->CreateCLServerListReqVerAndOSMes ( UpdateServerHostAddress ); + qWarning() << "Cannot start update check for" << UPDATECHECK2_ADDRESS; } +} - if ( NetworkUtil::ParseNetworkAddressBare ( UPDATECHECK2_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; + } + + 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() ) ) + { + CHostAddress HostAddress ( HostAddr, port ); + + pClient->CreateCLServerListReqVerAndOSMes ( HostAddress ); + return; + } } } @@ -771,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(); } @@ -1220,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 ) { @@ -1248,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() { diff --git a/src/clientdlg.h b/src/clientdlg.h index b127231b27..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(); @@ -260,6 +261,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..0eaf4b515e 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 ); @@ -283,6 +284,12 @@ void CConnectDlg::RequestServerList() // ensure ping timer is stopped TimerPing.stop(); + // 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; @@ -312,24 +319,63 @@ 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] ); + + // get a new sequence number for matching the resolved callback + const int seq = ++iResolverSeq; + + if ( !NetworkUtil::ResolveAddress ( + strDirectoryAddress, + 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 { - // send the request for the server list - emit ReqServerListQuery ( haDirectoryAddress ); + qWarning() << "Cannot start directory fetch from" << strDirectoryAddress; + } +} + +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 ); - // 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 + // 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 +901,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..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 ); @@ -157,6 +160,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..e2fcb43aea 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; @@ -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 ); @@ -447,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 ) { @@ -455,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 @@ -486,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 **************************************************/ @@ -827,9 +780,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 ) { @@ -958,13 +915,7 @@ void CServerListManager::OnTimerCLRegisterServerResp() else { locker.unlock(); - { - OnTimerRefreshRegistration(); - } - locker.relock(); - - // re-start timer for registration timeout - TimerCLRegisterServerResp.start(); + OnTimerRefreshRegistration(); } } } @@ -992,10 +943,57 @@ 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 ) + { + // invalidate any pending address resolution for registration + ++iResolverSeq; + + // unregister server if it is registered - regardless of success of parse + SetSvrRegStatus ( SRS_NOT_REGISTERED ); + + // disable service -> unregister and stop timers + if ( bIsDirectory ) + { + TimerPollList.stop(); + TimerPingServerInList.stop(); + } + else + { + // 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 ( bIsRegister ? SRS_REGISTERED : SRS_NOT_REGISTERED ); + 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; } @@ -1009,41 +1007,94 @@ 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 ); - const bool bDirectoryAddressValid = NetworkUtil::ParseNetworkAddress ( strNetworkAddress, DirectoryAddress, false ); - // lock the mutex again now that the address has been resolved. - locker.relock(); + const QString strNetworkAddress = NetworkUtil::GetDirectoryAddress ( DirectoryType, strDirectoryAddress ); + + // invalidate current directory address until resolved + DirectoryAddress = CHostAddress(); - if ( bIsRegister ) + // get a new sequence number for matching the resolved callback + const int seq = ++iResolverSeq; + + // 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 ) { - if ( bDirectoryAddressValid ) - { - // register server - SetSvrRegStatus ( SRS_REQUESTED ); + // lock the mutex again before calling SetSvrRegStatus() + locker.relock(); + 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] ); + + // 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; + } } + 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..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(); @@ -256,6 +259,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..03f6dca376 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -855,112 +855,60 @@ 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 bool 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; + // 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 ); } ); } -#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]) + // note that \w only matches ASCII as QRegularExpression::UseUnicodePropertiesOption is not set + "(?!.*?_)" + // 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 + "(?!-|(?:.*?\\.-))" + // doesn't contain dash at the end of a label + "(?!.*?-\\.)" + "(?!.*?-$)" + // starts with an alphanumeric char + "(?=\\w)" + // not longer than 253 chars + "(?!.{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,81 +918,235 @@ 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; - // qInfo() << qUtf8Printable ( QString ( "Parsed network address %1" ).arg ( InetAddr.toString() ) ); + // 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 ) ); - HostAddress = CHostAddress ( InetAddr, iNetPort ); + 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; + } + + 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() ) + { + // Jamulus doesn't handle multiple SRV records, so warn if they are found + qWarning() << "SRV returned" << records.length() << "records"; + } + } - return true; + dns->deleteLater(); + + // SRV failed - lookup host directly + 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(); + + return true; + } +#endif + + return resolveHostname ( strHost, iNetPort, context, slot ); } CHostAddress NetworkUtil::GetLocalAddress() diff --git a/src/util.h b/src/util.h index 08e45166cb..f338d4ce0e 100644 --- a/src/util.h +++ b/src/util.h @@ -48,6 +48,7 @@ #include #include #include +#include #ifdef _WIN32 # include # include @@ -107,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 @@ -1102,13 +1102,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 SRV 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();