-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
server.go
92 lines (80 loc) · 2.55 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package v2raygrpc
import (
"context"
"net"
"os"
"strings"
"time"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/tls"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"golang.org/x/net/http2"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
gM "google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
)
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) {
var serverOptions []grpc.ServerOption
if tlsConfig != nil {
if !common.Contains(tlsConfig.NextProtos(), http2.NextProtoTLS) {
tlsConfig.SetNextProtos(append([]string{"h2"}, tlsConfig.NextProtos()...))
}
serverOptions = append(serverOptions, grpc.Creds(NewTLSTransportCredentials(tlsConfig)))
}
if options.IdleTimeout > 0 {
serverOptions = append(serverOptions, grpc.KeepaliveParams(keepalive.ServerParameters{
Time: time.Duration(options.IdleTimeout),
Timeout: time.Duration(options.PingTimeout),
}))
}
server := &Server{ctx, handler, grpc.NewServer(serverOptions...)}
RegisterGunServiceCustomNameServer(server.server, server, options.ServiceName)
return server, nil
}
func (s *Server) Tun(server GunService_TunServer) error {
ctx, cancel := common.ContextWithCancelCause(s.ctx)
conn := NewGRPCConn(server, cancel)
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)
<-ctx.Done()
return nil
}
func (s *Server) mustEmbedUnimplementedGunServiceServer() {
}
func (s *Server) Network() []string {
return []string{N.NetworkTCP}
}
func (s *Server) Serve(listener net.Listener) error {
return s.server.Serve(listener)
}
func (s *Server) ServePacket(listener net.PacketConn) error {
return os.ErrInvalid
}
func (s *Server) Close() error {
s.server.Stop()
return nil
}