sing-box/transport/v2raygrpc/conn.go

102 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-08-22 10:53:47 +00:00
package v2raygrpc
import (
"net"
"os"
"time"
2023-04-10 05:00:57 +00:00
"github.com/sagernet/sing/common"
2023-09-07 11:26:45 +00:00
"github.com/sagernet/sing/common/baderror"
2023-08-30 09:53:37 +00:00
M "github.com/sagernet/sing/common/metadata"
2022-08-22 10:53:47 +00:00
"github.com/sagernet/sing/common/rw"
)
var _ net.Conn = (*GRPCConn)(nil)
type GRPCConn struct {
GunService
2023-04-10 05:00:57 +00:00
cancel common.ContextCancelCauseFunc
2022-08-22 10:53:47 +00:00
cache []byte
}
2023-04-10 05:00:57 +00:00
func NewGRPCConn(service GunService, cancel common.ContextCancelCauseFunc) *GRPCConn {
2022-08-22 10:53:47 +00:00
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()
2022-08-29 02:10:41 +00:00
err = baderror.WrapGRPC(err)
2022-08-22 10:53:47 +00:00
if err != nil {
2023-04-10 05:00:57 +00:00
c.cancel(err)
2022-08-22 10:53:47 +00:00
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) {
2022-08-29 02:10:41 +00:00
err = baderror.WrapGRPC(c.Send(&Hunk{Data: b}))
2022-08-22 10:53:47 +00:00
if err != nil {
2023-04-10 05:00:57 +00:00
c.cancel(err)
2022-08-22 10:53:47 +00:00
return
}
return len(b), nil
}
func (c *GRPCConn) Close() error {
2023-04-10 05:00:57 +00:00
c.cancel(net.ErrClosed)
2022-08-22 10:53:47 +00:00
return nil
}
func (c *GRPCConn) LocalAddr() net.Addr {
2023-08-30 09:53:37 +00:00
return M.Socksaddr{}
2022-08-22 10:53:47 +00:00
}
func (c *GRPCConn) RemoteAddr() net.Addr {
2023-08-30 09:53:37 +00:00
return M.Socksaddr{}
2022-08-22 10:53:47 +00:00
}
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
}
2023-04-19 13:48:54 +00:00
func (c *GRPCConn) NeedAdditionalReadDeadline() bool {
return true
}
2022-08-22 10:53:47 +00:00
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()
}