~bigbes/shroud

ref: 5afb3bad1be8eb82352dde56e6836a0a8ea4ef7f shroud/internal/awgserver/filteredconn.go -rw-r--r-- 2.3 KiB
5afb3bad — Eugene Blikh feat: add optional shadowsocks and outline smart dialer config 2 months ago
                                                                                
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package awgserver

import (
	"net"
	"time"
)

// FilteredConn implements net.PacketConn. It receives only non-AWG packets
// from MuxBind via a channel, and writes QUIC responses through the shared
// UDP socket.
type FilteredConn struct {
	quicCh  chan quicPacket
	udpConn *net.UDPConn
	closed  chan struct{}

	readDeadline  time.Time
	writeDeadline time.Time
}

func newFilteredConn(quicCh chan quicPacket, udpConn *net.UDPConn) *FilteredConn {
	return &FilteredConn{
		quicCh:  quicCh,
		udpConn: udpConn,
		closed:  make(chan struct{}),
	}
}

// ReadFrom blocks until a non-AWG packet arrives from MuxBind.
func (fc *FilteredConn) ReadFrom(p []byte) (int, net.Addr, error) {
	var timer <-chan time.Time
	if !fc.readDeadline.IsZero() {
		d := time.Until(fc.readDeadline)
		if d <= 0 {
			return 0, nil, &net.OpError{Op: "read", Err: errTimeout}
		}
		t := time.NewTimer(d)
		defer t.Stop()
		timer = t.C
	}

	select {
	case pkt := <-fc.quicCh:
		n := copy(p, pkt.data)
		return n, pkt.addr, nil
	case <-timer:
		return 0, nil, &net.OpError{Op: "read", Err: errTimeout}
	case <-fc.closed:
		return 0, nil, net.ErrClosed
	}
}

// WriteTo sends QUIC responses through the shared socket.
func (fc *FilteredConn) WriteTo(p []byte, addr net.Addr) (int, error) {
	udpAddr, ok := addr.(*net.UDPAddr)
	if !ok {
		return 0, &net.OpError{Op: "write", Err: net.ErrClosed}
	}
	return fc.udpConn.WriteToUDP(p, udpAddr)
}

func (fc *FilteredConn) Close() error {
	select {
	case <-fc.closed:
	default:
		close(fc.closed)
	}
	return nil
}

func (fc *FilteredConn) LocalAddr() net.Addr {
	return fc.udpConn.LocalAddr()
}

func (fc *FilteredConn) SetDeadline(t time.Time) error {
	fc.readDeadline = t
	fc.writeDeadline = t
	return nil
}

func (fc *FilteredConn) SetReadDeadline(t time.Time) error {
	fc.readDeadline = t
	return nil
}

func (fc *FilteredConn) SetWriteDeadline(t time.Time) error {
	fc.writeDeadline = t
	return nil
}

// SyscallConn is required by quic-go's OOBCapablePacketConn check.
func (fc *FilteredConn) SyscallConn() (interface{}, error) {
	return nil, &net.OpError{Op: "syscall", Err: net.ErrClosed}
}

type timeoutError struct{}

func (timeoutError) Error() string   { return "i/o timeout" }
func (timeoutError) Timeout() bool   { return true }
func (timeoutError) Temporary() bool { return true }

var errTimeout = timeoutError{}