sing-box/transport/v2raygrpc/conn.go

96 lines
1.6 KiB
Go
Raw Permalink Normal View History

2022-08-22 18:53:47 +08:00
package v2raygrpc
import (
"net"
"os"
"time"
2023-09-07 19:26:45 +08:00
"github.com/sagernet/sing/common/baderror"
2023-08-30 17:53:37 +08:00
M "github.com/sagernet/sing/common/metadata"
2024-06-24 09:49:15 +08:00
N "github.com/sagernet/sing/common/network"
2022-08-22 18:53:47 +08:00
)
var _ net.Conn = (*GRPCConn)(nil)
type GRPCConn struct {
GunService
2024-10-21 23:38:34 +08:00
cache []byte
2022-08-22 18:53:47 +08:00
}
2024-10-21 23:38:34 +08:00
func NewGRPCConn(service GunService) *GRPCConn {
2022-08-22 18:53:47 +08:00
if client, isClient := service.(GunService_TunClient); isClient {
service = &clientConnWrapper{client}
}
return &GRPCConn{
GunService: service,
}
}
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 10:10:41 +08:00
err = baderror.WrapGRPC(err)
2022-08-22 18:53:47 +08:00
if err != nil {
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 10:10:41 +08:00
err = baderror.WrapGRPC(c.Send(&Hunk{Data: b}))
2022-08-22 18:53:47 +08:00
if err != nil {
return
}
return len(b), nil
}
func (c *GRPCConn) Close() error {
return nil
}
func (c *GRPCConn) LocalAddr() net.Addr {
2023-08-30 17:53:37 +08:00
return M.Socksaddr{}
2022-08-22 18:53:47 +08:00
}
func (c *GRPCConn) RemoteAddr() net.Addr {
2023-08-30 17:53:37 +08:00
return M.Socksaddr{}
2022-08-22 18:53:47 +08: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 21:48:54 +08:00
func (c *GRPCConn) NeedAdditionalReadDeadline() bool {
return true
}
2022-08-22 18:53:47 +08:00
func (c *GRPCConn) Upstream() any {
return c.GunService
}
2024-06-24 09:49:15 +08:00
var _ N.WriteCloser = (*clientConnWrapper)(nil)
2022-08-22 18:53:47 +08:00
type clientConnWrapper struct {
GunService_TunClient
}
func (c *clientConnWrapper) CloseWrite() error {
return c.CloseSend()
}