sing-box/transport/v2raygrpc/conn.go

96 lines
1.6 KiB
Go
Raw Normal View History

2022-08-22 10:53:47 +00:00
package v2raygrpc
import (
"net"
"os"
"time"
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"
2024-06-24 01:49:15 +00:00
N "github.com/sagernet/sing/common/network"
2022-08-22 10:53:47 +00:00
)
var _ net.Conn = (*GRPCConn)(nil)
type GRPCConn struct {
GunService
2024-10-21 15:38:34 +00:00
cache []byte
2022-08-22 10:53:47 +00:00
}
2024-10-21 15:38:34 +00:00
func NewGRPCConn(service GunService) *GRPCConn {
2022-08-22 10:53:47 +00: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 02:10:41 +00:00
err = baderror.WrapGRPC(err)
2022-08-22 10:53:47 +00: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 02:10:41 +00:00
err = baderror.WrapGRPC(c.Send(&Hunk{Data: b}))
2022-08-22 10:53:47 +00: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 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
}
2024-06-24 01:49:15 +00:00
var _ N.WriteCloser = (*clientConnWrapper)(nil)
2022-08-22 10:53:47 +00:00
type clientConnWrapper struct {
GunService_TunClient
}
func (c *clientConnWrapper) CloseWrite() error {
return c.CloseSend()
}