Introduction to the turn protocol of webrtc P2P

1. Introduction to TURN

The full name of TURN is Traversal Using Relays around NAT, which is an extension of STUN/RFC5389, mainly adding the Relay function. If the terminal is behind NAT, it may be impossible for the terminal to communicate directly with its peer (peer) under certain circumstances. At this time, the server on the public network needs to be used as a relay to forward the incoming and outgoing data. . The forwarding protocol is defined as TURN. TURN differs from other relay protocols in that it allows clients to communicate with multiple different peers using the same relay address.

The client using the TURN protocol must be able to communicate with the peer through the relay address, and be able to know the IP address and port of each peer (to be precise, it should be the server reflection address of the peer). How these actions are accomplished is outside the scope of the TURN protocol. One of the available ways is that the client informs the peer information through email, and another way is that the client uses some specified protocols, such as "introduction" or "rendezvous", see RFC5128 for details

If TURN is used in the ICE protocol, the relay address will be used as a candidate, and ICE will evaluate among multiple candidates and select the most suitable communication address. Generally, relays have the lowest priority. The TURN protocol is designed as part of the ICE protocol (Interactive Connectivity Establishment), and it is strongly recommended that users use ICE in their programs, but it can also run independently of ICE. It is worth mentioning that the TURN protocol itself is an extension of STUN, so most TURN packets are of the STUN type. As an extension of STUN, TURN adds new methods and attributes.

2. Operation overview

In a typical situation, the TURN client is connected to the internal network and reaches the public network through one or more NATs. The TURN server is set up in the public network. Different clients use the TURN server as a relay to communicate with other peers. As shown below:

                                        Peer A
                                        Server-Reflexive    +---------+
                                        Transport Address   |         |
                                        192.0.2.150:32102   |         |
                                            |              /|         |
                          TURN              |            / ^|  Peer A |
    Client’s              Server            |           /  ||         |
    Host Transport        Transport         |         //   ||         |
    Address               Address           |       //     |+---------+
   10.1.1.2:49721       192.0.2.15:3478     |+-+  //     Peer A
            |               |               ||N| /       Host Transport
            |   +-+         |               ||A|/        Address
            |   | |         |               v|T|     192.168.100.2:49582
            |   | |         |               /+-+
 +---------+|   | |         |+---------+   /              +---------+
 |         ||   |N|         ||         | //               |         |
 | TURN    |v   | |         v| TURN    |/                 |         |
 | Client  |----|A|----------| Server  |------------------|  Peer B |
 |         |    | |^         |         |^                ^|         |
 |         |    |T||         |         ||                ||         |
 +---------+    | ||         +---------+|                |+---------+
                | ||                    |                |
                | ||                    |                |
                +-+|                    |                |
                   |                    |                |
                   |                    |                |
             Client’s                   |            Peer B
             Server-Reflexive    Relayed             Transport
             Transport Address   Transport Address   Address
             192.0.2.1:7000      192.0.2.15:50000     192.0.2.210:49191  

In the figure above, the TURN Client on the left is a client behind NAT (intranet address is 10.1.1.2:49721). After connecting to the TURN server on the public network (default port 3478), the server will get a reflection address of the Client (Reflexive Transport Address, that is, the public network IP and port assigned by NAT) 192.0.2.1:7000. At this time, the Client will create or manage ALLOCATION through the TURN command. Allocation is a data structure on the server, including the information of the relay address. The server will then assign a relay address to the Client, which is 192.0.2.15:50000 in the figure. If the other two peers want to communicate with the Client through the TURN protocol, they can directly send and receive data to the relay address. The TURN server The data sent to the specified relay address will be forwarded to the corresponding Client, here is its reflection address.

Each allocation on the server corresponds to only one client, and there is only one relay address, so when a data packet arrives at a relay address, the server always knows where it should be forwarded. But it is worth mentioning that a Client may have multiple allocations on a Server at the same time, which does not contradict the above rules.

3. Transmission

In the protocol, the connection between the TURN server and the peer is based on UDP, but the server and the client can transmit STUN messages through other connections, such as TCP/UDP/TLS-over-TCP. Client When transmitting data through relays, if TCP is used, it will also be converted to UDP on the server side, so it is recommended that the client use UDP for transmission. As for why TCP is supported, it is because some firewalls will completely block UDP data. For the TCP data of the three-way handshake, there is no isolation.

4. Allocations

To obtain a relay allocation on the server side, the client must use the allocation transaction. The client sends an allocation request (Allocate request) to the server, and then the server returns an allocation success response, which includes the allocated address. The client can describe in the attribute field The type of allocation it wants (such as life cycle). Since the relay data achieves secure transmission, the server will require authentication of the client, mainly using STUN's long-term credential mechanism.

Once the relay transport address is allocated, the client must keep it alive. The usual method is to send a refresh request (Refresh request) to the server. This is a standard method in TURN. The refresh frequency depends on the lifetime of the allocation. , the default is 10 minutes. The client can also specify a longer lifetime in the refresh request, and the server will return an actually allocated time. When the client wants to communicate with the middle finger, it can send a refresh with a lifetime of 0 ask.

Both the server and the client store a 5-tuple (5-TUPLE) information. For example, for the client, the 5-tuple includes the client's local address/port, server address/port, and transmission protocol; the server is similar , just change the client's address to its reflection address, because that's what the server sees. Both the server and the client carry 5-TUPLE information in the allocation request, and it is also used in the subsequent information transmission, So they both know which allocation corresponds to which transfer.

TURN                                 TURN           Peer          Peer
client                               server          A             B
  |-- Allocate request --------------->|             |             |
  |                                    |             |             |
  |<--------------- Allocate failure --|             |             |
  |                 (401 Unauthorized) |             |             |
  |                                    |             |             |
  |-- Allocate request --------------->|             |             |
  |                                    |             |             |
  |<---------- Allocate success resp --|             |             |
  |            (192.0.2.15:50000)      |             |             |
  //                                   //            //            //
  |                                    |             |             |
  |-- Refresh request ---------------->|             |             |
  |                                    |             |             |
  |<----------- Refresh success resp --|             |             |
  |                                    |             |             |

As shown in the figure above, the client first sends an Allocate request without verification information, so the STUN server will return an error response, and the client will request again after receiving the error and add the required verification information to make a successful allocation.

5. Send Mechanism

There are two methods between client and peer to exchange application information through TURN server, the first is to use Send and Data methods (method), the second is to use channels (channels), both methods tell the server which The peer should receive the data, and the server tells the client which peer the data came from.

Send Mechanism uses the Send and Data instructions (Indication). The Send instruction is used to send data from the client to the server, and the Data instruction is used to send data from the server to the client. When using the Send instruction, the client sends a Send Indication to the server, which contains:

•XOR-PEER-ADDRESS属性,指定对等端的(服务器反射)地址.
•DATA属性,包含要传给对等端的信息.  

When the server receives the Send Indication, it will parse the data of the DATA part and forward it to the corresponding endpoint in UDP format, and use the relay address of the client as the source address when encapsulating the data packet. Thus from The data sent by the peer to the relay address will also be forwarded to the client by the server. It is worth mentioning that Send/Data Indication does not support verification, because the long-term verification mechanism does not support the verification of indication, so in order to prevent Attack, TURN requires the client to install a permission to the peer before sending an indication to the peer. As shown in the figure below, the client does not have a permission to Peer B, causing its indication packet to be discarded by the server. For peer The same is true for B:

TURN                                 TURN           Peer          Peer
client                               server          A             B
  |                                    |             |             |
  |-- CreatePermission req (Peer A) -->|             |             |
  |<-- CreatePermission success resp --|             |             |
  |                                    |             |             |
  |--- Send ind (Peer A)-------------->|             |             |
  |                                    |=== data ===>|             |
  |                                    |             |             |
  |                                    |<== data ====|             |
  |<-------------- Data ind (Peer A) --|             |             |
  |                                    |             |             |
  |                                    |             |             |
  |--- Send ind (Peer B)-------------->|             |             |
  |                                    | dropped     |             |
  |                                    |             |             |
  |                                    |<== data ==================|
  |                            dropped |             |             |
  |                                    |             |             |  

TURN supports two ways to create permissions, one is to send CreatePermission request

6. Channel mechanism (Channels)

For some applications, such as VOIP (Voice over IP), the additional 36-byte format information in the Send/Data Indication will increase the bandwidth pressure between the client and the server. To improve this situation, TURN provides a second A method to allow client and peer to exchange data. This method uses another data packet format, namely ChannelData message, channel data message. ChannelData message does not use STUN header, but uses a 4-byte header, which contains a Called the value of the channel number (channel number). Each channel number in use is bound to a specific peer, that is, as a token of the peer's address.

To bind a channel to a peer, the client first sends a Channel Bind Request (ChannelBind Request) to the server, and specifies an unbound channel number and the address information of the peer. After binding, both the client and the server Can send and forward data through ChannelData message. Channel binding lasts for 10 minutes by default, and the duration can be refreshed by resending ChannelBind Request. Unlike Allocation, there is no way to directly delete the binding, only waiting for its timeout Automatically lapse.

TURN                                 TURN           Peer          Peer
client                               server          A             B
  |                                    |             |             |
  |-- ChannelBind req ---------------->|             |             |
  | (Peer A to 0x4001)                 |             |             |
  |                                    |             |             |
  |<---------- ChannelBind succ resp --|             |             |
  |                                    |             |             |
  |-- [0x4001] data ------------------>|             |             |
  |                                    |=== data ===>|             |
  |                                    |             |             |
  |                                    |<== data ====|             |
  |<------------------ [0x4001] data --|             |             |
  |                                    |             |             |
  |--- Send ind (Peer A)-------------->|             |             |
  |                                    |=== data ===>|             |
  |                                    |             |             |
  |                                    |<== data ====|             |
  |<------------------ [0x4001] data --|             |             |
  |                                    |             |             |  

In the figure above, 0x4001 is the channel number, that is, the first 2 bytes in the header of the ChannelData message. It is worth mentioning that the selection of the channel number has the following requirements:

•0x0000-0x3FFF : 这一段的值不能用来作为信道号
•0x4000-0x7FFF : 这一段是可以作为信道号的值,一共有16383种不同值在目前来看是足够用的
•0x8000-0xFFFF : 这一段是保留值,留给以后使用    

7. Examples

As mentioned in the previous chapter, because RFC is a standard protocol, it often has good compatibility and scalability in implementation. Existing open source P2P applications can be easily connected to them if they are designed according to the standard. Among them The famous one is PJSIP. PJSIP is an open source multimedia communication library that implements many standard protocols, such as SIP, SDP, RTP, STUN, TURN and ICE. Of course, we can also implement it ourselves. For example, TurnServer on GitHub is one of them that supports TURN The implementation of the server. The following is a brief analysis of the TURN data packet in the LAN environment. First, there are the following machine conditions:

•TurnServer运行在192.168.1.110,使用默认端口3478,采用用户名和密码验证,其中用户名为pannzh,密码123456
•TurnClient运行在192.168.1.106,为了方便,令peer也在192.168.1.106运行,端口为59593  

Here wireshark is used to capture and analyze packets. First, TurnClient sends an Allocation request:

1.png

It can be seen that the first request was rejected by the server, because the latter required nonce verification information, and the server's return contained nonce information, in addition to ERROR-CODE, SOFTWARE, and FINGERPRINT attributes.

2.png

In the next request request, the client adds the received nonce, and attributes such as USERNAME and REALM, and sends it to TurnServer again:

3.png

The server receives the correct allocation request, so it returns the succcess response, and you can see that the return has the default lifetime of 1800 seconds, XOR-MAPPED-ADDRESS and XOR-RELAY-ADDRESS and other attributes:

4.png

As mentioned earlier, if you want to communicate with the peer, you must first create a permission, so the Client sends a CreatePermission request to the server, which carries the information of the peer:

5.png

If the server passes the verification, it will return a success response, and then the Client can communicate with the Peer through the two methods mentioned above, such as the Send indication method below:

6.png

By sending an indication to the TurnServer to inform the receiver of the data and the content of the data, the TurnServer can forward it, thereby indirectly sending DATA to the peer. From the point of view of the peer, it is to receive a relay address from the client 192.168.1.110:65315 UDP packets to the destination address 192.168.1.106:59593 (that is, the peer address).

Introduction to the turn protocol of the original webrtc P2P - short book 

★The business card at the end of the article can receive audio and video development learning materials for free, including (FFmpeg, webRTC, rtmp, hls, rtsp, ffplay, srs) and audio and video learning roadmaps, etc.

see below!

 

Guess you like

Origin blog.csdn.net/yinshipin007/article/details/132307491