sing-box/transport/v2raygrpc/server.go

68 lines
1.6 KiB
Go
Raw Normal View History

2022-08-22 18:53:47 +08:00
package v2raygrpc
import (
"context"
"net"
2022-08-22 21:20:05 +08:00
"os"
2022-08-22 18:53:47 +08:00
"github.com/sagernet/sing-box/adapter"
2022-09-09 18:45:10 +08:00
"github.com/sagernet/sing-box/common/tls"
2022-08-22 20:20:56 +08:00
"github.com/sagernet/sing-box/option"
2022-08-22 18:53:47 +08:00
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
var _ adapter.V2RayServerTransport = (*Server)(nil)
type Server struct {
ctx context.Context
handler N.TCPConnectionHandler
server *grpc.Server
}
2022-09-09 18:45:10 +08:00
func NewServer(ctx context.Context, options option.V2RayGRPCOptions, tlsConfig tls.Config, handler N.TCPConnectionHandler) (*Server, error) {
2022-08-22 18:53:47 +08:00
var serverOptions []grpc.ServerOption
if tlsConfig != nil {
2022-09-09 18:45:10 +08:00
stdConfig, err := tlsConfig.Config()
if err != nil {
return nil, err
}
stdConfig.NextProtos = []string{"h2"}
serverOptions = append(serverOptions, grpc.Creds(credentials.NewTLS(stdConfig)))
2022-08-22 18:53:47 +08:00
}
server := &Server{ctx, handler, grpc.NewServer(serverOptions...)}
2022-08-22 20:20:56 +08:00
RegisterGunServiceCustomNameServer(server.server, server, options.ServiceName)
2022-09-09 18:45:10 +08:00
return server, nil
2022-08-22 18:53:47 +08:00
}
func (s *Server) Tun(server GunService_TunServer) error {
ctx, cancel := context.WithCancel(s.ctx)
conn := NewGRPCConn(server, cancel)
go s.handler.NewConnection(ctx, conn, M.Metadata{})
<-ctx.Done()
return nil
}
func (s *Server) mustEmbedUnimplementedGunServiceServer() {
}
2022-08-22 21:20:05 +08:00
func (s *Server) Network() []string {
return []string{N.NetworkTCP}
}
2022-08-22 18:53:47 +08:00
func (s *Server) Serve(listener net.Listener) error {
return s.server.Serve(listener)
}
2022-08-22 21:20:05 +08:00
func (s *Server) ServePacket(listener net.PacketConn) error {
return os.ErrInvalid
}
2022-08-22 18:53:47 +08:00
func (s *Server) Close() error {
s.server.Stop()
return nil
}