-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
conn.go
101 lines (83 loc) · 1.82 KB
/
conn.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package v2raygrpc
import (
"net"
"os"
"time"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/baderror"
M "github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/common/rw"
)
var _ net.Conn = (*GRPCConn)(nil)
type GRPCConn struct {
GunService
cancel common.ContextCancelCauseFunc
cache []byte
}
func NewGRPCConn(service GunService, cancel common.ContextCancelCauseFunc) *GRPCConn {
if client, isClient := service.(GunService_TunClient); isClient {
service = &clientConnWrapper{client}
}
return &GRPCConn{
GunService: service,
cancel: cancel,
}
}
func (c *GRPCConn) Read(b []byte) (n int, err error) {
if len(c.cache) > 0 {
n = copy(b, c.cache)
c.cache = c.cache[n:]
return
}
hunk, err := c.Recv()
err = baderror.WrapGRPC(err)
if err != nil {
c.cancel(err)
return
}
n = copy(b, hunk.Data)
if n < len(hunk.Data) {
c.cache = hunk.Data[n:]
}
return
}
func (c *GRPCConn) Write(b []byte) (n int, err error) {
err = baderror.WrapGRPC(c.Send(&Hunk{Data: b}))
if err != nil {
c.cancel(err)
return
}
return len(b), nil
}
func (c *GRPCConn) Close() error {
c.cancel(net.ErrClosed)
return nil
}
func (c *GRPCConn) LocalAddr() net.Addr {
return M.Socksaddr{}
}
func (c *GRPCConn) RemoteAddr() net.Addr {
return M.Socksaddr{}
}
func (c *GRPCConn) SetDeadline(t time.Time) error {
return os.ErrInvalid
}
func (c *GRPCConn) SetReadDeadline(t time.Time) error {
return os.ErrInvalid
}
func (c *GRPCConn) SetWriteDeadline(t time.Time) error {
return os.ErrInvalid
}
func (c *GRPCConn) NeedAdditionalReadDeadline() bool {
return true
}
func (c *GRPCConn) Upstream() any {
return c.GunService
}
var _ rw.WriteCloser = (*clientConnWrapper)(nil)
type clientConnWrapper struct {
GunService_TunClient
}
func (c *clientConnWrapper) CloseWrite() error {
return c.CloseSend()
}