📄 turnsocket.cxx
字号:
{ // Missing RemoteAddress or ChannelNumber attribute WarningLog(<< "DataInd missing attributes."); return asio::error_code(reTurn::MissingAttributes, asio::error::misc_category); } StunTuple remoteTuple; remoteTuple.setTransportType(mRelayTuple.getTransportType()); StunMessage::setTupleFromStunAtrAddress(remoteTuple, stunMessage.mTurnPeerAddress); RemotePeer* remotePeer = mChannelManager.findRemotePeerByPeerAddress(remoteTuple); if(!remotePeer) { // Remote Peer not found - discard data WarningLog(<< "Data received from unknown RemotePeer - discarding"); return asio::error_code(reTurn::UnknownRemoteAddress, asio::error::misc_category); } if(remotePeer->getServerToClientChannel() != 0 && remotePeer->getServerToClientChannel() != stunMessage.mTurnChannelNumber) { // Mismatched channel number WarningLog(<< "Channel number received in DataInd (" << (int)stunMessage.mTurnChannelNumber << ") does not match existing number for RemotePeer (" << (int)remotePeer->getServerToClientChannel() << ")."); return asio::error_code(reTurn::InvalidChannelNumberReceived, asio::error::misc_category); } if(!remotePeer->isServerToClientChannelConfirmed()) { remotePeer->setServerToClientChannel(stunMessage.mTurnChannelNumber); remotePeer->setServerToClientChannelConfirmed(); mChannelManager.addRemotePeerServerToClientChannelLookup(remotePeer); } if(mLocalBinding.getTransportType() == StunTuple::UDP) { // If UDP, then send TurnChannelConfirmationInd StunMessage channelConfirmationInd; channelConfirmationInd.createHeader(StunMessage::StunClassIndication, StunMessage::TurnChannelConfirmationMethod); channelConfirmationInd.mHasTurnPeerAddress = true; channelConfirmationInd.mTurnPeerAddress = stunMessage.mTurnPeerAddress; channelConfirmationInd.mHasTurnChannelNumber = true; channelConfirmationInd.mTurnChannelNumber = stunMessage.mTurnChannelNumber; // send channelConfirmationInd to local client unsigned int bufferSize = 8 /* Stun Header */ + 36 /* Remote Address (v6) */ + 8 /* TurnChannelNumber */ + 4 /* Turn Frame size */; resip::Data buffer(bufferSize, resip::Data::Preallocate); unsigned int writeSize = channelConfirmationInd.stunEncodeFramedMessage((char*)buffer.data(), bufferSize); DebugLog(<< "Channel confirmation indication send for channel: " << stunMessage.mTurnChannelNumber); errorCode = rawWrite(buffer.data(), writeSize); } if(stunMessage.mHasTurnData) { if(stunMessage.mTurnData->size() > size) { // Passed in buffer is not large enough WarningLog(<< "Passed in buffer not large enough."); return asio::error_code(reTurn::BufferTooSmall, asio::error::misc_category); } memcpy(buffer, stunMessage.mTurnData->data(), stunMessage.mTurnData->size()); size = (unsigned int)stunMessage.mTurnData->size(); if(sourceAddress != 0) { *sourceAddress = remoteTuple.getAddress(); } if(sourcePort != 0) { *sourcePort = remoteTuple.getPort(); } } else { size = 0; } } else if(stunMessage.mClass == StunMessage::StunClassIndication && stunMessage.mMethod == StunMessage::TurnChannelConfirmationMethod) { if(!stunMessage.mHasTurnPeerAddress || !stunMessage.mHasTurnChannelNumber) { // Missing RemoteAddress or ChannelNumber attribute WarningLog(<< "DataInd missing attributes."); return asio::error_code(reTurn::MissingAttributes, asio::error::misc_category); } StunTuple remoteTuple; remoteTuple.setTransportType(mRelayTuple.getTransportType()); StunMessage::setTupleFromStunAtrAddress(remoteTuple, stunMessage.mTurnPeerAddress); RemotePeer* remotePeer = mChannelManager.findRemotePeerByClientToServerChannel(stunMessage.mTurnChannelNumber); if(!remotePeer) { // Remote Peer not found - discard WarningLog(<< "Received ChannelConfirmationInd for unknown channel (" << stunMessage.mTurnChannelNumber << ") - discarding"); return asio::error_code(reTurn::InvalidChannelNumberReceived, asio::error::misc_category); } if(remotePeer->getPeerTuple() != remoteTuple) { // Mismatched remote address WarningLog(<< "RemoteAddress associated with channel (" << remotePeer->getPeerTuple() << ") does not match ChannelConfirmationInd (" << remoteTuple << ")."); return asio::error_code(reTurn::UnknownRemoteAddress, asio::error::misc_category); } remotePeer->setClientToServerChannelConfirmed(); size = 0; } else if(stunMessage.mClass == StunMessage::StunClassRequest && stunMessage.mMethod == StunMessage::BindMethod) { // Note: handling of BindRequest is not fully backwards compatible with RFC3489 - it is inline with bis11 StunMessage response; // form the outgoing message response.mClass = StunMessage::StunClassSuccessResponse; response.mMethod = StunMessage::BindMethod; // Copy over TransactionId response.mHeader.magicCookieAndTid = stunMessage.mHeader.magicCookieAndTid; // Add XOrMappedAddress to response response.mHasXorMappedAddress = true; StunMessage::setStunAtrAddressFromTuple(response.mXorMappedAddress, stunMessage.mRemoteTuple); // send bind response to local client unsigned int bufferSize = 8 /* Stun Header */ + 36 /* XorMapped Address (v6) */ + 4 /* Turn Frame size */; resip::Data buffer(bufferSize, resip::Data::Preallocate); unsigned int writeSize = response.stunEncodeFramedMessage((char*)buffer.data(), bufferSize); errorCode = rawWrite(buffer.data(), writeSize); size = 0; // go back to receiving } else if(stunMessage.mClass == StunMessage::StunClassIndication && stunMessage.mMethod == StunMessage::BindMethod) { // Nothing to do size = 0; } else if(stunMessage.mClass == StunMessage::StunClassSuccessResponse || stunMessage.mClass == StunMessage::StunClassErrorResponse) { // Received a stray or response retranmission - ignore size = 0; } else { // TODO - handle others ???? } } else { WarningLog(<< "Read Invalid StunMsg."); return asio::error_code(reTurn::ErrorParsingMessage, asio::error::misc_category); } return errorCode;}void TurnSocket::startReadTimer(unsigned int timeout){ if(timeout != 0) { mReadTimer.expires_from_now(boost::posix_time::milliseconds(timeout)); mReadTimer.async_wait(boost::bind(&TurnSocket::handleRawReadTimeout, this, asio::placeholders::error)); }}void TurnSocket::handleRawRead(const asio::error_code& errorCode, size_t bytesRead){ mBytesRead = bytesRead; mReadErrorCode = errorCode; mReadTimer.cancel();}void TurnSocket::handleRawReadTimeout(const asio::error_code& errorCode){ if(!errorCode) { cancelSocket(); }}asio::error_code TurnSocket::checkIfAllocationRefreshRequired(){ if(mHaveAllocation && (time(0) >= mAllocationRefreshTime)) { // Do refresh return refreshAllocation(); } return asio::error_code(); // 0}StunMessage* TurnSocket::sendRequestAndGetResponse(StunMessage& request, asio::error_code& errorCode){ unsigned int writesize = request.stunEncodeFramedMessage(mWriteBuffer, sizeof(mWriteBuffer)); bool sendRequest = true; bool reliableTransport = mLocalBinding.getTransportType() != StunTuple::UDP; unsigned int timeout = reliableTransport ? TCP_RESPONSE_TIME : UDP_RT0; unsigned int totalTime = 0; unsigned int requestsSent = 0; unsigned int readsize = 0; while(true) { if(sendRequest) { // Send request to Turn Server if(requestsSent > 0) { DebugLog(<< "TurnSocket: retranmitting request..."); } requestsSent++; errorCode = rawWrite(mWriteBuffer, writesize); if(errorCode) { return 0; } sendRequest = false; } // Wait for response errorCode = rawRead(timeout, &readsize); if(errorCode) { if(errorCode == asio::error::operation_aborted) { totalTime += timeout; if(reliableTransport || requestsSent == UDP_MAX_RETRANSMITS) { InfoLog(<< "Timed out waiting for Stun response!"); errorCode = asio::error_code(reTurn::ResponseTimeout, asio::error::misc_category); return 0; } // timed out and should retransmit - calculate next timeout if(requestsSent == UDP_MAX_RETRANSMITS - 1) { timeout = UDP_FINAL_REQUEST_TIME; } else { timeout = (timeout*2); } sendRequest = true; continue; } return 0; } if(readsize > 4) { unsigned short channelNumber; memcpy(&channelNumber, &mReadBuffer[0], 2); channelNumber = ntohs(channelNumber); if(channelNumber == 0) // Channel 0 is Stun/Turn messaging { StunMessage* response = new StunMessage(mLocalBinding, mConnectedTuple, &mReadBuffer[4], readsize-4); if(response->isValid()) { if(!response->checkMessageIntegrity(request.mHmacKey)) { WarningLog(<< "Stun response message integrity is bad!"); delete response; errorCode = asio::error_code(reTurn::BadMessageIntegrity, asio::error::misc_category); return 0; } // Check that TID matches request if(!(response->mHeader.magicCookieAndTid == request.mHeader.magicCookieAndTid)) { InfoLog(<< "Stun response TID does not match request - discarding!"); delete response; continue; // read next message } errorCode = asio::error_code(reTurn::Success, asio::error::misc_category); return response; } else { WarningLog(<< "Stun response message is invalid!"); delete response; errorCode = asio::error_code(reTurn::ErrorParsingMessage, asio::error::misc_category); return 0; } } else // Channel != 0 indicates Turn Data { // TODO - handle buffering of Turn data that is receive while waiting for a Request/Response errorCode = asio::error_code(reTurn::FrameError, asio::error::misc_category); return 0; } } else { // Less data than frame size received errorCode = asio::error_code(reTurn::FrameError, asio::error::misc_category); return 0; } }}} // namespace/* ==================================================================== Original contribution Copyright (C) 2007 Plantronics, Inc. Provided under the terms of the Vovida Software License, Version 2.0. The Vovida Software License, Version 2.0 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ==================================================================== */
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -