sing-box/transport/v2raygrpc/server.go

89 lines
2.4 KiB
Go
Raw Permalink Normal View History

2022-08-22 10:53:47 +00:00
package v2raygrpc
import (
"context"
"net"
2022-08-22 13:20:05 +00:00
"os"
2022-09-25 11:29:29 +00:00
"strings"
"time"
2022-08-22 10:53:47 +00:00
"github.com/sagernet/sing-box/adapter"
2022-09-09 10:45:10 +00:00
"github.com/sagernet/sing-box/common/tls"
2022-08-22 12:20:56 +00:00
"github.com/sagernet/sing-box/option"
2022-08-22 10:53:47 +00:00
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
2022-09-25 11:29:29 +00:00
gM "google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
2022-08-22 10:53:47 +00:00
)
var _ adapter.V2RayServerTransport = (*Server)(nil)
type Server struct {
ctx context.Context
handler N.TCPConnectionHandler
server *grpc.Server
}
func NewServer(ctx context.Context, options option.V2RayGRPCOptions, tlsConfig tls.ServerConfig, handler N.TCPConnectionHandler) (*Server, error) {
2022-08-22 10:53:47 +00:00
var serverOptions []grpc.ServerOption
if tlsConfig != nil {
tlsConfig.SetNextProtos([]string{"h2"})
serverOptions = append(serverOptions, grpc.Creds(NewTLSTransportCredentials(tlsConfig)))
2022-08-22 10:53:47 +00:00
}
if options.IdleTimeout > 0 {
serverOptions = append(serverOptions, grpc.KeepaliveParams(keepalive.ServerParameters{
Time: time.Duration(options.IdleTimeout),
Timeout: time.Duration(options.PingTimeout),
}))
}
2022-08-22 10:53:47 +00:00
server := &Server{ctx, handler, grpc.NewServer(serverOptions...)}
2022-08-22 12:20:56 +00:00
RegisterGunServiceCustomNameServer(server.server, server, options.ServiceName)
2022-09-09 10:45:10 +00:00
return server, nil
2022-08-22 10:53:47 +00:00
}
func (s *Server) Tun(server GunService_TunServer) error {
ctx, cancel := context.WithCancel(s.ctx)
conn := NewGRPCConn(server, cancel)
2022-09-25 11:29:29 +00:00
var metadata M.Metadata
if remotePeer, loaded := peer.FromContext(server.Context()); loaded {
metadata.Source = M.SocksaddrFromNet(remotePeer.Addr)
}
if grpcMetadata, loaded := gM.FromIncomingContext(server.Context()); loaded {
forwardFrom := strings.Join(grpcMetadata.Get("X-Forwarded-For"), ",")
if forwardFrom != "" {
for _, from := range strings.Split(forwardFrom, ",") {
originAddr := M.ParseSocksaddr(from)
if originAddr.IsValid() {
metadata.Source = originAddr.Unwrap()
}
}
}
}
go s.handler.NewConnection(ctx, conn, metadata)
2022-08-22 10:53:47 +00:00
<-ctx.Done()
return nil
}
func (s *Server) mustEmbedUnimplementedGunServiceServer() {
}
2022-08-22 13:20:05 +00:00
func (s *Server) Network() []string {
return []string{N.NetworkTCP}
}
2022-08-22 10:53:47 +00:00
func (s *Server) Serve(listener net.Listener) error {
return s.server.Serve(listener)
}
2022-08-22 13:20:05 +00:00
func (s *Server) ServePacket(listener net.PacketConn) error {
return os.ErrInvalid
}
2022-08-22 10:53:47 +00:00
func (s *Server) Close() error {
s.server.Stop()
return nil
}