Source Code Analysis of WebRTC Collection Relay Address Candidates

I. Introduction

        In this blog , we introduced WebRTC candidates and focused on analyzing the process of WebRTC collecting host candidates. This article will introduce how WebRTC collects relay address candidates (Relayed Address).

        If you are not familiar with the concept of Relay or the working principle of TURN, it is recommended to read this blog before continuing to read.

2. Source code analysis

1. Send an Allocate Request

        As shown below, call AllocationSequence::CreateRelayPorts first, return directly if the relay candidate is disabled or the TURN server address is not configured, otherwise enter CreateTurnPort.

        AllocationSequence::CreateTurnPort is mainly to create TurnPort, then add TurnPort to std::vector<PortData> ports_ object through BasicPortAllocatorSession::AddAllocatedPort, and execute TurnPort::PrepareAddress() to start preparing to collect addresses.

 

         In the TurnPort::PrepareAddress function, it first judges that if the address of the TURN server is a domain name, it first performs domain name address resolution, otherwise enters the else branch, and first creates a connection with the TURN Server (CreateTurnClientSocket). The connection between the TURN Client and the TURN Server can be UDP or TCP or TLS over TCP, send the AllocateRequest request through SendRequest(new TurnAllocateRequest(this), 0) after the connection is established.

        AllocateRequest is actually a STUN message with Message Type=0x0003.

2. Receive and parse the Allocate Response

        After receiving the response message, it will call back AllocationSequence::OnReadPacket, which checks that the sender address of the received data packet is in the TURN Server address we configured, and if so, calls TurnPort::HandleIncomingPacket for processing.

        TurnPort::HandleIncomingPacket will judge that if it is a ChannelData message, it will call HandleChannelData processing, if it is a Data Indication message, it will call HandleDataIndication processing, both of which are the processing logic of the turn client when the Peer sends data to the turn client through the turn server.

        Then call StunRequestManager::CheckResponse to check whether the message is a response to the request sent by the local end. For a successful response, StunRequest::OnResponse will be executed for processing, and for AllocationRequest, TurnAllocateRequest::OnResponse will be called for processing.

         After receiving the Allocation Response, take out the XOR_RELAYED_ADDRESS of the response message, call TurnPort::OnAllocateSuccess to add the Relayed Address (relay address candidate), and then call TurnPort::ScheduleRefresh to enable connection keep alive (send TurnRefreshRequest), so far the relay address candidate is The collection is complete.

Guess you like

Origin blog.csdn.net/weixin_38102771/article/details/124535830