sing-box/transport/v2ray/transport.go

62 lines
2.2 KiB
Go
Raw Normal View History

2022-08-22 10:53:47 +00:00
package v2ray
import (
"context"
"crypto/tls"
"github.com/sagernet/sing-box/adapter"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/option"
2022-08-22 14:19:25 +00:00
"github.com/sagernet/sing-box/transport/v2rayhttp"
2022-08-22 12:20:56 +00:00
"github.com/sagernet/sing-box/transport/v2raywebsocket"
2022-08-22 10:53:47 +00:00
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
2022-08-22 12:20:56 +00:00
func NewServerTransport(ctx context.Context, options option.V2RayTransportOptions, tlsConfig *tls.Config, handler N.TCPConnectionHandler, errorHandler E.Handler) (adapter.V2RayServerTransport, error) {
2022-08-22 10:53:47 +00:00
if options.Type == "" {
return nil, nil
}
switch options.Type {
2022-08-22 14:19:25 +00:00
case C.V2RayTransportTypeHTTP:
return v2rayhttp.NewServer(ctx, options.HTTPOptions, tlsConfig, handler, errorHandler), nil
2022-08-22 12:20:56 +00:00
case C.V2RayTransportTypeWebsocket:
return v2raywebsocket.NewServer(ctx, options.WebsocketOptions, tlsConfig, handler, errorHandler), nil
2022-08-22 13:20:05 +00:00
case C.V2RayTransportTypeQUIC:
2022-08-22 14:19:25 +00:00
if tlsConfig == nil {
return nil, C.ErrTLSRequired
}
2022-08-22 13:20:05 +00:00
return NewQUICServer(ctx, options.QUICOptions, tlsConfig, handler, errorHandler)
2022-08-22 14:19:25 +00:00
case C.V2RayTransportTypeGRPC:
2022-08-27 13:05:15 +00:00
return NewGRPCServer(ctx, options.GRPCOptions, tlsConfig, handler, errorHandler)
2022-08-22 10:53:47 +00:00
default:
return nil, E.New("unknown transport type: " + options.Type)
}
}
2022-08-22 12:20:56 +00:00
func NewClientTransport(ctx context.Context, dialer N.Dialer, serverAddr M.Socksaddr, options option.V2RayTransportOptions, tlsConfig *tls.Config) (adapter.V2RayClientTransport, error) {
2022-08-22 10:53:47 +00:00
if options.Type == "" {
return nil, nil
}
switch options.Type {
2022-08-22 14:19:25 +00:00
case C.V2RayTransportTypeHTTP:
return v2rayhttp.NewClient(ctx, dialer, serverAddr, options.HTTPOptions, tlsConfig), nil
2022-08-22 10:53:47 +00:00
case C.V2RayTransportTypeGRPC:
2022-08-22 14:19:25 +00:00
if tlsConfig == nil {
return nil, C.ErrTLSRequired
}
2022-08-22 12:20:56 +00:00
return NewGRPCClient(ctx, dialer, serverAddr, options.GRPCOptions, tlsConfig)
case C.V2RayTransportTypeWebsocket:
return v2raywebsocket.NewClient(ctx, dialer, serverAddr, options.WebsocketOptions, tlsConfig), nil
2022-08-22 13:20:05 +00:00
case C.V2RayTransportTypeQUIC:
2022-08-22 14:19:25 +00:00
if tlsConfig == nil {
return nil, C.ErrTLSRequired
}
2022-08-22 13:20:05 +00:00
return NewQUICClient(ctx, dialer, serverAddr, options.QUICOptions, tlsConfig)
2022-08-22 14:19:25 +00:00
2022-08-22 10:53:47 +00:00
default:
return nil, E.New("unknown transport type: " + options.Type)
}
}