-
Notifications
You must be signed in to change notification settings - Fork 0
/
freedom.go
85 lines (68 loc) · 1.75 KB
/
freedom.go
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
package freedom
import (
"io"
"net"
"sync"
v2io "github.com/v2ray/v2ray-core/common/io"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/retry"
"github.com/v2ray/v2ray-core/transport/dialer"
"github.com/v2ray/v2ray-core/transport/ray"
)
type FreedomConnection struct {
}
func (this *FreedomConnection) Dispatch(firstPacket v2net.Packet, ray ray.OutboundRay) error {
log.Info("Freedom: Opening connection to ", firstPacket.Destination())
defer firstPacket.Release()
defer ray.OutboundInput().Release()
var conn net.Conn
err := retry.Timed(5, 100).On(func() error {
rawConn, err := dialer.Dial(firstPacket.Destination())
if err != nil {
return err
}
conn = rawConn
return nil
})
if err != nil {
log.Error("Freedom: Failed to open connection to ", firstPacket.Destination(), ": ", err)
return err
}
defer conn.Close()
input := ray.OutboundInput()
output := ray.OutboundOutput()
var readMutex, writeMutex sync.Mutex
readMutex.Lock()
writeMutex.Lock()
if chunk := firstPacket.Chunk(); chunk != nil {
conn.Write(chunk.Value)
}
if !firstPacket.MoreChunks() {
writeMutex.Unlock()
} else {
go func() {
v2writer := v2io.NewAdaptiveWriter(conn)
defer v2writer.Release()
v2io.Pipe(input, v2writer)
writeMutex.Unlock()
}()
}
go func() {
defer readMutex.Unlock()
defer output.Close()
var reader io.Reader = conn
if firstPacket.Destination().IsUDP() {
reader = v2net.NewTimeOutReader(16 /* seconds */, conn)
}
v2reader := v2io.NewAdaptiveReader(reader)
defer v2reader.Release()
v2io.Pipe(v2reader, output)
}()
writeMutex.Lock()
if tcpConn, ok := conn.(*net.TCPConn); ok {
tcpConn.CloseWrite()
}
readMutex.Lock()
return nil
}