1
0
Fork 0
mirror of https://github.com/ossrs/srs.git synced 2025-03-09 15:49:59 +00:00

SquashSRS4: Regine DTLS and add regression tests. 4.0.84

This commit is contained in:
winlin 2021-03-10 08:29:40 +08:00
parent dc93836489
commit e74810230a
32 changed files with 4740 additions and 1275 deletions

View file

@ -0,0 +1,278 @@
// The MIT License (MIT)
//
// Copyright (c) 2021 srs-bench(ossrs)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vnet_test
import (
"net"
vnet_proxy "github.com/ossrs/srs-bench/vnet"
"github.com/pion/logging"
"github.com/pion/transport/vnet"
)
// Proxy many vnet endpoint to one real server endpoint.
// For example:
// vnet(10.0.0.11:5787) => proxy => 192.168.1.10:8000
// vnet(10.0.0.11:5788) => proxy => 192.168.1.10:8000
// vnet(10.0.0.11:5789) => proxy => 192.168.1.10:8000
func ExampleUDPProxyManyToOne() { // nolint:govet
var clientNetwork *vnet.Net
var serverAddr *net.UDPAddr
if addr, err := net.ResolveUDPAddr("udp4", "192.168.1.10:8000"); err != nil {
// handle error
} else {
serverAddr = addr
}
// Setup the network and proxy.
if true {
// Create vnet WAN with one endpoint, please read from
// https://github.com/pion/transport/tree/master/vnet#example-wan-with-one-endpoint-vnet
router, err := vnet.NewRouter(&vnet.RouterConfig{
CIDR: "0.0.0.0/0",
LoggerFactory: logging.NewDefaultLoggerFactory(),
})
if err != nil {
// handle error
}
// Create a network and add to router, for example, for client.
clientNetwork = vnet.NewNet(&vnet.NetConfig{
StaticIP: "10.0.0.11",
})
if err = router.AddNet(clientNetwork); err != nil {
// handle error
}
// Start the router.
if err = router.Start(); err != nil {
// handle error
}
defer router.Stop() // nolint:errcheck
// Create a proxy, bind to the router.
proxy, err := vnet_proxy.NewProxy(router)
if err != nil {
// handle error
}
defer proxy.Close() // nolint:errcheck
// Start to proxy some addresses, clientNetwork is a hit for proxy,
// that the client in vnet is from this network.
if err := proxy.Proxy(clientNetwork, serverAddr); err != nil {
// handle error
}
}
// Now, all packets from client, will be proxy to real server, vice versa.
client0, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5787")
if err != nil {
// handle error
}
_, _ = client0.WriteTo([]byte("Hello"), serverAddr)
client1, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5788")
if err != nil {
// handle error
}
_, _ = client1.WriteTo([]byte("Hello"), serverAddr)
client2, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5789")
if err != nil {
// handle error
}
_, _ = client2.WriteTo([]byte("Hello"), serverAddr)
}
// Proxy many vnet endpoint to one real server endpoint.
// For example:
// vnet(10.0.0.11:5787) => proxy => 192.168.1.10:8000
// vnet(10.0.0.11:5788) => proxy => 192.168.1.10:8000
func ExampleUDPProxyMultileTimes() { // nolint:govet
var clientNetwork *vnet.Net
var serverAddr *net.UDPAddr
if addr, err := net.ResolveUDPAddr("udp4", "192.168.1.10:8000"); err != nil {
// handle error
} else {
serverAddr = addr
}
// Setup the network and proxy.
var proxy *vnet_proxy.UDPProxy
if true {
// Create vnet WAN with one endpoint, please read from
// https://github.com/pion/transport/tree/master/vnet#example-wan-with-one-endpoint-vnet
router, err := vnet.NewRouter(&vnet.RouterConfig{
CIDR: "0.0.0.0/0",
LoggerFactory: logging.NewDefaultLoggerFactory(),
})
if err != nil {
// handle error
}
// Create a network and add to router, for example, for client.
clientNetwork = vnet.NewNet(&vnet.NetConfig{
StaticIP: "10.0.0.11",
})
if err = router.AddNet(clientNetwork); err != nil {
// handle error
}
// Start the router.
if err = router.Start(); err != nil {
// handle error
}
defer router.Stop() // nolint:errcheck
// Create a proxy, bind to the router.
proxy, err = vnet_proxy.NewProxy(router)
if err != nil {
// handle error
}
defer proxy.Close() // nolint:errcheck
}
if true {
// Start to proxy some addresses, clientNetwork is a hit for proxy,
// that the client in vnet is from this network.
if err := proxy.Proxy(clientNetwork, serverAddr); err != nil {
// handle error
}
// Now, all packets from client, will be proxy to real server, vice versa.
client0, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5787")
if err != nil {
// handle error
}
_, _ = client0.WriteTo([]byte("Hello"), serverAddr)
}
if true {
// It's ok to proxy multiple times, for example, the publisher and player
// might need to proxy when got answer.
if err := proxy.Proxy(clientNetwork, serverAddr); err != nil {
// handle error
}
client1, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5788")
if err != nil {
// handle error
}
_, _ = client1.WriteTo([]byte("Hello"), serverAddr)
}
}
// Proxy one vnet endpoint to one real server endpoint.
// For example:
// vnet(10.0.0.11:5787) => proxy0 => 192.168.1.10:8000
// vnet(10.0.0.11:5788) => proxy1 => 192.168.1.10:8001
// vnet(10.0.0.11:5789) => proxy2 => 192.168.1.10:8002
func ExampleUDPProxyOneToOne() { // nolint:govet
var clientNetwork *vnet.Net
var serverAddr0 *net.UDPAddr
if addr, err := net.ResolveUDPAddr("udp4", "192.168.1.10:8000"); err != nil {
// handle error
} else {
serverAddr0 = addr
}
var serverAddr1 *net.UDPAddr
if addr, err := net.ResolveUDPAddr("udp4", "192.168.1.10:8001"); err != nil {
// handle error
} else {
serverAddr1 = addr
}
var serverAddr2 *net.UDPAddr
if addr, err := net.ResolveUDPAddr("udp4", "192.168.1.10:8002"); err != nil {
// handle error
} else {
serverAddr2 = addr
}
// Setup the network and proxy.
if true {
// Create vnet WAN with one endpoint, please read from
// https://github.com/pion/transport/tree/master/vnet#example-wan-with-one-endpoint-vnet
router, err := vnet.NewRouter(&vnet.RouterConfig{
CIDR: "0.0.0.0/0",
LoggerFactory: logging.NewDefaultLoggerFactory(),
})
if err != nil {
// handle error
}
// Create a network and add to router, for example, for client.
clientNetwork = vnet.NewNet(&vnet.NetConfig{
StaticIP: "10.0.0.11",
})
if err = router.AddNet(clientNetwork); err != nil {
// handle error
}
// Start the router.
if err = router.Start(); err != nil {
// handle error
}
defer router.Stop() // nolint:errcheck
// Create a proxy, bind to the router.
proxy, err := vnet_proxy.NewProxy(router)
if err != nil {
// handle error
}
defer proxy.Close() // nolint:errcheck
// Start to proxy some addresses, clientNetwork is a hit for proxy,
// that the client in vnet is from this network.
if err := proxy.Proxy(clientNetwork, serverAddr0); err != nil {
// handle error
}
if err := proxy.Proxy(clientNetwork, serverAddr1); err != nil {
// handle error
}
if err := proxy.Proxy(clientNetwork, serverAddr2); err != nil {
// handle error
}
}
// Now, all packets from client, will be proxy to real server, vice versa.
client0, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5787")
if err != nil {
// handle error
}
_, _ = client0.WriteTo([]byte("Hello"), serverAddr0)
client1, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5788")
if err != nil {
// handle error
}
_, _ = client1.WriteTo([]byte("Hello"), serverAddr1)
client2, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5789")
if err != nil {
// handle error
}
_, _ = client2.WriteTo([]byte("Hello"), serverAddr2)
}

View file

@ -0,0 +1,222 @@
// The MIT License (MIT)
//
// Copyright (c) 2021 srs-bench(ossrs)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vnet
import (
"net"
"sync"
"time"
"github.com/pion/transport/vnet"
)
// A UDP proxy between real server(net.UDPConn) and vnet.UDPConn.
//
// High level design:
// ..............................................
// : Virtual Network (vnet) :
// : :
// +-------+ * 1 +----+ +--------+ :
// | :App |------------>|:Net|--o<-----|:Router | .............................
// +-------+ +----+ | | : UDPProxy :
// : | | +----+ +---------+ +---------+ +--------+
// : | |--->o--|:Net|-->o-| vnet. |-->o-| net. |--->-| :Real |
// : | | +----+ | UDPConn | | UDPConn | | Server |
// : | | : +---------+ +---------+ +--------+
// : | | ............................:
// : +--------+ :
// ...............................................
//
// The whole big picture:
// ......................................
// : Virtual Network (vnet) :
// : :
// +-------+ * 1 +----+ +--------+ :
// | :App |------------>|:Net|--o<-----|:Router | .............................
// +-------+ +----+ | | : UDPProxy :
// +-----------+ * 1 +----+ | | +----+ +---------+ +---------+ +--------+
// |:STUNServer|-------->|:Net|--o<-----| |--->o--|:Net|-->o-| vnet. |-->o-| net. |--->-| :Real |
// +-----------+ +----+ | | +----+ | UDPConn | | UDPConn | | Server |
// +-----------+ * 1 +----+ | | : +---------+ +---------+ +--------+
// |:TURNServer|-------->|:Net|--o<-----| | ............................:
// +-----------+ +----+ [1] | | :
// : 1 | | 1 <<has>> :
// : +---<>| |<>----+ [2] :
// : | +--------+ | :
// To form | *| v 0..1 :
// a subnet tree | o [3] +-----+ :
// : | ^ |:NAT | :
// : | | +-----+ :
// : +-------+ :
// ......................................
type UDPProxy struct {
// The router bind to.
router *vnet.Router
// Each vnet source, bind to a real socket to server.
// key is real server addr, which is net.Addr
// value is *aUDPProxyWorker
workers sync.Map
// For each endpoint, we never know when to start and stop proxy,
// so we stop the endpoint when timeout.
timeout time.Duration
// For utest, to mock the target real server.
// Optional, use the address of received client packet.
mockRealServerAddr *net.UDPAddr
}
// NewProxy create a proxy, the router for this proxy belongs/bind to. If need to proxy for
// please create a new proxy for each router. For all addresses we proxy, we will create a
// vnet.Net in this router and proxy all packets.
func NewProxy(router *vnet.Router) (*UDPProxy, error) {
v := &UDPProxy{router: router, timeout: 2 * time.Minute}
return v, nil
}
// Close the proxy, stop all workers.
func (v *UDPProxy) Close() error {
// nolint:godox // TODO: FIXME: Do cleanup.
return nil
}
// Proxy starts a worker for server, ignore if already started.
func (v *UDPProxy) Proxy(client *vnet.Net, server *net.UDPAddr) error {
// Note that even if the worker exists, it's also ok to create a same worker,
// because the router will use the last one, and the real server will see a address
// change event after we switch to the next worker.
if _, ok := v.workers.Load(server.String()); ok {
// nolint:godox // TODO: Need to restart the stopped worker?
return nil
}
// Not exists, create a new one.
worker := &aUDPProxyWorker{
router: v.router, mockRealServerAddr: v.mockRealServerAddr,
}
v.workers.Store(server.String(), worker)
return worker.Proxy(client, server)
}
// A proxy worker for a specified proxy server.
type aUDPProxyWorker struct {
router *vnet.Router
mockRealServerAddr *net.UDPAddr
// Each vnet source, bind to a real socket to server.
// key is vnet client addr, which is net.Addr
// value is *net.UDPConn
endpoints sync.Map
}
func (v *aUDPProxyWorker) Proxy(client *vnet.Net, serverAddr *net.UDPAddr) error { // nolint:gocognit
// Create vnet for real server by serverAddr.
nw := vnet.NewNet(&vnet.NetConfig{
StaticIP: serverAddr.IP.String(),
})
if err := v.router.AddNet(nw); err != nil {
return err
}
// We must create a "same" vnet.UDPConn as the net.UDPConn,
// which has the same ip:port, to copy packets between them.
vnetSocket, err := nw.ListenUDP("udp4", serverAddr)
if err != nil {
return err
}
// Start a proxy goroutine.
var findEndpointBy func(addr net.Addr) (*net.UDPConn, error)
// nolint:godox // TODO: FIXME: Do cleanup.
go func() {
buf := make([]byte, 1500)
for {
n, addr, err := vnetSocket.ReadFrom(buf)
if err != nil {
return
}
if n <= 0 || addr == nil {
continue // Drop packet
}
realSocket, err := findEndpointBy(addr)
if err != nil {
continue // Drop packet.
}
if _, err := realSocket.Write(buf[:n]); err != nil {
return
}
}
}()
// Got new vnet client, start a new endpoint.
findEndpointBy = func(addr net.Addr) (*net.UDPConn, error) {
// Exists binding.
if value, ok := v.endpoints.Load(addr.String()); ok {
// Exists endpoint, reuse it.
return value.(*net.UDPConn), nil
}
// The real server we proxy to, for utest to mock it.
realAddr := serverAddr
if v.mockRealServerAddr != nil {
realAddr = v.mockRealServerAddr
}
// Got new vnet client, create new endpoint.
realSocket, err := net.DialUDP("udp4", nil, realAddr)
if err != nil {
return nil, err
}
// Bind address.
v.endpoints.Store(addr.String(), realSocket)
// Got packet from real serverAddr, we should proxy it to vnet.
// nolint:godox // TODO: FIXME: Do cleanup.
go func(vnetClientAddr net.Addr) {
buf := make([]byte, 1500)
for {
n, _, err := realSocket.ReadFrom(buf)
if err != nil {
return
}
if n <= 0 {
continue // Drop packet
}
if _, err := vnetSocket.WriteTo(buf[:n], vnetClientAddr); err != nil {
return
}
}
}(addr)
return realSocket, nil
}
return nil
}

View file

@ -0,0 +1,61 @@
// The MIT License (MIT)
//
// Copyright (c) 2021 srs-bench(ossrs)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vnet
import (
"net"
)
func (v *UDPProxy) Deliver(sourceAddr, destAddr net.Addr, b []byte) (nn int, err error) {
v.workers.Range(func(key, value interface{}) bool {
if nn, err := value.(*aUDPProxyWorker).Deliver(sourceAddr, destAddr, b); err != nil {
return false // Fail, abort.
} else if nn == len(b) {
return false // Done.
}
return true // Deliver by next worker.
})
return
}
func (v *aUDPProxyWorker) Deliver(sourceAddr, destAddr net.Addr, b []byte) (nn int, err error) {
addr, ok := sourceAddr.(*net.UDPAddr)
if !ok {
return 0, nil
}
// TODO: Support deliver packet from real server to vnet.
// If packet is from vent, proxy to real server.
var realSocket *net.UDPConn
if value, ok := v.endpoints.Load(addr.String()); !ok {
return 0, nil
} else {
realSocket = value.(*net.UDPConn)
}
// Send to real server.
if _, err := realSocket.Write(b); err != nil {
return 0, err
}
return len(b), nil
}

View file

@ -0,0 +1,184 @@
// The MIT License (MIT)
//
// Copyright (c) 2021 srs-bench(ossrs)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vnet
import (
"context"
"fmt"
"github.com/pion/logging"
"github.com/pion/transport/vnet"
"net"
"sync"
"testing"
"time"
)
// vnet client:
// 10.0.0.11:5787
// proxy to real server:
// 192.168.1.10:8000
func TestUDPProxyDirectDeliver(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
var r0, r1, r2 error
defer func() {
if r0 != nil || r1 != nil || r2 != nil {
t.Errorf("fail for ctx=%v, r0=%v, r1=%v, r2=%v", ctx.Err(), r0, r1, r2)
}
}()
var wg sync.WaitGroup
defer wg.Wait()
// Timeout, fail
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
select {
case <-ctx.Done():
case <-time.After(time.Duration(*testTimeout) * time.Millisecond):
r2 = fmt.Errorf("timeout")
}
}()
// For utest, we always proxy vnet packets to the random port we listen to.
mockServer := NewMockUDPEchoServer()
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
if err := mockServer.doMockUDPServer(ctx); err != nil {
r0 = err
}
}()
// Create a vent and proxy.
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
// When real server is ready, start the vnet test.
select {
case <-ctx.Done():
return
case <-mockServer.realServerReady.Done():
}
doVnetProxy := func() error {
router, err := vnet.NewRouter(&vnet.RouterConfig{
CIDR: "0.0.0.0/0",
LoggerFactory: logging.NewDefaultLoggerFactory(),
})
if err != nil {
return err
}
clientNetwork := vnet.NewNet(&vnet.NetConfig{
StaticIP: "10.0.0.11",
})
if err = router.AddNet(clientNetwork); err != nil {
return err
}
if err := router.Start(); err != nil {
return err
}
defer router.Stop()
proxy, err := NewProxy(router)
if err != nil {
return err
}
defer proxy.Close()
// For utest, mock the target real server.
proxy.mockRealServerAddr = mockServer.realServerAddr
// The real server address to proxy to.
// Note that for utest, we will proxy to a local address.
serverAddr, err := net.ResolveUDPAddr("udp4", "192.168.1.10:8000")
if err != nil {
return err
}
if err := proxy.Proxy(clientNetwork, serverAddr); err != nil {
return err
}
// Now, all packets from client, will be proxy to real server, vice versa.
client, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5787")
if err != nil {
return err
}
// When system quit, interrupt client.
selfKill, selfKillCancel := context.WithCancel(context.Background())
go func() {
<-ctx.Done()
selfKillCancel()
client.Close()
}()
// Write by vnet client.
if _, err := client.WriteTo([]byte("Hello"), serverAddr); err != nil {
return err
}
buf := make([]byte, 1500)
if n, addr, err := client.ReadFrom(buf); err != nil {
if selfKill.Err() == context.Canceled {
return nil
}
return err
} else if n != 5 || addr == nil {
return fmt.Errorf("n=%v, addr=%v", n, addr)
} else if string(buf[:n]) != "Hello" {
return fmt.Errorf("data %v", buf[:n])
}
// Directly write, simulate the ARQ packet.
// We should got the echo packet also.
if _, err := proxy.Deliver(client.LocalAddr(), serverAddr, []byte("Hello")); err != nil {
return err
}
if n, addr, err := client.ReadFrom(buf); err != nil {
if selfKill.Err() == context.Canceled {
return nil
}
return err
} else if n != 5 || addr == nil {
return fmt.Errorf("n=%v, addr=%v", n, addr)
} else if string(buf[:n]) != "Hello" {
return fmt.Errorf("data %v", buf[:n])
}
return err
}
if err := doVnetProxy(); err != nil {
r1 = err
}
}()
}

View file

@ -0,0 +1,615 @@
// The MIT License (MIT)
//
// Copyright (c) 2021 srs-bench(ossrs)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vnet
import (
"context"
"errors"
"flag"
"fmt"
"net"
"os"
"sync"
"testing"
"time"
"github.com/pion/logging"
"github.com/pion/transport/vnet"
)
type MockUDPEchoServer struct {
realServerAddr *net.UDPAddr
realServerReady context.Context
realServerReadyCancel context.CancelFunc
}
func NewMockUDPEchoServer() *MockUDPEchoServer {
v := &MockUDPEchoServer{}
v.realServerReady, v.realServerReadyCancel = context.WithCancel(context.Background())
return v
}
func (v *MockUDPEchoServer) doMockUDPServer(ctx context.Context) error {
// Listen to a random port.
laddr, err := net.ResolveUDPAddr("udp4", "127.0.0.1:0")
if err != nil {
return err
}
conn, err := net.ListenUDP("udp4", laddr)
if err != nil {
return err
}
v.realServerAddr = conn.LocalAddr().(*net.UDPAddr)
v.realServerReadyCancel()
// When system quit, interrupt client.
selfKill, selfKillCancel := context.WithCancel(context.Background())
go func() {
<-ctx.Done()
selfKillCancel()
_ = conn.Close()
}()
// Note that if they has the same ID, the address should not changed.
addrs := make(map[string]net.Addr)
// Start an echo UDP server.
buf := make([]byte, 1500)
for ctx.Err() == nil {
n, addr, err := conn.ReadFrom(buf)
if err != nil {
if errors.Is(selfKill.Err(), context.Canceled) {
return nil
}
return err
} else if n == 0 || addr == nil {
return fmt.Errorf("n=%v, addr=%v", n, addr) // nolint:goerr113
} else if nn, err := conn.WriteTo(buf[:n], addr); err != nil {
return err
} else if nn != n {
return fmt.Errorf("nn=%v, n=%v", nn, n) // nolint:goerr113
}
// Check the address, shold not change, use content as ID.
clientID := string(buf[:n])
if oldAddr, ok := addrs[clientID]; ok && oldAddr.String() != addr.String() {
return fmt.Errorf("address change %v to %v", oldAddr.String(), addr.String()) // nolint:goerr113
}
addrs[clientID] = addr
}
return nil
}
var testTimeout = flag.Int("timeout", 5000, "For each case, the timeout in ms") // nolint:gochecknoglobals
func TestMain(m *testing.M) {
flag.Parse()
os.Exit(m.Run())
}
// vnet client:
// 10.0.0.11:5787
// proxy to real server:
// 192.168.1.10:8000
func TestUDPProxyOne2One(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
var r0, r1, r2 error
defer func() {
if r0 != nil || r1 != nil || r2 != nil {
t.Errorf("fail for ctx=%v, r0=%v, r1=%v, r2=%v", ctx.Err(), r0, r1, r2)
}
}()
var wg sync.WaitGroup
defer wg.Wait()
// Timeout, fail
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
select {
case <-ctx.Done():
case <-time.After(time.Duration(*testTimeout) * time.Millisecond):
r2 = fmt.Errorf("timeout") // nolint:goerr113
}
}()
// For utest, we always proxy vnet packets to the random port we listen to.
mockServer := NewMockUDPEchoServer()
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
if err := mockServer.doMockUDPServer(ctx); err != nil {
r0 = err
}
}()
// Create a vent and proxy.
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
// When real server is ready, start the vnet test.
select {
case <-ctx.Done():
return
case <-mockServer.realServerReady.Done():
}
doVnetProxy := func() error {
router, err := vnet.NewRouter(&vnet.RouterConfig{
CIDR: "0.0.0.0/0",
LoggerFactory: logging.NewDefaultLoggerFactory(),
})
if err != nil {
return err
}
clientNetwork := vnet.NewNet(&vnet.NetConfig{
StaticIP: "10.0.0.11",
})
if err = router.AddNet(clientNetwork); err != nil {
return err
}
if err = router.Start(); err != nil {
return err
}
defer router.Stop() // nolint:errcheck
proxy, err := NewProxy(router)
if err != nil {
return err
}
defer proxy.Close() // nolint:errcheck
// For utest, mock the target real server.
proxy.mockRealServerAddr = mockServer.realServerAddr
// The real server address to proxy to.
// Note that for utest, we will proxy to a local address.
serverAddr, err := net.ResolveUDPAddr("udp4", "192.168.1.10:8000")
if err != nil {
return err
}
if err = proxy.Proxy(clientNetwork, serverAddr); err != nil {
return err
}
// Now, all packets from client, will be proxy to real server, vice versa.
client, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5787")
if err != nil {
return err
}
// When system quit, interrupt client.
selfKill, selfKillCancel := context.WithCancel(context.Background())
go func() {
<-ctx.Done()
selfKillCancel()
_ = client.Close() // nolint:errcheck
}()
for i := 0; i < 10; i++ {
if _, err = client.WriteTo([]byte("Hello"), serverAddr); err != nil {
return err
}
var n int
var addr net.Addr
buf := make([]byte, 1500)
if n, addr, err = client.ReadFrom(buf); err != nil { // nolint:gocritic
if errors.Is(selfKill.Err(), context.Canceled) {
return nil
}
return err
} else if n != 5 || addr == nil {
return fmt.Errorf("n=%v, addr=%v", n, addr) // nolint:goerr113
} else if string(buf[:n]) != "Hello" {
return fmt.Errorf("data %v", buf[:n]) // nolint:goerr113
}
// Wait for awhile for each UDP packet, to simulate real network.
select {
case <-ctx.Done():
return nil
case <-time.After(30 * time.Millisecond):
}
}
return err
}
if err := doVnetProxy(); err != nil {
r1 = err
}
}()
}
// vnet client:
// 10.0.0.11:5787
// 10.0.0.11:5788
// proxy to real server:
// 192.168.1.10:8000
func TestUDPProxyTwo2One(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
var r0, r1, r2, r3 error
defer func() {
if r0 != nil || r1 != nil || r2 != nil || r3 != nil {
t.Errorf("fail for ctx=%v, r0=%v, r1=%v, r2=%v, r3=%v", ctx.Err(), r0, r1, r2, r3)
}
}()
var wg sync.WaitGroup
defer wg.Wait()
// Timeout, fail
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
select {
case <-ctx.Done():
case <-time.After(time.Duration(*testTimeout) * time.Millisecond):
r2 = fmt.Errorf("timeout") // nolint:goerr113
}
}()
// For utest, we always proxy vnet packets to the random port we listen to.
mockServer := NewMockUDPEchoServer()
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
if err := mockServer.doMockUDPServer(ctx); err != nil {
r0 = err
}
}()
// Create a vent and proxy.
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
// When real server is ready, start the vnet test.
select {
case <-ctx.Done():
return
case <-mockServer.realServerReady.Done():
}
doVnetProxy := func() error {
router, err := vnet.NewRouter(&vnet.RouterConfig{
CIDR: "0.0.0.0/0",
LoggerFactory: logging.NewDefaultLoggerFactory(),
})
if err != nil {
return err
}
clientNetwork := vnet.NewNet(&vnet.NetConfig{
StaticIP: "10.0.0.11",
})
if err = router.AddNet(clientNetwork); err != nil {
return err
}
if err = router.Start(); err != nil {
return err
}
defer router.Stop() // nolint:errcheck
proxy, err := NewProxy(router)
if err != nil {
return err
}
defer proxy.Close() // nolint:errcheck
// For utest, mock the target real server.
proxy.mockRealServerAddr = mockServer.realServerAddr
// The real server address to proxy to.
// Note that for utest, we will proxy to a local address.
serverAddr, err := net.ResolveUDPAddr("udp4", "192.168.1.10:8000")
if err != nil {
return err
}
if err = proxy.Proxy(clientNetwork, serverAddr); err != nil {
return err
}
handClient := func(address, echoData string) error {
// Now, all packets from client, will be proxy to real server, vice versa.
client, err := clientNetwork.ListenPacket("udp4", address) // nolint:govet
if err != nil {
return err
}
// When system quit, interrupt client.
selfKill, selfKillCancel := context.WithCancel(context.Background())
go func() {
<-ctx.Done()
selfKillCancel()
_ = client.Close()
}()
for i := 0; i < 10; i++ {
if _, err := client.WriteTo([]byte(echoData), serverAddr); err != nil { // nolint:govet
return err
}
var n int
var addr net.Addr
buf := make([]byte, 1400)
if n, addr, err = client.ReadFrom(buf); err != nil { // nolint:gocritic
if errors.Is(selfKill.Err(), context.Canceled) {
return nil
}
return err
} else if n != len(echoData) || addr == nil {
return fmt.Errorf("n=%v, addr=%v", n, addr) // nolint:goerr113
} else if string(buf[:n]) != echoData {
return fmt.Errorf("check data %v", buf[:n]) // nolint:goerr113
}
// Wait for awhile for each UDP packet, to simulate real network.
select {
case <-ctx.Done():
return nil
case <-time.After(30 * time.Millisecond):
}
}
return nil
}
client0, client0Cancel := context.WithCancel(context.Background())
go func() {
defer client0Cancel()
address := "10.0.0.11:5787"
if err := handClient(address, "Hello"); err != nil { // nolint:govet
r3 = fmt.Errorf("client %v err %v", address, err) // nolint:goerr113
}
}()
client1, client1Cancel := context.WithCancel(context.Background())
go func() {
defer client1Cancel()
address := "10.0.0.11:5788"
if err := handClient(address, "World"); err != nil { // nolint:govet
r3 = fmt.Errorf("client %v err %v", address, err) // nolint:goerr113
}
}()
select {
case <-ctx.Done():
case <-client0.Done():
case <-client1.Done():
}
return err
}
if err := doVnetProxy(); err != nil {
r1 = err
}
}()
}
// vnet client:
// 10.0.0.11:5787
// proxy to real server:
// 192.168.1.10:8000
//
// vnet client:
// 10.0.0.11:5788
// proxy to real server:
// 192.168.1.10:8000
func TestUDPProxyProxyTwice(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
var r0, r1, r2, r3 error
defer func() {
if r0 != nil || r1 != nil || r2 != nil || r3 != nil {
t.Errorf("fail for ctx=%v, r0=%v, r1=%v, r2=%v, r3=%v", ctx.Err(), r0, r1, r2, r3)
}
}()
var wg sync.WaitGroup
defer wg.Wait()
// Timeout, fail
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
select {
case <-ctx.Done():
case <-time.After(time.Duration(*testTimeout) * time.Millisecond):
r2 = fmt.Errorf("timeout") // nolint:goerr113
}
}()
// For utest, we always proxy vnet packets to the random port we listen to.
mockServer := NewMockUDPEchoServer()
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
if err := mockServer.doMockUDPServer(ctx); err != nil {
r0 = err
}
}()
// Create a vent and proxy.
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
// When real server is ready, start the vnet test.
select {
case <-ctx.Done():
return
case <-mockServer.realServerReady.Done():
}
doVnetProxy := func() error {
router, err := vnet.NewRouter(&vnet.RouterConfig{
CIDR: "0.0.0.0/0",
LoggerFactory: logging.NewDefaultLoggerFactory(),
})
if err != nil {
return err
}
clientNetwork := vnet.NewNet(&vnet.NetConfig{
StaticIP: "10.0.0.11",
})
if err = router.AddNet(clientNetwork); err != nil {
return err
}
if err = router.Start(); err != nil {
return err
}
defer router.Stop() // nolint:errcheck
proxy, err := NewProxy(router)
if err != nil {
return err
}
defer proxy.Close() // nolint:errcheck
// For utest, mock the target real server.
proxy.mockRealServerAddr = mockServer.realServerAddr
// The real server address to proxy to.
// Note that for utest, we will proxy to a local address.
serverAddr, err := net.ResolveUDPAddr("udp4", "192.168.1.10:8000")
if err != nil {
return err
}
handClient := func(address, echoData string) error {
// We proxy multiple times, for example, in publisher and player, both call
// the proxy when got answer.
if err := proxy.Proxy(clientNetwork, serverAddr); err != nil { // nolint:govet
return err
}
// Now, all packets from client, will be proxy to real server, vice versa.
client, err := clientNetwork.ListenPacket("udp4", address) // nolint:govet
if err != nil {
return err
}
// When system quit, interrupt client.
selfKill, selfKillCancel := context.WithCancel(context.Background())
go func() {
<-ctx.Done()
selfKillCancel()
_ = client.Close() // nolint:errcheck
}()
for i := 0; i < 10; i++ {
if _, err = client.WriteTo([]byte(echoData), serverAddr); err != nil {
return err
}
buf := make([]byte, 1500)
if n, addr, err := client.ReadFrom(buf); err != nil { // nolint:gocritic,govet
if errors.Is(selfKill.Err(), context.Canceled) {
return nil
}
return err
} else if n != len(echoData) || addr == nil {
return fmt.Errorf("n=%v, addr=%v", n, addr) // nolint:goerr113
} else if string(buf[:n]) != echoData {
return fmt.Errorf("verify data %v", buf[:n]) // nolint:goerr113
}
// Wait for awhile for each UDP packet, to simulate real network.
select {
case <-ctx.Done():
return nil
case <-time.After(30 * time.Millisecond):
}
}
return nil
}
client0, client0Cancel := context.WithCancel(context.Background())
go func() {
defer client0Cancel()
address := "10.0.0.11:5787"
if err = handClient(address, "Hello"); err != nil {
r3 = fmt.Errorf("client %v err %v", address, err) // nolint:goerr113
}
}()
client1, client1Cancel := context.WithCancel(context.Background())
go func() {
defer client1Cancel()
// Slower than client0, 60ms.
// To simulate the real player or publisher, might not start at the same time.
select {
case <-ctx.Done():
return
case <-time.After(150 * time.Millisecond):
}
address := "10.0.0.11:5788"
if err = handClient(address, "World"); err != nil {
r3 = fmt.Errorf("client %v err %v", address, err) // nolint:goerr113
}
}()
select {
case <-ctx.Done():
case <-client0.Done():
case <-client1.Done():
}
return err
}
if err := doVnetProxy(); err != nil {
r1 = err
}
}()
}