File: sctp_proxy_linux.go

package info (click to toggle)
docker.io 28.5.2%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 69,048 kB
  • sloc: sh: 5,867; makefile: 863; ansic: 184; python: 162; asm: 159
file content (81 lines) | stat: -rw-r--r-- 1,854 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main

import (
	"io"
	"log"
	"net"
	"sync"

	"github.com/ishidawataru/sctp"
)

// SCTPProxy is a proxy for SCTP connections. It implements the Proxy interface to
// handle SCTP traffic forwarding between the frontend and backend addresses.
type SCTPProxy struct {
	listener     *sctp.SCTPListener
	frontendAddr *sctp.SCTPAddr
	backendAddr  *sctp.SCTPAddr
}

// NewSCTPProxy creates a new SCTPProxy.
func NewSCTPProxy(listener *sctp.SCTPListener, backendAddr *sctp.SCTPAddr) (*SCTPProxy, error) {
	return &SCTPProxy{
		listener:     listener,
		frontendAddr: listener.Addr().(*sctp.SCTPAddr),
		backendAddr:  backendAddr,
	}, nil
}

func (proxy *SCTPProxy) clientLoop(client *sctp.SCTPConn, quit chan bool) {
	backend, err := sctp.DialSCTP("sctp", nil, proxy.backendAddr)
	if err != nil {
		log.Printf("Can't forward traffic to backend sctp/%v: %s\n", proxy.backendAddr, err)
		client.Close()
		return
	}
	clientC := sctp.NewSCTPSndRcvInfoWrappedConn(client)
	backendC := sctp.NewSCTPSndRcvInfoWrappedConn(backend)

	var wg sync.WaitGroup
	broker := func(to, from net.Conn) {
		io.Copy(to, from)
		from.Close()
		to.Close()
		wg.Done()
	}

	wg.Add(2)
	go broker(clientC, backendC)
	go broker(backendC, clientC)

	finish := make(chan struct{})
	go func() {
		wg.Wait()
		close(finish)
	}()

	select {
	case <-quit:
	case <-finish:
	}
	clientC.Close()
	backendC.Close()
	<-finish
}

// Run starts forwarding the traffic using SCTP.
func (proxy *SCTPProxy) Run() {
	quit := make(chan bool)
	defer close(quit)
	for {
		client, err := proxy.listener.Accept()
		if err != nil {
			log.Printf("Stopping proxy on sctp/%v for sctp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err)
			return
		}
		go proxy.clientLoop(client.(*sctp.SCTPConn), quit)
	}
}

// Close stops forwarding the traffic.
func (proxy *SCTPProxy) Close() { proxy.listener.Close() }