mirror of
https://github.com/XTLS/Xray-core.git
synced 2025-04-30 09:18:34 +00:00
v1.0.0
This commit is contained in:
parent
47d23e9972
commit
c7f7c08ead
711 changed files with 82154 additions and 2 deletions
46
app/router/balancing.go
Normal file
46
app/router/balancing.go
Normal file
|
@ -0,0 +1,46 @@
|
|||
// +build !confonly
|
||||
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/v1/common/dice"
|
||||
"github.com/xtls/xray-core/v1/features/outbound"
|
||||
)
|
||||
|
||||
type BalancingStrategy interface {
|
||||
PickOutbound([]string) string
|
||||
}
|
||||
|
||||
type RandomStrategy struct {
|
||||
}
|
||||
|
||||
func (s *RandomStrategy) PickOutbound(tags []string) string {
|
||||
n := len(tags)
|
||||
if n == 0 {
|
||||
panic("0 tags")
|
||||
}
|
||||
|
||||
return tags[dice.Roll(n)]
|
||||
}
|
||||
|
||||
type Balancer struct {
|
||||
selectors []string
|
||||
strategy BalancingStrategy
|
||||
ohm outbound.Manager
|
||||
}
|
||||
|
||||
func (b *Balancer) PickOutbound() (string, error) {
|
||||
hs, ok := b.ohm.(outbound.HandlerSelector)
|
||||
if !ok {
|
||||
return "", newError("outbound.Manager is not a HandlerSelector")
|
||||
}
|
||||
tags := hs.Select(b.selectors)
|
||||
if len(tags) == 0 {
|
||||
return "", newError("no available outbounds selected")
|
||||
}
|
||||
tag := b.strategy.PickOutbound(tags)
|
||||
if tag == "" {
|
||||
return "", newError("balancing strategy returns empty tag")
|
||||
}
|
||||
return tag, nil
|
||||
}
|
95
app/router/command/command.go
Normal file
95
app/router/command/command.go
Normal file
|
@ -0,0 +1,95 @@
|
|||
// +build !confonly
|
||||
|
||||
package command
|
||||
|
||||
//go:generate go run github.com/xtls/xray-core/v1/common/errors/errorgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/xtls/xray-core/v1/common"
|
||||
"github.com/xtls/xray-core/v1/core"
|
||||
"github.com/xtls/xray-core/v1/features/routing"
|
||||
"github.com/xtls/xray-core/v1/features/stats"
|
||||
)
|
||||
|
||||
// routingServer is an implementation of RoutingService.
|
||||
type routingServer struct {
|
||||
router routing.Router
|
||||
routingStats stats.Channel
|
||||
}
|
||||
|
||||
// NewRoutingServer creates a statistics service with statistics manager.
|
||||
func NewRoutingServer(router routing.Router, routingStats stats.Channel) RoutingServiceServer {
|
||||
return &routingServer{
|
||||
router: router,
|
||||
routingStats: routingStats,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *routingServer) TestRoute(ctx context.Context, request *TestRouteRequest) (*RoutingContext, error) {
|
||||
if request.RoutingContext == nil {
|
||||
return nil, newError("Invalid routing request.")
|
||||
}
|
||||
route, err := s.router.PickRoute(AsRoutingContext(request.RoutingContext))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if request.PublishResult && s.routingStats != nil {
|
||||
ctx, _ := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
s.routingStats.Publish(ctx, route)
|
||||
}
|
||||
return AsProtobufMessage(request.FieldSelectors)(route), nil
|
||||
}
|
||||
|
||||
func (s *routingServer) SubscribeRoutingStats(request *SubscribeRoutingStatsRequest, stream RoutingService_SubscribeRoutingStatsServer) error {
|
||||
if s.routingStats == nil {
|
||||
return newError("Routing statistics not enabled.")
|
||||
}
|
||||
genMessage := AsProtobufMessage(request.FieldSelectors)
|
||||
subscriber, err := stats.SubscribeRunnableChannel(s.routingStats)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stats.UnsubscribeClosableChannel(s.routingStats, subscriber)
|
||||
for {
|
||||
select {
|
||||
case value, ok := <-subscriber:
|
||||
if !ok {
|
||||
return newError("Upstream closed the subscriber channel.")
|
||||
}
|
||||
route, ok := value.(routing.Route)
|
||||
if !ok {
|
||||
return newError("Upstream sent malformed statistics.")
|
||||
}
|
||||
err := stream.Send(genMessage(route))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case <-stream.Context().Done():
|
||||
return stream.Context().Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *routingServer) mustEmbedUnimplementedRoutingServiceServer() {}
|
||||
|
||||
type service struct {
|
||||
v *core.Instance
|
||||
}
|
||||
|
||||
func (s *service) Register(server *grpc.Server) {
|
||||
common.Must(s.v.RequireFeatures(func(router routing.Router, stats stats.Manager) {
|
||||
RegisterRoutingServiceServer(server, NewRoutingServer(router, nil))
|
||||
}))
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) {
|
||||
s := core.MustFromContext(ctx)
|
||||
return &service{v: s}, nil
|
||||
}))
|
||||
}
|
532
app/router/command/command.pb.go
Normal file
532
app/router/command/command.pb.go
Normal file
|
@ -0,0 +1,532 @@
|
|||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.25.0
|
||||
// protoc v3.14.0
|
||||
// source: app/router/command/command.proto
|
||||
|
||||
package command
|
||||
|
||||
import (
|
||||
proto "github.com/golang/protobuf/proto"
|
||||
net "github.com/xtls/xray-core/v1/common/net"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
// This is a compile-time assertion that a sufficiently up-to-date version
|
||||
// of the legacy proto package is being used.
|
||||
const _ = proto.ProtoPackageIsVersion4
|
||||
|
||||
// RoutingContext is the context with information relative to routing process.
|
||||
// It conforms to the structure of xray.features.routing.Context and
|
||||
// xray.features.routing.Route.
|
||||
type RoutingContext struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
InboundTag string `protobuf:"bytes,1,opt,name=InboundTag,proto3" json:"InboundTag,omitempty"`
|
||||
Network net.Network `protobuf:"varint,2,opt,name=Network,proto3,enum=xray.common.net.Network" json:"Network,omitempty"`
|
||||
SourceIPs [][]byte `protobuf:"bytes,3,rep,name=SourceIPs,proto3" json:"SourceIPs,omitempty"`
|
||||
TargetIPs [][]byte `protobuf:"bytes,4,rep,name=TargetIPs,proto3" json:"TargetIPs,omitempty"`
|
||||
SourcePort uint32 `protobuf:"varint,5,opt,name=SourcePort,proto3" json:"SourcePort,omitempty"`
|
||||
TargetPort uint32 `protobuf:"varint,6,opt,name=TargetPort,proto3" json:"TargetPort,omitempty"`
|
||||
TargetDomain string `protobuf:"bytes,7,opt,name=TargetDomain,proto3" json:"TargetDomain,omitempty"`
|
||||
Protocol string `protobuf:"bytes,8,opt,name=Protocol,proto3" json:"Protocol,omitempty"`
|
||||
User string `protobuf:"bytes,9,opt,name=User,proto3" json:"User,omitempty"`
|
||||
Attributes map[string]string `protobuf:"bytes,10,rep,name=Attributes,proto3" json:"Attributes,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
OutboundGroupTags []string `protobuf:"bytes,11,rep,name=OutboundGroupTags,proto3" json:"OutboundGroupTags,omitempty"`
|
||||
OutboundTag string `protobuf:"bytes,12,opt,name=OutboundTag,proto3" json:"OutboundTag,omitempty"`
|
||||
}
|
||||
|
||||
func (x *RoutingContext) Reset() {
|
||||
*x = RoutingContext{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_app_router_command_command_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *RoutingContext) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*RoutingContext) ProtoMessage() {}
|
||||
|
||||
func (x *RoutingContext) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_router_command_command_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use RoutingContext.ProtoReflect.Descriptor instead.
|
||||
func (*RoutingContext) Descriptor() ([]byte, []int) {
|
||||
return file_app_router_command_command_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *RoutingContext) GetInboundTag() string {
|
||||
if x != nil {
|
||||
return x.InboundTag
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *RoutingContext) GetNetwork() net.Network {
|
||||
if x != nil {
|
||||
return x.Network
|
||||
}
|
||||
return net.Network_Unknown
|
||||
}
|
||||
|
||||
func (x *RoutingContext) GetSourceIPs() [][]byte {
|
||||
if x != nil {
|
||||
return x.SourceIPs
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *RoutingContext) GetTargetIPs() [][]byte {
|
||||
if x != nil {
|
||||
return x.TargetIPs
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *RoutingContext) GetSourcePort() uint32 {
|
||||
if x != nil {
|
||||
return x.SourcePort
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *RoutingContext) GetTargetPort() uint32 {
|
||||
if x != nil {
|
||||
return x.TargetPort
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *RoutingContext) GetTargetDomain() string {
|
||||
if x != nil {
|
||||
return x.TargetDomain
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *RoutingContext) GetProtocol() string {
|
||||
if x != nil {
|
||||
return x.Protocol
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *RoutingContext) GetUser() string {
|
||||
if x != nil {
|
||||
return x.User
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *RoutingContext) GetAttributes() map[string]string {
|
||||
if x != nil {
|
||||
return x.Attributes
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *RoutingContext) GetOutboundGroupTags() []string {
|
||||
if x != nil {
|
||||
return x.OutboundGroupTags
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *RoutingContext) GetOutboundTag() string {
|
||||
if x != nil {
|
||||
return x.OutboundTag
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// SubscribeRoutingStatsRequest subscribes to routing statistics channel if
|
||||
// opened by xray-core.
|
||||
// * FieldSelectors selects a subset of fields in routing statistics to return.
|
||||
// Valid selectors:
|
||||
// - inbound: Selects connection's inbound tag.
|
||||
// - network: Selects connection's network.
|
||||
// - ip: Equivalent as "ip_source" and "ip_target", selects both source and
|
||||
// target IP.
|
||||
// - port: Equivalent as "port_source" and "port_target", selects both source
|
||||
// and target port.
|
||||
// - domain: Selects target domain.
|
||||
// - protocol: Select connection's protocol.
|
||||
// - user: Select connection's inbound user email.
|
||||
// - attributes: Select connection's additional attributes.
|
||||
// - outbound: Equivalent as "outbound" and "outbound_group", select both
|
||||
// outbound tag and outbound group tags.
|
||||
// * If FieldSelectors is left empty, all fields will be returned.
|
||||
type SubscribeRoutingStatsRequest struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
FieldSelectors []string `protobuf:"bytes,1,rep,name=FieldSelectors,proto3" json:"FieldSelectors,omitempty"`
|
||||
}
|
||||
|
||||
func (x *SubscribeRoutingStatsRequest) Reset() {
|
||||
*x = SubscribeRoutingStatsRequest{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_app_router_command_command_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *SubscribeRoutingStatsRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*SubscribeRoutingStatsRequest) ProtoMessage() {}
|
||||
|
||||
func (x *SubscribeRoutingStatsRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_router_command_command_proto_msgTypes[1]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use SubscribeRoutingStatsRequest.ProtoReflect.Descriptor instead.
|
||||
func (*SubscribeRoutingStatsRequest) Descriptor() ([]byte, []int) {
|
||||
return file_app_router_command_command_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *SubscribeRoutingStatsRequest) GetFieldSelectors() []string {
|
||||
if x != nil {
|
||||
return x.FieldSelectors
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestRouteRequest manually tests a routing result according to the routing
|
||||
// context message.
|
||||
// * RoutingContext is the routing message without outbound information.
|
||||
// * FieldSelectors selects the fields to return in the routing result. All
|
||||
// fields are returned if left empty.
|
||||
// * PublishResult broadcasts the routing result to routing statistics channel
|
||||
// if set true.
|
||||
type TestRouteRequest struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
RoutingContext *RoutingContext `protobuf:"bytes,1,opt,name=RoutingContext,proto3" json:"RoutingContext,omitempty"`
|
||||
FieldSelectors []string `protobuf:"bytes,2,rep,name=FieldSelectors,proto3" json:"FieldSelectors,omitempty"`
|
||||
PublishResult bool `protobuf:"varint,3,opt,name=PublishResult,proto3" json:"PublishResult,omitempty"`
|
||||
}
|
||||
|
||||
func (x *TestRouteRequest) Reset() {
|
||||
*x = TestRouteRequest{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_app_router_command_command_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *TestRouteRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*TestRouteRequest) ProtoMessage() {}
|
||||
|
||||
func (x *TestRouteRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_router_command_command_proto_msgTypes[2]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use TestRouteRequest.ProtoReflect.Descriptor instead.
|
||||
func (*TestRouteRequest) Descriptor() ([]byte, []int) {
|
||||
return file_app_router_command_command_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *TestRouteRequest) GetRoutingContext() *RoutingContext {
|
||||
if x != nil {
|
||||
return x.RoutingContext
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *TestRouteRequest) GetFieldSelectors() []string {
|
||||
if x != nil {
|
||||
return x.FieldSelectors
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *TestRouteRequest) GetPublishResult() bool {
|
||||
if x != nil {
|
||||
return x.PublishResult
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
}
|
||||
|
||||
func (x *Config) Reset() {
|
||||
*x = Config{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_app_router_command_command_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Config) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Config) ProtoMessage() {}
|
||||
|
||||
func (x *Config) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_router_command_command_proto_msgTypes[3]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
|
||||
func (*Config) Descriptor() ([]byte, []int) {
|
||||
return file_app_router_command_command_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
var File_app_router_command_command_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_app_router_command_command_proto_rawDesc = []byte{
|
||||
0x0a, 0x20, 0x61, 0x70, 0x70, 0x2f, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2f, 0x63, 0x6f, 0x6d,
|
||||
0x6d, 0x61, 0x6e, 0x64, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x2e, 0x70, 0x72, 0x6f,
|
||||
0x74, 0x6f, 0x12, 0x17, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f, 0x75,
|
||||
0x74, 0x65, 0x72, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x1a, 0x18, 0x63, 0x6f, 0x6d,
|
||||
0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0x2f, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e,
|
||||
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x9c, 0x04, 0x0a, 0x0e, 0x52, 0x6f, 0x75, 0x74, 0x69, 0x6e,
|
||||
0x67, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x12, 0x1e, 0x0a, 0x0a, 0x49, 0x6e, 0x62, 0x6f,
|
||||
0x75, 0x6e, 0x64, 0x54, 0x61, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x49, 0x6e,
|
||||
0x62, 0x6f, 0x75, 0x6e, 0x64, 0x54, 0x61, 0x67, 0x12, 0x32, 0x0a, 0x07, 0x4e, 0x65, 0x74, 0x77,
|
||||
0x6f, 0x72, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x18, 0x2e, 0x78, 0x72, 0x61, 0x79,
|
||||
0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x4e, 0x65, 0x74, 0x77,
|
||||
0x6f, 0x72, 0x6b, 0x52, 0x07, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x12, 0x1c, 0x0a, 0x09,
|
||||
0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x49, 0x50, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0c, 0x52,
|
||||
0x09, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x49, 0x50, 0x73, 0x12, 0x1c, 0x0a, 0x09, 0x54, 0x61,
|
||||
0x72, 0x67, 0x65, 0x74, 0x49, 0x50, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x09, 0x54,
|
||||
0x61, 0x72, 0x67, 0x65, 0x74, 0x49, 0x50, 0x73, 0x12, 0x1e, 0x0a, 0x0a, 0x53, 0x6f, 0x75, 0x72,
|
||||
0x63, 0x65, 0x50, 0x6f, 0x72, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x53, 0x6f,
|
||||
0x75, 0x72, 0x63, 0x65, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x1e, 0x0a, 0x0a, 0x54, 0x61, 0x72, 0x67,
|
||||
0x65, 0x74, 0x50, 0x6f, 0x72, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x54, 0x61,
|
||||
0x72, 0x67, 0x65, 0x74, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x22, 0x0a, 0x0c, 0x54, 0x61, 0x72, 0x67,
|
||||
0x65, 0x74, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c,
|
||||
0x54, 0x61, 0x72, 0x67, 0x65, 0x74, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x12, 0x1a, 0x0a, 0x08,
|
||||
0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08,
|
||||
0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x12, 0x12, 0x0a, 0x04, 0x55, 0x73, 0x65, 0x72,
|
||||
0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x55, 0x73, 0x65, 0x72, 0x12, 0x57, 0x0a, 0x0a,
|
||||
0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x0a, 0x20, 0x03, 0x28, 0x0b,
|
||||
0x32, 0x37, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f, 0x75, 0x74,
|
||||
0x65, 0x72, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x2e, 0x52, 0x6f, 0x75, 0x74, 0x69,
|
||||
0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x2e, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62,
|
||||
0x75, 0x74, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0a, 0x41, 0x74, 0x74, 0x72, 0x69,
|
||||
0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x2c, 0x0a, 0x11, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e,
|
||||
0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x54, 0x61, 0x67, 0x73, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x09,
|
||||
0x52, 0x11, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x54,
|
||||
0x61, 0x67, 0x73, 0x12, 0x20, 0x0a, 0x0b, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x54,
|
||||
0x61, 0x67, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75,
|
||||
0x6e, 0x64, 0x54, 0x61, 0x67, 0x1a, 0x3d, 0x0a, 0x0f, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75,
|
||||
0x74, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18,
|
||||
0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61,
|
||||
0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65,
|
||||
0x3a, 0x02, 0x38, 0x01, 0x22, 0x46, 0x0a, 0x1c, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62,
|
||||
0x65, 0x52, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x53, 0x74, 0x61, 0x74, 0x73, 0x52, 0x65, 0x71,
|
||||
0x75, 0x65, 0x73, 0x74, 0x12, 0x26, 0x0a, 0x0e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x53, 0x65, 0x6c,
|
||||
0x65, 0x63, 0x74, 0x6f, 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0e, 0x46, 0x69,
|
||||
0x65, 0x6c, 0x64, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x73, 0x22, 0xb1, 0x01, 0x0a,
|
||||
0x10, 0x54, 0x65, 0x73, 0x74, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
|
||||
0x74, 0x12, 0x4f, 0x0a, 0x0e, 0x52, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x74,
|
||||
0x65, 0x78, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x78, 0x72, 0x61, 0x79,
|
||||
0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2e, 0x63, 0x6f, 0x6d, 0x6d,
|
||||
0x61, 0x6e, 0x64, 0x2e, 0x52, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x65,
|
||||
0x78, 0x74, 0x52, 0x0e, 0x52, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x65,
|
||||
0x78, 0x74, 0x12, 0x26, 0x0a, 0x0e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x53, 0x65, 0x6c, 0x65, 0x63,
|
||||
0x74, 0x6f, 0x72, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0e, 0x46, 0x69, 0x65, 0x6c,
|
||||
0x64, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x73, 0x12, 0x24, 0x0a, 0x0d, 0x50, 0x75,
|
||||
0x62, 0x6c, 0x69, 0x73, 0x68, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28,
|
||||
0x08, 0x52, 0x0d, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x73, 0x68, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74,
|
||||
0x22, 0x08, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x32, 0xf0, 0x01, 0x0a, 0x0e, 0x52,
|
||||
0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x7b, 0x0a,
|
||||
0x15, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x6f, 0x75, 0x74, 0x69, 0x6e,
|
||||
0x67, 0x53, 0x74, 0x61, 0x74, 0x73, 0x12, 0x35, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x61, 0x70,
|
||||
0x70, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64,
|
||||
0x2e, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x6f, 0x75, 0x74, 0x69, 0x6e,
|
||||
0x67, 0x53, 0x74, 0x61, 0x74, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e,
|
||||
0x78, 0x72, 0x61, 0x79, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2e,
|
||||
0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x2e, 0x52, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x43,
|
||||
0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x22, 0x00, 0x30, 0x01, 0x12, 0x61, 0x0a, 0x09, 0x54, 0x65,
|
||||
0x73, 0x74, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x12, 0x29, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x61,
|
||||
0x70, 0x70, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e,
|
||||
0x64, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65,
|
||||
0x73, 0x74, 0x1a, 0x27, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f,
|
||||
0x75, 0x74, 0x65, 0x72, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x2e, 0x52, 0x6f, 0x75,
|
||||
0x74, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x22, 0x00, 0x42, 0x6a, 0x0a,
|
||||
0x1b, 0x63, 0x6f, 0x6d, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f,
|
||||
0x75, 0x74, 0x65, 0x72, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x50, 0x01, 0x5a, 0x2f,
|
||||
0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x74, 0x6c, 0x73, 0x2f,
|
||||
0x78, 0x72, 0x61, 0x79, 0x2d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x61, 0x70, 0x70,
|
||||
0x2f, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0xaa,
|
||||
0x02, 0x17, 0x58, 0x72, 0x61, 0x79, 0x2e, 0x41, 0x70, 0x70, 0x2e, 0x52, 0x6f, 0x75, 0x74, 0x65,
|
||||
0x72, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
|
||||
0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_app_router_command_command_proto_rawDescOnce sync.Once
|
||||
file_app_router_command_command_proto_rawDescData = file_app_router_command_command_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_app_router_command_command_proto_rawDescGZIP() []byte {
|
||||
file_app_router_command_command_proto_rawDescOnce.Do(func() {
|
||||
file_app_router_command_command_proto_rawDescData = protoimpl.X.CompressGZIP(file_app_router_command_command_proto_rawDescData)
|
||||
})
|
||||
return file_app_router_command_command_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_app_router_command_command_proto_msgTypes = make([]protoimpl.MessageInfo, 5)
|
||||
var file_app_router_command_command_proto_goTypes = []interface{}{
|
||||
(*RoutingContext)(nil), // 0: xray.app.router.command.RoutingContext
|
||||
(*SubscribeRoutingStatsRequest)(nil), // 1: xray.app.router.command.SubscribeRoutingStatsRequest
|
||||
(*TestRouteRequest)(nil), // 2: xray.app.router.command.TestRouteRequest
|
||||
(*Config)(nil), // 3: xray.app.router.command.Config
|
||||
nil, // 4: xray.app.router.command.RoutingContext.AttributesEntry
|
||||
(net.Network)(0), // 5: xray.common.net.Network
|
||||
}
|
||||
var file_app_router_command_command_proto_depIdxs = []int32{
|
||||
5, // 0: xray.app.router.command.RoutingContext.Network:type_name -> xray.common.net.Network
|
||||
4, // 1: xray.app.router.command.RoutingContext.Attributes:type_name -> xray.app.router.command.RoutingContext.AttributesEntry
|
||||
0, // 2: xray.app.router.command.TestRouteRequest.RoutingContext:type_name -> xray.app.router.command.RoutingContext
|
||||
1, // 3: xray.app.router.command.RoutingService.SubscribeRoutingStats:input_type -> xray.app.router.command.SubscribeRoutingStatsRequest
|
||||
2, // 4: xray.app.router.command.RoutingService.TestRoute:input_type -> xray.app.router.command.TestRouteRequest
|
||||
0, // 5: xray.app.router.command.RoutingService.SubscribeRoutingStats:output_type -> xray.app.router.command.RoutingContext
|
||||
0, // 6: xray.app.router.command.RoutingService.TestRoute:output_type -> xray.app.router.command.RoutingContext
|
||||
5, // [5:7] is the sub-list for method output_type
|
||||
3, // [3:5] is the sub-list for method input_type
|
||||
3, // [3:3] is the sub-list for extension type_name
|
||||
3, // [3:3] is the sub-list for extension extendee
|
||||
0, // [0:3] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_app_router_command_command_proto_init() }
|
||||
func file_app_router_command_command_proto_init() {
|
||||
if File_app_router_command_command_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_app_router_command_command_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*RoutingContext); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_app_router_command_command_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*SubscribeRoutingStatsRequest); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_app_router_command_command_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*TestRouteRequest); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_app_router_command_command_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Config); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_app_router_command_command_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 5,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_app_router_command_command_proto_goTypes,
|
||||
DependencyIndexes: file_app_router_command_command_proto_depIdxs,
|
||||
MessageInfos: file_app_router_command_command_proto_msgTypes,
|
||||
}.Build()
|
||||
File_app_router_command_command_proto = out.File
|
||||
file_app_router_command_command_proto_rawDesc = nil
|
||||
file_app_router_command_command_proto_goTypes = nil
|
||||
file_app_router_command_command_proto_depIdxs = nil
|
||||
}
|
69
app/router/command/command.proto
Normal file
69
app/router/command/command.proto
Normal file
|
@ -0,0 +1,69 @@
|
|||
syntax = "proto3";
|
||||
|
||||
package xray.app.router.command;
|
||||
option csharp_namespace = "Xray.App.Router.Command";
|
||||
option go_package = "github.com/xtls/xray-core/v1/app/router/command";
|
||||
option java_package = "com.xray.app.router.command";
|
||||
option java_multiple_files = true;
|
||||
|
||||
import "common/net/network.proto";
|
||||
|
||||
// RoutingContext is the context with information relative to routing process.
|
||||
// It conforms to the structure of xray.features.routing.Context and
|
||||
// xray.features.routing.Route.
|
||||
message RoutingContext {
|
||||
string InboundTag = 1;
|
||||
xray.common.net.Network Network = 2;
|
||||
repeated bytes SourceIPs = 3;
|
||||
repeated bytes TargetIPs = 4;
|
||||
uint32 SourcePort = 5;
|
||||
uint32 TargetPort = 6;
|
||||
string TargetDomain = 7;
|
||||
string Protocol = 8;
|
||||
string User = 9;
|
||||
map<string, string> Attributes = 10;
|
||||
repeated string OutboundGroupTags = 11;
|
||||
string OutboundTag = 12;
|
||||
}
|
||||
|
||||
// SubscribeRoutingStatsRequest subscribes to routing statistics channel if
|
||||
// opened by xray-core.
|
||||
// * FieldSelectors selects a subset of fields in routing statistics to return.
|
||||
// Valid selectors:
|
||||
// - inbound: Selects connection's inbound tag.
|
||||
// - network: Selects connection's network.
|
||||
// - ip: Equivalent as "ip_source" and "ip_target", selects both source and
|
||||
// target IP.
|
||||
// - port: Equivalent as "port_source" and "port_target", selects both source
|
||||
// and target port.
|
||||
// - domain: Selects target domain.
|
||||
// - protocol: Select connection's protocol.
|
||||
// - user: Select connection's inbound user email.
|
||||
// - attributes: Select connection's additional attributes.
|
||||
// - outbound: Equivalent as "outbound" and "outbound_group", select both
|
||||
// outbound tag and outbound group tags.
|
||||
// * If FieldSelectors is left empty, all fields will be returned.
|
||||
message SubscribeRoutingStatsRequest {
|
||||
repeated string FieldSelectors = 1;
|
||||
}
|
||||
|
||||
// TestRouteRequest manually tests a routing result according to the routing
|
||||
// context message.
|
||||
// * RoutingContext is the routing message without outbound information.
|
||||
// * FieldSelectors selects the fields to return in the routing result. All
|
||||
// fields are returned if left empty.
|
||||
// * PublishResult broadcasts the routing result to routing statistics channel
|
||||
// if set true.
|
||||
message TestRouteRequest {
|
||||
RoutingContext RoutingContext = 1;
|
||||
repeated string FieldSelectors = 2;
|
||||
bool PublishResult = 3;
|
||||
}
|
||||
|
||||
service RoutingService {
|
||||
rpc SubscribeRoutingStats(SubscribeRoutingStatsRequest)
|
||||
returns (stream RoutingContext) {}
|
||||
rpc TestRoute(TestRouteRequest) returns (RoutingContext) {}
|
||||
}
|
||||
|
||||
message Config {}
|
161
app/router/command/command_grpc.pb.go
Normal file
161
app/router/command/command_grpc.pb.go
Normal file
|
@ -0,0 +1,161 @@
|
|||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
|
||||
package command
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
const _ = grpc.SupportPackageIsVersion7
|
||||
|
||||
// RoutingServiceClient is the client API for RoutingService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type RoutingServiceClient interface {
|
||||
SubscribeRoutingStats(ctx context.Context, in *SubscribeRoutingStatsRequest, opts ...grpc.CallOption) (RoutingService_SubscribeRoutingStatsClient, error)
|
||||
TestRoute(ctx context.Context, in *TestRouteRequest, opts ...grpc.CallOption) (*RoutingContext, error)
|
||||
}
|
||||
|
||||
type routingServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewRoutingServiceClient(cc grpc.ClientConnInterface) RoutingServiceClient {
|
||||
return &routingServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *routingServiceClient) SubscribeRoutingStats(ctx context.Context, in *SubscribeRoutingStatsRequest, opts ...grpc.CallOption) (RoutingService_SubscribeRoutingStatsClient, error) {
|
||||
stream, err := c.cc.NewStream(ctx, &_RoutingService_serviceDesc.Streams[0], "/xray.app.router.command.RoutingService/SubscribeRoutingStats", opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &routingServiceSubscribeRoutingStatsClient{stream}
|
||||
if err := x.ClientStream.SendMsg(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := x.ClientStream.CloseSend(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
type RoutingService_SubscribeRoutingStatsClient interface {
|
||||
Recv() (*RoutingContext, error)
|
||||
grpc.ClientStream
|
||||
}
|
||||
|
||||
type routingServiceSubscribeRoutingStatsClient struct {
|
||||
grpc.ClientStream
|
||||
}
|
||||
|
||||
func (x *routingServiceSubscribeRoutingStatsClient) Recv() (*RoutingContext, error) {
|
||||
m := new(RoutingContext)
|
||||
if err := x.ClientStream.RecvMsg(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (c *routingServiceClient) TestRoute(ctx context.Context, in *TestRouteRequest, opts ...grpc.CallOption) (*RoutingContext, error) {
|
||||
out := new(RoutingContext)
|
||||
err := c.cc.Invoke(ctx, "/xray.app.router.command.RoutingService/TestRoute", in, out, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// RoutingServiceServer is the server API for RoutingService service.
|
||||
// All implementations must embed UnimplementedRoutingServiceServer
|
||||
// for forward compatibility
|
||||
type RoutingServiceServer interface {
|
||||
SubscribeRoutingStats(*SubscribeRoutingStatsRequest, RoutingService_SubscribeRoutingStatsServer) error
|
||||
TestRoute(context.Context, *TestRouteRequest) (*RoutingContext, error)
|
||||
mustEmbedUnimplementedRoutingServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedRoutingServiceServer must be embedded to have forward compatible implementations.
|
||||
type UnimplementedRoutingServiceServer struct {
|
||||
}
|
||||
|
||||
func (UnimplementedRoutingServiceServer) SubscribeRoutingStats(*SubscribeRoutingStatsRequest, RoutingService_SubscribeRoutingStatsServer) error {
|
||||
return status.Errorf(codes.Unimplemented, "method SubscribeRoutingStats not implemented")
|
||||
}
|
||||
func (UnimplementedRoutingServiceServer) TestRoute(context.Context, *TestRouteRequest) (*RoutingContext, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method TestRoute not implemented")
|
||||
}
|
||||
func (UnimplementedRoutingServiceServer) mustEmbedUnimplementedRoutingServiceServer() {}
|
||||
|
||||
// UnsafeRoutingServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to RoutingServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeRoutingServiceServer interface {
|
||||
mustEmbedUnimplementedRoutingServiceServer()
|
||||
}
|
||||
|
||||
func RegisterRoutingServiceServer(s grpc.ServiceRegistrar, srv RoutingServiceServer) {
|
||||
s.RegisterService(&_RoutingService_serviceDesc, srv)
|
||||
}
|
||||
|
||||
func _RoutingService_SubscribeRoutingStats_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
m := new(SubscribeRoutingStatsRequest)
|
||||
if err := stream.RecvMsg(m); err != nil {
|
||||
return err
|
||||
}
|
||||
return srv.(RoutingServiceServer).SubscribeRoutingStats(m, &routingServiceSubscribeRoutingStatsServer{stream})
|
||||
}
|
||||
|
||||
type RoutingService_SubscribeRoutingStatsServer interface {
|
||||
Send(*RoutingContext) error
|
||||
grpc.ServerStream
|
||||
}
|
||||
|
||||
type routingServiceSubscribeRoutingStatsServer struct {
|
||||
grpc.ServerStream
|
||||
}
|
||||
|
||||
func (x *routingServiceSubscribeRoutingStatsServer) Send(m *RoutingContext) error {
|
||||
return x.ServerStream.SendMsg(m)
|
||||
}
|
||||
|
||||
func _RoutingService_TestRoute_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(TestRouteRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(RoutingServiceServer).TestRoute(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: "/xray.app.router.command.RoutingService/TestRoute",
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(RoutingServiceServer).TestRoute(ctx, req.(*TestRouteRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
var _RoutingService_serviceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "xray.app.router.command.RoutingService",
|
||||
HandlerType: (*RoutingServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "TestRoute",
|
||||
Handler: _RoutingService_TestRoute_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
StreamName: "SubscribeRoutingStats",
|
||||
Handler: _RoutingService_SubscribeRoutingStats_Handler,
|
||||
ServerStreams: true,
|
||||
},
|
||||
},
|
||||
Metadata: "app/router/command/command.proto",
|
||||
}
|
361
app/router/command/command_test.go
Normal file
361
app/router/command/command_test.go
Normal file
|
@ -0,0 +1,361 @@
|
|||
package command_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/google/go-cmp/cmp/cmpopts"
|
||||
"github.com/xtls/xray-core/v1/app/router"
|
||||
. "github.com/xtls/xray-core/v1/app/router/command"
|
||||
"github.com/xtls/xray-core/v1/app/stats"
|
||||
"github.com/xtls/xray-core/v1/common"
|
||||
"github.com/xtls/xray-core/v1/common/net"
|
||||
"github.com/xtls/xray-core/v1/features/routing"
|
||||
"github.com/xtls/xray-core/v1/testing/mocks"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
)
|
||||
|
||||
func TestServiceSubscribeRoutingStats(t *testing.T) {
|
||||
c := stats.NewChannel(&stats.ChannelConfig{
|
||||
SubscriberLimit: 1,
|
||||
BufferSize: 0,
|
||||
Blocking: true,
|
||||
})
|
||||
common.Must(c.Start())
|
||||
defer c.Close()
|
||||
|
||||
lis := bufconn.Listen(1024 * 1024)
|
||||
bufDialer := func(context.Context, string) (net.Conn, error) {
|
||||
return lis.Dial()
|
||||
}
|
||||
|
||||
testCases := []*RoutingContext{
|
||||
{InboundTag: "in", OutboundTag: "out"},
|
||||
{TargetIPs: [][]byte{{1, 2, 3, 4}}, TargetPort: 8080, OutboundTag: "out"},
|
||||
{TargetDomain: "example.com", TargetPort: 443, OutboundTag: "out"},
|
||||
{SourcePort: 9999, TargetPort: 9999, OutboundTag: "out"},
|
||||
{Network: net.Network_UDP, OutboundGroupTags: []string{"outergroup", "innergroup"}, OutboundTag: "out"},
|
||||
{Protocol: "bittorrent", OutboundTag: "blocked"},
|
||||
{User: "example@example.com", OutboundTag: "out"},
|
||||
{SourceIPs: [][]byte{{127, 0, 0, 1}}, Attributes: map[string]string{"attr": "value"}, OutboundTag: "out"},
|
||||
}
|
||||
errCh := make(chan error)
|
||||
nextPub := make(chan struct{})
|
||||
|
||||
// Server goroutine
|
||||
go func() {
|
||||
server := grpc.NewServer()
|
||||
RegisterRoutingServiceServer(server, NewRoutingServer(nil, c))
|
||||
errCh <- server.Serve(lis)
|
||||
}()
|
||||
|
||||
// Publisher goroutine
|
||||
go func() {
|
||||
publishTestCases := func() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
for { // Wait until there's one subscriber in routing stats channel
|
||||
if len(c.Subscribers()) > 0 {
|
||||
break
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
c.Publish(context.Background(), AsRoutingRoute(tc))
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := publishTestCases(); err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
|
||||
// Wait for next round of publishing
|
||||
<-nextPub
|
||||
|
||||
if err := publishTestCases(); err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
}()
|
||||
|
||||
// Client goroutine
|
||||
go func() {
|
||||
defer lis.Close()
|
||||
conn, err := grpc.DialContext(context.Background(), "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
client := NewRoutingServiceClient(conn)
|
||||
|
||||
// Test retrieving all fields
|
||||
testRetrievingAllFields := func() error {
|
||||
streamCtx, streamClose := context.WithCancel(context.Background())
|
||||
|
||||
// Test the unsubscription of stream works well
|
||||
defer func() {
|
||||
streamClose()
|
||||
timeOutCtx, timeout := context.WithTimeout(context.Background(), time.Second)
|
||||
defer timeout()
|
||||
for { // Wait until there's no subscriber in routing stats channel
|
||||
if len(c.Subscribers()) == 0 {
|
||||
break
|
||||
}
|
||||
if timeOutCtx.Err() != nil {
|
||||
t.Error("unexpected subscribers not decreased in channel", timeOutCtx.Err())
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
stream, err := client.SubscribeRoutingStats(streamCtx, &SubscribeRoutingStatsRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
msg, err := stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r := cmp.Diff(msg, tc, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
|
||||
t.Error(r)
|
||||
}
|
||||
}
|
||||
|
||||
// Test that double subscription will fail
|
||||
errStream, err := client.SubscribeRoutingStats(context.Background(), &SubscribeRoutingStatsRequest{
|
||||
FieldSelectors: []string{"ip", "port", "domain", "outbound"},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := errStream.Recv(); err == nil {
|
||||
t.Error("unexpected successful subscription")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Test retrieving only a subset of fields
|
||||
testRetrievingSubsetOfFields := func() error {
|
||||
streamCtx, streamClose := context.WithCancel(context.Background())
|
||||
defer streamClose()
|
||||
stream, err := client.SubscribeRoutingStats(streamCtx, &SubscribeRoutingStatsRequest{
|
||||
FieldSelectors: []string{"ip", "port", "domain", "outbound"},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Send nextPub signal to start next round of publishing
|
||||
close(nextPub)
|
||||
|
||||
for _, tc := range testCases {
|
||||
msg, err := stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
stat := &RoutingContext{ // Only a subset of stats is retrieved
|
||||
SourceIPs: tc.SourceIPs,
|
||||
TargetIPs: tc.TargetIPs,
|
||||
SourcePort: tc.SourcePort,
|
||||
TargetPort: tc.TargetPort,
|
||||
TargetDomain: tc.TargetDomain,
|
||||
OutboundGroupTags: tc.OutboundGroupTags,
|
||||
OutboundTag: tc.OutboundTag,
|
||||
}
|
||||
if r := cmp.Diff(msg, stat, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
|
||||
t.Error(r)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := testRetrievingAllFields(); err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
if err := testRetrievingSubsetOfFields(); err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
errCh <- nil // Client passed all tests successfully
|
||||
}()
|
||||
|
||||
// Wait for goroutines to complete
|
||||
select {
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Test timeout after 2s")
|
||||
case err := <-errCh:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerivceTestRoute(t *testing.T) {
|
||||
c := stats.NewChannel(&stats.ChannelConfig{
|
||||
SubscriberLimit: 1,
|
||||
BufferSize: 16,
|
||||
Blocking: true,
|
||||
})
|
||||
common.Must(c.Start())
|
||||
defer c.Close()
|
||||
|
||||
r := new(router.Router)
|
||||
mockCtl := gomock.NewController(t)
|
||||
defer mockCtl.Finish()
|
||||
common.Must(r.Init(&router.Config{
|
||||
Rule: []*router.RoutingRule{
|
||||
{
|
||||
InboundTag: []string{"in"},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "out"},
|
||||
},
|
||||
{
|
||||
Protocol: []string{"bittorrent"},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "blocked"},
|
||||
},
|
||||
{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{{From: 8080, To: 8080}}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "out"},
|
||||
},
|
||||
{
|
||||
SourcePortList: &net.PortList{Range: []*net.PortRange{{From: 9999, To: 9999}}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "out"},
|
||||
},
|
||||
{
|
||||
Domain: []*router.Domain{{Type: router.Domain_Domain, Value: "com"}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "out"},
|
||||
},
|
||||
{
|
||||
SourceGeoip: []*router.GeoIP{{CountryCode: "private", Cidr: []*router.CIDR{{Ip: []byte{127, 0, 0, 0}, Prefix: 8}}}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "out"},
|
||||
},
|
||||
{
|
||||
UserEmail: []string{"example@example.com"},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "out"},
|
||||
},
|
||||
{
|
||||
Networks: []net.Network{net.Network_UDP, net.Network_TCP},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "out"},
|
||||
},
|
||||
},
|
||||
}, mocks.NewDNSClient(mockCtl), mocks.NewOutboundManager(mockCtl)))
|
||||
|
||||
lis := bufconn.Listen(1024 * 1024)
|
||||
bufDialer := func(context.Context, string) (net.Conn, error) {
|
||||
return lis.Dial()
|
||||
}
|
||||
|
||||
errCh := make(chan error)
|
||||
|
||||
// Server goroutine
|
||||
go func() {
|
||||
server := grpc.NewServer()
|
||||
RegisterRoutingServiceServer(server, NewRoutingServer(r, c))
|
||||
errCh <- server.Serve(lis)
|
||||
}()
|
||||
|
||||
// Client goroutine
|
||||
go func() {
|
||||
defer lis.Close()
|
||||
conn, err := grpc.DialContext(context.Background(), "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
defer conn.Close()
|
||||
client := NewRoutingServiceClient(conn)
|
||||
|
||||
testCases := []*RoutingContext{
|
||||
{InboundTag: "in", OutboundTag: "out"},
|
||||
{TargetIPs: [][]byte{{1, 2, 3, 4}}, TargetPort: 8080, OutboundTag: "out"},
|
||||
{TargetDomain: "example.com", TargetPort: 443, OutboundTag: "out"},
|
||||
{SourcePort: 9999, TargetPort: 9999, OutboundTag: "out"},
|
||||
{Network: net.Network_UDP, Protocol: "bittorrent", OutboundTag: "blocked"},
|
||||
{User: "example@example.com", OutboundTag: "out"},
|
||||
{SourceIPs: [][]byte{{127, 0, 0, 1}}, Attributes: map[string]string{"attr": "value"}, OutboundTag: "out"},
|
||||
}
|
||||
|
||||
// Test simple TestRoute
|
||||
testSimple := func() error {
|
||||
for _, tc := range testCases {
|
||||
route, err := client.TestRoute(context.Background(), &TestRouteRequest{RoutingContext: tc})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r := cmp.Diff(route, tc, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
|
||||
t.Error(r)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Test TestRoute with special options
|
||||
testOptions := func() error {
|
||||
sub, err := c.Subscribe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
route, err := client.TestRoute(context.Background(), &TestRouteRequest{
|
||||
RoutingContext: tc,
|
||||
FieldSelectors: []string{"ip", "port", "domain", "outbound"},
|
||||
PublishResult: true,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
stat := &RoutingContext{ // Only a subset of stats is retrieved
|
||||
SourceIPs: tc.SourceIPs,
|
||||
TargetIPs: tc.TargetIPs,
|
||||
SourcePort: tc.SourcePort,
|
||||
TargetPort: tc.TargetPort,
|
||||
TargetDomain: tc.TargetDomain,
|
||||
OutboundGroupTags: tc.OutboundGroupTags,
|
||||
OutboundTag: tc.OutboundTag,
|
||||
}
|
||||
if r := cmp.Diff(route, stat, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
|
||||
t.Error(r)
|
||||
}
|
||||
select { // Check that routing result has been published to statistics channel
|
||||
case msg, received := <-sub:
|
||||
if route, ok := msg.(routing.Route); received && ok {
|
||||
if r := cmp.Diff(AsProtobufMessage(nil)(route), tc, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
|
||||
t.Error(r)
|
||||
}
|
||||
} else {
|
||||
t.Error("unexpected failure in receiving published routing result for testcase", tc)
|
||||
}
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
t.Error("unexpected failure in receiving published routing result", tc)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := testSimple(); err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
if err := testOptions(); err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
errCh <- nil // Client passed all tests successfully
|
||||
}()
|
||||
|
||||
// Wait for goroutines to complete
|
||||
select {
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Test timeout after 2s")
|
||||
case err := <-errCh:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
94
app/router/command/config.go
Normal file
94
app/router/command/config.go
Normal file
|
@ -0,0 +1,94 @@
|
|||
package command
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/xtls/xray-core/v1/common/net"
|
||||
"github.com/xtls/xray-core/v1/features/routing"
|
||||
)
|
||||
|
||||
// routingContext is an wrapper of protobuf RoutingContext as implementation of routing.Context and routing.Route.
|
||||
type routingContext struct {
|
||||
*RoutingContext
|
||||
}
|
||||
|
||||
func (c routingContext) GetSourceIPs() []net.IP {
|
||||
return mapBytesToIPs(c.RoutingContext.GetSourceIPs())
|
||||
}
|
||||
|
||||
func (c routingContext) GetSourcePort() net.Port {
|
||||
return net.Port(c.RoutingContext.GetSourcePort())
|
||||
}
|
||||
|
||||
func (c routingContext) GetTargetIPs() []net.IP {
|
||||
return mapBytesToIPs(c.RoutingContext.GetTargetIPs())
|
||||
}
|
||||
|
||||
func (c routingContext) GetTargetPort() net.Port {
|
||||
return net.Port(c.RoutingContext.GetTargetPort())
|
||||
}
|
||||
|
||||
// AsRoutingContext converts a protobuf RoutingContext into an implementation of routing.Context.
|
||||
func AsRoutingContext(r *RoutingContext) routing.Context {
|
||||
return routingContext{r}
|
||||
}
|
||||
|
||||
// AsRoutingRoute converts a protobuf RoutingContext into an implementation of routing.Route.
|
||||
func AsRoutingRoute(r *RoutingContext) routing.Route {
|
||||
return routingContext{r}
|
||||
}
|
||||
|
||||
var fieldMap = map[string]func(*RoutingContext, routing.Route){
|
||||
"inbound": func(s *RoutingContext, r routing.Route) { s.InboundTag = r.GetInboundTag() },
|
||||
"network": func(s *RoutingContext, r routing.Route) { s.Network = r.GetNetwork() },
|
||||
"ip_source": func(s *RoutingContext, r routing.Route) { s.SourceIPs = mapIPsToBytes(r.GetSourceIPs()) },
|
||||
"ip_target": func(s *RoutingContext, r routing.Route) { s.TargetIPs = mapIPsToBytes(r.GetTargetIPs()) },
|
||||
"port_source": func(s *RoutingContext, r routing.Route) { s.SourcePort = uint32(r.GetSourcePort()) },
|
||||
"port_target": func(s *RoutingContext, r routing.Route) { s.TargetPort = uint32(r.GetTargetPort()) },
|
||||
"domain": func(s *RoutingContext, r routing.Route) { s.TargetDomain = r.GetTargetDomain() },
|
||||
"protocol": func(s *RoutingContext, r routing.Route) { s.Protocol = r.GetProtocol() },
|
||||
"user": func(s *RoutingContext, r routing.Route) { s.User = r.GetUser() },
|
||||
"attributes": func(s *RoutingContext, r routing.Route) { s.Attributes = r.GetAttributes() },
|
||||
"outbound_group": func(s *RoutingContext, r routing.Route) { s.OutboundGroupTags = r.GetOutboundGroupTags() },
|
||||
"outbound": func(s *RoutingContext, r routing.Route) { s.OutboundTag = r.GetOutboundTag() },
|
||||
}
|
||||
|
||||
// AsProtobufMessage takes selectors of fields and returns a function to convert routing.Route to protobuf RoutingContext.
|
||||
func AsProtobufMessage(fieldSelectors []string) func(routing.Route) *RoutingContext {
|
||||
initializers := []func(*RoutingContext, routing.Route){}
|
||||
for field, init := range fieldMap {
|
||||
if len(fieldSelectors) == 0 { // If selectors not set, retrieve all fields
|
||||
initializers = append(initializers, init)
|
||||
continue
|
||||
}
|
||||
for _, selector := range fieldSelectors {
|
||||
if strings.HasPrefix(field, selector) {
|
||||
initializers = append(initializers, init)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return func(ctx routing.Route) *RoutingContext {
|
||||
message := new(RoutingContext)
|
||||
for _, init := range initializers {
|
||||
init(message, ctx)
|
||||
}
|
||||
return message
|
||||
}
|
||||
}
|
||||
|
||||
func mapBytesToIPs(bytes [][]byte) []net.IP {
|
||||
var ips []net.IP
|
||||
for _, rawIP := range bytes {
|
||||
ips = append(ips, net.IP(rawIP))
|
||||
}
|
||||
return ips
|
||||
}
|
||||
|
||||
func mapIPsToBytes(ips []net.IP) [][]byte {
|
||||
var bytes [][]byte
|
||||
for _, ip := range ips {
|
||||
bytes = append(bytes, []byte(ip))
|
||||
}
|
||||
return bytes
|
||||
}
|
9
app/router/command/errors.generated.go
Normal file
9
app/router/command/errors.generated.go
Normal file
|
@ -0,0 +1,9 @@
|
|||
package command
|
||||
|
||||
import "github.com/xtls/xray-core/v1/common/errors"
|
||||
|
||||
type errPathObjHolder struct{}
|
||||
|
||||
func newError(values ...interface{}) *errors.Error {
|
||||
return errors.New(values...).WithPathObj(errPathObjHolder{})
|
||||
}
|
319
app/router/condition.go
Normal file
319
app/router/condition.go
Normal file
|
@ -0,0 +1,319 @@
|
|||
// +build !confonly
|
||||
|
||||
package router
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"go.starlark.net/starlark"
|
||||
"go.starlark.net/syntax"
|
||||
|
||||
"github.com/xtls/xray-core/v1/common/net"
|
||||
"github.com/xtls/xray-core/v1/common/strmatcher"
|
||||
"github.com/xtls/xray-core/v1/features/routing"
|
||||
)
|
||||
|
||||
type Condition interface {
|
||||
Apply(ctx routing.Context) bool
|
||||
}
|
||||
|
||||
type ConditionChan []Condition
|
||||
|
||||
func NewConditionChan() *ConditionChan {
|
||||
var condChan ConditionChan = make([]Condition, 0, 8)
|
||||
return &condChan
|
||||
}
|
||||
|
||||
func (v *ConditionChan) Add(cond Condition) *ConditionChan {
|
||||
*v = append(*v, cond)
|
||||
return v
|
||||
}
|
||||
|
||||
// Apply applies all conditions registered in this chan.
|
||||
func (v *ConditionChan) Apply(ctx routing.Context) bool {
|
||||
for _, cond := range *v {
|
||||
if !cond.Apply(ctx) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (v *ConditionChan) Len() int {
|
||||
return len(*v)
|
||||
}
|
||||
|
||||
var matcherTypeMap = map[Domain_Type]strmatcher.Type{
|
||||
Domain_Plain: strmatcher.Substr,
|
||||
Domain_Regex: strmatcher.Regex,
|
||||
Domain_Domain: strmatcher.Domain,
|
||||
Domain_Full: strmatcher.Full,
|
||||
}
|
||||
|
||||
func domainToMatcher(domain *Domain) (strmatcher.Matcher, error) {
|
||||
matcherType, f := matcherTypeMap[domain.Type]
|
||||
if !f {
|
||||
return nil, newError("unsupported domain type", domain.Type)
|
||||
}
|
||||
|
||||
matcher, err := matcherType.New(domain.Value)
|
||||
if err != nil {
|
||||
return nil, newError("failed to create domain matcher").Base(err)
|
||||
}
|
||||
|
||||
return matcher, nil
|
||||
}
|
||||
|
||||
type DomainMatcher struct {
|
||||
matchers strmatcher.IndexMatcher
|
||||
}
|
||||
|
||||
func NewDomainMatcher(domains []*Domain) (*DomainMatcher, error) {
|
||||
g := new(strmatcher.MatcherGroup)
|
||||
for _, d := range domains {
|
||||
m, err := domainToMatcher(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g.Add(m)
|
||||
}
|
||||
|
||||
return &DomainMatcher{
|
||||
matchers: g,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *DomainMatcher) ApplyDomain(domain string) bool {
|
||||
return len(m.matchers.Match(domain)) > 0
|
||||
}
|
||||
|
||||
// Apply implements Condition.
|
||||
func (m *DomainMatcher) Apply(ctx routing.Context) bool {
|
||||
domain := ctx.GetTargetDomain()
|
||||
if len(domain) == 0 {
|
||||
return false
|
||||
}
|
||||
return m.ApplyDomain(domain)
|
||||
}
|
||||
|
||||
type MultiGeoIPMatcher struct {
|
||||
matchers []*GeoIPMatcher
|
||||
onSource bool
|
||||
}
|
||||
|
||||
func NewMultiGeoIPMatcher(geoips []*GeoIP, onSource bool) (*MultiGeoIPMatcher, error) {
|
||||
var matchers []*GeoIPMatcher
|
||||
for _, geoip := range geoips {
|
||||
matcher, err := globalGeoIPContainer.Add(geoip)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
matchers = append(matchers, matcher)
|
||||
}
|
||||
|
||||
matcher := &MultiGeoIPMatcher{
|
||||
matchers: matchers,
|
||||
onSource: onSource,
|
||||
}
|
||||
|
||||
return matcher, nil
|
||||
}
|
||||
|
||||
// Apply implements Condition.
|
||||
func (m *MultiGeoIPMatcher) Apply(ctx routing.Context) bool {
|
||||
var ips []net.IP
|
||||
if m.onSource {
|
||||
ips = ctx.GetSourceIPs()
|
||||
} else {
|
||||
ips = ctx.GetTargetIPs()
|
||||
}
|
||||
for _, ip := range ips {
|
||||
for _, matcher := range m.matchers {
|
||||
if matcher.Match(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type PortMatcher struct {
|
||||
port net.MemoryPortList
|
||||
onSource bool
|
||||
}
|
||||
|
||||
// NewPortMatcher create a new port matcher that can match source or destination port
|
||||
func NewPortMatcher(list *net.PortList, onSource bool) *PortMatcher {
|
||||
return &PortMatcher{
|
||||
port: net.PortListFromProto(list),
|
||||
onSource: onSource,
|
||||
}
|
||||
}
|
||||
|
||||
// Apply implements Condition.
|
||||
func (v *PortMatcher) Apply(ctx routing.Context) bool {
|
||||
if v.onSource {
|
||||
return v.port.Contains(ctx.GetSourcePort())
|
||||
} else {
|
||||
return v.port.Contains(ctx.GetTargetPort())
|
||||
}
|
||||
}
|
||||
|
||||
type NetworkMatcher struct {
|
||||
list [8]bool
|
||||
}
|
||||
|
||||
func NewNetworkMatcher(network []net.Network) NetworkMatcher {
|
||||
var matcher NetworkMatcher
|
||||
for _, n := range network {
|
||||
matcher.list[int(n)] = true
|
||||
}
|
||||
return matcher
|
||||
}
|
||||
|
||||
// Apply implements Condition.
|
||||
func (v NetworkMatcher) Apply(ctx routing.Context) bool {
|
||||
return v.list[int(ctx.GetNetwork())]
|
||||
}
|
||||
|
||||
type UserMatcher struct {
|
||||
user []string
|
||||
}
|
||||
|
||||
func NewUserMatcher(users []string) *UserMatcher {
|
||||
usersCopy := make([]string, 0, len(users))
|
||||
for _, user := range users {
|
||||
if len(user) > 0 {
|
||||
usersCopy = append(usersCopy, user)
|
||||
}
|
||||
}
|
||||
return &UserMatcher{
|
||||
user: usersCopy,
|
||||
}
|
||||
}
|
||||
|
||||
// Apply implements Condition.
|
||||
func (v *UserMatcher) Apply(ctx routing.Context) bool {
|
||||
user := ctx.GetUser()
|
||||
if len(user) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, u := range v.user {
|
||||
if u == user {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type InboundTagMatcher struct {
|
||||
tags []string
|
||||
}
|
||||
|
||||
func NewInboundTagMatcher(tags []string) *InboundTagMatcher {
|
||||
tagsCopy := make([]string, 0, len(tags))
|
||||
for _, tag := range tags {
|
||||
if len(tag) > 0 {
|
||||
tagsCopy = append(tagsCopy, tag)
|
||||
}
|
||||
}
|
||||
return &InboundTagMatcher{
|
||||
tags: tagsCopy,
|
||||
}
|
||||
}
|
||||
|
||||
// Apply implements Condition.
|
||||
func (v *InboundTagMatcher) Apply(ctx routing.Context) bool {
|
||||
tag := ctx.GetInboundTag()
|
||||
if len(tag) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, t := range v.tags {
|
||||
if t == tag {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type ProtocolMatcher struct {
|
||||
protocols []string
|
||||
}
|
||||
|
||||
func NewProtocolMatcher(protocols []string) *ProtocolMatcher {
|
||||
pCopy := make([]string, 0, len(protocols))
|
||||
|
||||
for _, p := range protocols {
|
||||
if len(p) > 0 {
|
||||
pCopy = append(pCopy, p)
|
||||
}
|
||||
}
|
||||
|
||||
return &ProtocolMatcher{
|
||||
protocols: pCopy,
|
||||
}
|
||||
}
|
||||
|
||||
// Apply implements Condition.
|
||||
func (m *ProtocolMatcher) Apply(ctx routing.Context) bool {
|
||||
protocol := ctx.GetProtocol()
|
||||
if len(protocol) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, p := range m.protocols {
|
||||
if strings.HasPrefix(protocol, p) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type AttributeMatcher struct {
|
||||
program *starlark.Program
|
||||
}
|
||||
|
||||
func NewAttributeMatcher(code string) (*AttributeMatcher, error) {
|
||||
starFile, err := syntax.Parse("attr.star", "satisfied=("+code+")", 0)
|
||||
if err != nil {
|
||||
return nil, newError("attr rule").Base(err)
|
||||
}
|
||||
p, err := starlark.FileProgram(starFile, func(name string) bool {
|
||||
return name == "attrs"
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &AttributeMatcher{
|
||||
program: p,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Match implements attributes matching.
|
||||
func (m *AttributeMatcher) Match(attrs map[string]string) bool {
|
||||
attrsDict := new(starlark.Dict)
|
||||
for key, value := range attrs {
|
||||
attrsDict.SetKey(starlark.String(key), starlark.String(value))
|
||||
}
|
||||
|
||||
predefined := make(starlark.StringDict)
|
||||
predefined["attrs"] = attrsDict
|
||||
|
||||
thread := &starlark.Thread{
|
||||
Name: "matcher",
|
||||
}
|
||||
results, err := m.program.Init(thread, predefined)
|
||||
if err != nil {
|
||||
newError("attr matcher").Base(err).WriteToLog()
|
||||
}
|
||||
satisfied := results["satisfied"]
|
||||
return satisfied != nil && bool(satisfied.Truth())
|
||||
}
|
||||
|
||||
// Apply implements Condition.
|
||||
func (m *AttributeMatcher) Apply(ctx routing.Context) bool {
|
||||
attributes := ctx.GetAttributes()
|
||||
if attributes == nil {
|
||||
return false
|
||||
}
|
||||
return m.Match(attributes)
|
||||
}
|
193
app/router/condition_geoip.go
Normal file
193
app/router/condition_geoip.go
Normal file
|
@ -0,0 +1,193 @@
|
|||
// +build !confonly
|
||||
|
||||
package router
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"sort"
|
||||
|
||||
"github.com/xtls/xray-core/v1/common/net"
|
||||
)
|
||||
|
||||
type ipv6 struct {
|
||||
a uint64
|
||||
b uint64
|
||||
}
|
||||
|
||||
type GeoIPMatcher struct {
|
||||
countryCode string
|
||||
ip4 []uint32
|
||||
prefix4 []uint8
|
||||
ip6 []ipv6
|
||||
prefix6 []uint8
|
||||
}
|
||||
|
||||
func normalize4(ip uint32, prefix uint8) uint32 {
|
||||
return (ip >> (32 - prefix)) << (32 - prefix)
|
||||
}
|
||||
|
||||
func normalize6(ip ipv6, prefix uint8) ipv6 {
|
||||
if prefix <= 64 {
|
||||
ip.a = (ip.a >> (64 - prefix)) << (64 - prefix)
|
||||
ip.b = 0
|
||||
} else {
|
||||
ip.b = (ip.b >> (128 - prefix)) << (128 - prefix)
|
||||
}
|
||||
return ip
|
||||
}
|
||||
|
||||
func (m *GeoIPMatcher) Init(cidrs []*CIDR) error {
|
||||
ip4Count := 0
|
||||
ip6Count := 0
|
||||
|
||||
for _, cidr := range cidrs {
|
||||
ip := cidr.Ip
|
||||
switch len(ip) {
|
||||
case 4:
|
||||
ip4Count++
|
||||
case 16:
|
||||
ip6Count++
|
||||
default:
|
||||
return newError("unexpect ip length: ", len(ip))
|
||||
}
|
||||
}
|
||||
|
||||
cidrList := CIDRList(cidrs)
|
||||
sort.Sort(&cidrList)
|
||||
|
||||
m.ip4 = make([]uint32, 0, ip4Count)
|
||||
m.prefix4 = make([]uint8, 0, ip4Count)
|
||||
m.ip6 = make([]ipv6, 0, ip6Count)
|
||||
m.prefix6 = make([]uint8, 0, ip6Count)
|
||||
|
||||
for _, cidr := range cidrs {
|
||||
ip := cidr.Ip
|
||||
prefix := uint8(cidr.Prefix)
|
||||
switch len(ip) {
|
||||
case 4:
|
||||
m.ip4 = append(m.ip4, normalize4(binary.BigEndian.Uint32(ip), prefix))
|
||||
m.prefix4 = append(m.prefix4, prefix)
|
||||
case 16:
|
||||
ip6 := ipv6{
|
||||
a: binary.BigEndian.Uint64(ip[0:8]),
|
||||
b: binary.BigEndian.Uint64(ip[8:16]),
|
||||
}
|
||||
ip6 = normalize6(ip6, prefix)
|
||||
|
||||
m.ip6 = append(m.ip6, ip6)
|
||||
m.prefix6 = append(m.prefix6, prefix)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *GeoIPMatcher) match4(ip uint32) bool {
|
||||
if len(m.ip4) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
if ip < m.ip4[0] {
|
||||
return false
|
||||
}
|
||||
|
||||
size := uint32(len(m.ip4))
|
||||
l := uint32(0)
|
||||
r := size
|
||||
for l < r {
|
||||
x := ((l + r) >> 1)
|
||||
if ip < m.ip4[x] {
|
||||
r = x
|
||||
continue
|
||||
}
|
||||
|
||||
nip := normalize4(ip, m.prefix4[x])
|
||||
if nip == m.ip4[x] {
|
||||
return true
|
||||
}
|
||||
|
||||
l = x + 1
|
||||
}
|
||||
|
||||
return l > 0 && normalize4(ip, m.prefix4[l-1]) == m.ip4[l-1]
|
||||
}
|
||||
|
||||
func less6(a ipv6, b ipv6) bool {
|
||||
return a.a < b.a || (a.a == b.a && a.b < b.b)
|
||||
}
|
||||
|
||||
func (m *GeoIPMatcher) match6(ip ipv6) bool {
|
||||
if len(m.ip6) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
if less6(ip, m.ip6[0]) {
|
||||
return false
|
||||
}
|
||||
|
||||
size := uint32(len(m.ip6))
|
||||
l := uint32(0)
|
||||
r := size
|
||||
for l < r {
|
||||
x := (l + r) / 2
|
||||
if less6(ip, m.ip6[x]) {
|
||||
r = x
|
||||
continue
|
||||
}
|
||||
|
||||
if normalize6(ip, m.prefix6[x]) == m.ip6[x] {
|
||||
return true
|
||||
}
|
||||
|
||||
l = x + 1
|
||||
}
|
||||
|
||||
return l > 0 && normalize6(ip, m.prefix6[l-1]) == m.ip6[l-1]
|
||||
}
|
||||
|
||||
// Match returns true if the given ip is included by the GeoIP.
|
||||
func (m *GeoIPMatcher) Match(ip net.IP) bool {
|
||||
switch len(ip) {
|
||||
case 4:
|
||||
return m.match4(binary.BigEndian.Uint32(ip))
|
||||
case 16:
|
||||
return m.match6(ipv6{
|
||||
a: binary.BigEndian.Uint64(ip[0:8]),
|
||||
b: binary.BigEndian.Uint64(ip[8:16]),
|
||||
})
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// GeoIPMatcherContainer is a container for GeoIPMatchers. It keeps unique copies of GeoIPMatcher by country code.
|
||||
type GeoIPMatcherContainer struct {
|
||||
matchers []*GeoIPMatcher
|
||||
}
|
||||
|
||||
// Add adds a new GeoIP set into the container.
|
||||
// If the country code of GeoIP is not empty, GeoIPMatcherContainer will try to find an existing one, instead of adding a new one.
|
||||
func (c *GeoIPMatcherContainer) Add(geoip *GeoIP) (*GeoIPMatcher, error) {
|
||||
if len(geoip.CountryCode) > 0 {
|
||||
for _, m := range c.matchers {
|
||||
if m.countryCode == geoip.CountryCode {
|
||||
return m, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m := &GeoIPMatcher{
|
||||
countryCode: geoip.CountryCode,
|
||||
}
|
||||
if err := m.Init(geoip.Cidr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(geoip.CountryCode) > 0 {
|
||||
c.matchers = append(c.matchers, m)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
var (
|
||||
globalGeoIPContainer GeoIPMatcherContainer
|
||||
)
|
195
app/router/condition_geoip_test.go
Normal file
195
app/router/condition_geoip_test.go
Normal file
|
@ -0,0 +1,195 @@
|
|||
package router_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/xtls/xray-core/v1/app/router"
|
||||
"github.com/xtls/xray-core/v1/common"
|
||||
"github.com/xtls/xray-core/v1/common/net"
|
||||
"github.com/xtls/xray-core/v1/common/platform"
|
||||
"github.com/xtls/xray-core/v1/common/platform/filesystem"
|
||||
)
|
||||
|
||||
func init() {
|
||||
wd, err := os.Getwd()
|
||||
common.Must(err)
|
||||
|
||||
if _, err := os.Stat(platform.GetAssetLocation("geoip.dat")); err != nil && os.IsNotExist(err) {
|
||||
common.Must(filesystem.CopyFile(platform.GetAssetLocation("geoip.dat"), filepath.Join(wd, "..", "..", "release", "config", "geoip.dat")))
|
||||
}
|
||||
if _, err := os.Stat(platform.GetAssetLocation("geosite.dat")); err != nil && os.IsNotExist(err) {
|
||||
common.Must(filesystem.CopyFile(platform.GetAssetLocation("geosite.dat"), filepath.Join(wd, "..", "..", "release", "config", "geosite.dat")))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeoIPMatcherContainer(t *testing.T) {
|
||||
container := &router.GeoIPMatcherContainer{}
|
||||
|
||||
m1, err := container.Add(&router.GeoIP{
|
||||
CountryCode: "CN",
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
m2, err := container.Add(&router.GeoIP{
|
||||
CountryCode: "US",
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
m3, err := container.Add(&router.GeoIP{
|
||||
CountryCode: "CN",
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
if m1 != m3 {
|
||||
t.Error("expect same matcher for same geoip, but not")
|
||||
}
|
||||
|
||||
if m1 == m2 {
|
||||
t.Error("expect different matcher for different geoip, but actually same")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeoIPMatcher(t *testing.T) {
|
||||
cidrList := router.CIDRList{
|
||||
{Ip: []byte{0, 0, 0, 0}, Prefix: 8},
|
||||
{Ip: []byte{10, 0, 0, 0}, Prefix: 8},
|
||||
{Ip: []byte{100, 64, 0, 0}, Prefix: 10},
|
||||
{Ip: []byte{127, 0, 0, 0}, Prefix: 8},
|
||||
{Ip: []byte{169, 254, 0, 0}, Prefix: 16},
|
||||
{Ip: []byte{172, 16, 0, 0}, Prefix: 12},
|
||||
{Ip: []byte{192, 0, 0, 0}, Prefix: 24},
|
||||
{Ip: []byte{192, 0, 2, 0}, Prefix: 24},
|
||||
{Ip: []byte{192, 168, 0, 0}, Prefix: 16},
|
||||
{Ip: []byte{192, 18, 0, 0}, Prefix: 15},
|
||||
{Ip: []byte{198, 51, 100, 0}, Prefix: 24},
|
||||
{Ip: []byte{203, 0, 113, 0}, Prefix: 24},
|
||||
{Ip: []byte{8, 8, 8, 8}, Prefix: 32},
|
||||
{Ip: []byte{91, 108, 4, 0}, Prefix: 16},
|
||||
}
|
||||
|
||||
matcher := &router.GeoIPMatcher{}
|
||||
common.Must(matcher.Init(cidrList))
|
||||
|
||||
testCases := []struct {
|
||||
Input string
|
||||
Output bool
|
||||
}{
|
||||
{
|
||||
Input: "192.168.1.1",
|
||||
Output: true,
|
||||
},
|
||||
{
|
||||
Input: "192.0.0.0",
|
||||
Output: true,
|
||||
},
|
||||
{
|
||||
Input: "192.0.1.0",
|
||||
Output: false,
|
||||
}, {
|
||||
Input: "0.1.0.0",
|
||||
Output: true,
|
||||
},
|
||||
{
|
||||
Input: "1.0.0.1",
|
||||
Output: false,
|
||||
},
|
||||
{
|
||||
Input: "8.8.8.7",
|
||||
Output: false,
|
||||
},
|
||||
{
|
||||
Input: "8.8.8.8",
|
||||
Output: true,
|
||||
},
|
||||
{
|
||||
Input: "2001:cdba::3257:9652",
|
||||
Output: false,
|
||||
},
|
||||
{
|
||||
Input: "91.108.255.254",
|
||||
Output: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
ip := net.ParseAddress(testCase.Input).IP()
|
||||
actual := matcher.Match(ip)
|
||||
if actual != testCase.Output {
|
||||
t.Error("expect input", testCase.Input, "to be", testCase.Output, ", but actually", actual)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeoIPMatcher4CN(t *testing.T) {
|
||||
ips, err := loadGeoIP("CN")
|
||||
common.Must(err)
|
||||
|
||||
matcher := &router.GeoIPMatcher{}
|
||||
common.Must(matcher.Init(ips))
|
||||
|
||||
if matcher.Match([]byte{8, 8, 8, 8}) {
|
||||
t.Error("expect CN geoip doesn't contain 8.8.8.8, but actually does")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeoIPMatcher6US(t *testing.T) {
|
||||
ips, err := loadGeoIP("US")
|
||||
common.Must(err)
|
||||
|
||||
matcher := &router.GeoIPMatcher{}
|
||||
common.Must(matcher.Init(ips))
|
||||
|
||||
if !matcher.Match(net.ParseAddress("2001:4860:4860::8888").IP()) {
|
||||
t.Error("expect US geoip contain 2001:4860:4860::8888, but actually not")
|
||||
}
|
||||
}
|
||||
|
||||
func loadGeoIP(country string) ([]*router.CIDR, error) {
|
||||
geoipBytes, err := filesystem.ReadAsset("geoip.dat")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var geoipList router.GeoIPList
|
||||
if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, geoip := range geoipList.Entry {
|
||||
if geoip.CountryCode == country {
|
||||
return geoip.Cidr, nil
|
||||
}
|
||||
}
|
||||
|
||||
panic("country not found: " + country)
|
||||
}
|
||||
|
||||
func BenchmarkGeoIPMatcher4CN(b *testing.B) {
|
||||
ips, err := loadGeoIP("CN")
|
||||
common.Must(err)
|
||||
|
||||
matcher := &router.GeoIPMatcher{}
|
||||
common.Must(matcher.Init(ips))
|
||||
|
||||
b.ResetTimer()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = matcher.Match([]byte{8, 8, 8, 8})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGeoIPMatcher6US(b *testing.B) {
|
||||
ips, err := loadGeoIP("US")
|
||||
common.Must(err)
|
||||
|
||||
matcher := &router.GeoIPMatcher{}
|
||||
common.Must(matcher.Init(ips))
|
||||
|
||||
b.ResetTimer()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = matcher.Match(net.ParseAddress("2001:4860:4860::8888").IP())
|
||||
}
|
||||
}
|
446
app/router/condition_test.go
Normal file
446
app/router/condition_test.go
Normal file
|
@ -0,0 +1,446 @@
|
|||
package router_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/golang/protobuf/proto"
|
||||
|
||||
. "github.com/xtls/xray-core/v1/app/router"
|
||||
"github.com/xtls/xray-core/v1/common"
|
||||
"github.com/xtls/xray-core/v1/common/errors"
|
||||
"github.com/xtls/xray-core/v1/common/net"
|
||||
"github.com/xtls/xray-core/v1/common/platform"
|
||||
"github.com/xtls/xray-core/v1/common/platform/filesystem"
|
||||
"github.com/xtls/xray-core/v1/common/protocol"
|
||||
"github.com/xtls/xray-core/v1/common/protocol/http"
|
||||
"github.com/xtls/xray-core/v1/common/session"
|
||||
"github.com/xtls/xray-core/v1/features/routing"
|
||||
routing_session "github.com/xtls/xray-core/v1/features/routing/session"
|
||||
)
|
||||
|
||||
func init() {
|
||||
wd, err := os.Getwd()
|
||||
common.Must(err)
|
||||
|
||||
if _, err := os.Stat(platform.GetAssetLocation("geoip.dat")); err != nil && os.IsNotExist(err) {
|
||||
common.Must(filesystem.CopyFile(platform.GetAssetLocation("geoip.dat"), filepath.Join(wd, "..", "..", "release", "config", "geoip.dat")))
|
||||
}
|
||||
if _, err := os.Stat(platform.GetAssetLocation("geosite.dat")); err != nil && os.IsNotExist(err) {
|
||||
common.Must(filesystem.CopyFile(platform.GetAssetLocation("geosite.dat"), filepath.Join(wd, "..", "..", "release", "config", "geosite.dat")))
|
||||
}
|
||||
}
|
||||
|
||||
func withBackground() routing.Context {
|
||||
return &routing_session.Context{}
|
||||
}
|
||||
|
||||
func withOutbound(outbound *session.Outbound) routing.Context {
|
||||
return &routing_session.Context{Outbound: outbound}
|
||||
}
|
||||
|
||||
func withInbound(inbound *session.Inbound) routing.Context {
|
||||
return &routing_session.Context{Inbound: inbound}
|
||||
}
|
||||
|
||||
func withContent(content *session.Content) routing.Context {
|
||||
return &routing_session.Context{Content: content}
|
||||
}
|
||||
|
||||
func TestRoutingRule(t *testing.T) {
|
||||
type ruleTest struct {
|
||||
input routing.Context
|
||||
output bool
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
rule *RoutingRule
|
||||
test []ruleTest
|
||||
}{
|
||||
{
|
||||
rule: &RoutingRule{
|
||||
Domain: []*Domain{
|
||||
{
|
||||
Value: "example.com",
|
||||
Type: Domain_Plain,
|
||||
},
|
||||
{
|
||||
Value: "google.com",
|
||||
Type: Domain_Domain,
|
||||
},
|
||||
{
|
||||
Value: "^facebook\\.com$",
|
||||
Type: Domain_Regex,
|
||||
},
|
||||
},
|
||||
},
|
||||
test: []ruleTest{
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.DomainAddress("example.com"), 80)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.DomainAddress("www.example.com.www"), 80)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.DomainAddress("example.co"), 80)}),
|
||||
output: false,
|
||||
},
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.DomainAddress("www.google.com"), 80)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.DomainAddress("facebook.com"), 80)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.DomainAddress("www.facebook.com"), 80)}),
|
||||
output: false,
|
||||
},
|
||||
{
|
||||
input: withBackground(),
|
||||
output: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rule: &RoutingRule{
|
||||
Cidr: []*CIDR{
|
||||
{
|
||||
Ip: []byte{8, 8, 8, 8},
|
||||
Prefix: 32,
|
||||
},
|
||||
{
|
||||
Ip: []byte{8, 8, 8, 8},
|
||||
Prefix: 32,
|
||||
},
|
||||
{
|
||||
Ip: net.ParseAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334").IP(),
|
||||
Prefix: 128,
|
||||
},
|
||||
},
|
||||
},
|
||||
test: []ruleTest{
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("8.8.8.8"), 80)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("8.8.4.4"), 80)}),
|
||||
output: false,
|
||||
},
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334"), 80)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withBackground(),
|
||||
output: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rule: &RoutingRule{
|
||||
Geoip: []*GeoIP{
|
||||
{
|
||||
Cidr: []*CIDR{
|
||||
{
|
||||
Ip: []byte{8, 8, 8, 8},
|
||||
Prefix: 32,
|
||||
},
|
||||
{
|
||||
Ip: []byte{8, 8, 8, 8},
|
||||
Prefix: 32,
|
||||
},
|
||||
{
|
||||
Ip: net.ParseAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334").IP(),
|
||||
Prefix: 128,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
test: []ruleTest{
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("8.8.8.8"), 80)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("8.8.4.4"), 80)}),
|
||||
output: false,
|
||||
},
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334"), 80)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withBackground(),
|
||||
output: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rule: &RoutingRule{
|
||||
SourceCidr: []*CIDR{
|
||||
{
|
||||
Ip: []byte{192, 168, 0, 0},
|
||||
Prefix: 16,
|
||||
},
|
||||
},
|
||||
},
|
||||
test: []ruleTest{
|
||||
{
|
||||
input: withInbound(&session.Inbound{Source: net.TCPDestination(net.ParseAddress("192.168.0.1"), 80)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withInbound(&session.Inbound{Source: net.TCPDestination(net.ParseAddress("10.0.0.1"), 80)}),
|
||||
output: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rule: &RoutingRule{
|
||||
UserEmail: []string{
|
||||
"admin@example.com",
|
||||
},
|
||||
},
|
||||
test: []ruleTest{
|
||||
{
|
||||
input: withInbound(&session.Inbound{User: &protocol.MemoryUser{Email: "admin@example.com"}}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withInbound(&session.Inbound{User: &protocol.MemoryUser{Email: "love@example.com"}}),
|
||||
output: false,
|
||||
},
|
||||
{
|
||||
input: withBackground(),
|
||||
output: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rule: &RoutingRule{
|
||||
Protocol: []string{"http"},
|
||||
},
|
||||
test: []ruleTest{
|
||||
{
|
||||
input: withContent(&session.Content{Protocol: (&http.SniffHeader{}).Protocol()}),
|
||||
output: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rule: &RoutingRule{
|
||||
InboundTag: []string{"test", "test1"},
|
||||
},
|
||||
test: []ruleTest{
|
||||
{
|
||||
input: withInbound(&session.Inbound{Tag: "test"}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withInbound(&session.Inbound{Tag: "test2"}),
|
||||
output: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rule: &RoutingRule{
|
||||
PortList: &net.PortList{
|
||||
Range: []*net.PortRange{
|
||||
{From: 443, To: 443},
|
||||
{From: 1000, To: 1100},
|
||||
},
|
||||
},
|
||||
},
|
||||
test: []ruleTest{
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.LocalHostIP, 443)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.LocalHostIP, 1100)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.LocalHostIP, 1005)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.LocalHostIP, 53)}),
|
||||
output: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rule: &RoutingRule{
|
||||
SourcePortList: &net.PortList{
|
||||
Range: []*net.PortRange{
|
||||
{From: 123, To: 123},
|
||||
{From: 9993, To: 9999},
|
||||
},
|
||||
},
|
||||
},
|
||||
test: []ruleTest{
|
||||
{
|
||||
input: withInbound(&session.Inbound{Source: net.UDPDestination(net.LocalHostIP, 123)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withInbound(&session.Inbound{Source: net.UDPDestination(net.LocalHostIP, 9999)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withInbound(&session.Inbound{Source: net.UDPDestination(net.LocalHostIP, 9994)}),
|
||||
output: true,
|
||||
},
|
||||
{
|
||||
input: withInbound(&session.Inbound{Source: net.UDPDestination(net.LocalHostIP, 53)}),
|
||||
output: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rule: &RoutingRule{
|
||||
Protocol: []string{"http"},
|
||||
Attributes: "attrs[':path'].startswith('/test')",
|
||||
},
|
||||
test: []ruleTest{
|
||||
{
|
||||
input: withContent(&session.Content{Protocol: "http/1.1", Attributes: map[string]string{":path": "/test/1"}}),
|
||||
output: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range cases {
|
||||
cond, err := test.rule.BuildCondition()
|
||||
common.Must(err)
|
||||
|
||||
for _, subtest := range test.test {
|
||||
actual := cond.Apply(subtest.input)
|
||||
if actual != subtest.output {
|
||||
t.Error("test case failed: ", subtest.input, " expected ", subtest.output, " but got ", actual)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func loadGeoSite(country string) ([]*Domain, error) {
|
||||
geositeBytes, err := filesystem.ReadAsset("geosite.dat")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var geositeList GeoSiteList
|
||||
if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, site := range geositeList.Entry {
|
||||
if site.CountryCode == country {
|
||||
return site.Domain, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, errors.New("country not found: " + country)
|
||||
}
|
||||
|
||||
func TestChinaSites(t *testing.T) {
|
||||
domains, err := loadGeoSite("CN")
|
||||
common.Must(err)
|
||||
|
||||
matcher, err := NewDomainMatcher(domains)
|
||||
common.Must(err)
|
||||
|
||||
type TestCase struct {
|
||||
Domain string
|
||||
Output bool
|
||||
}
|
||||
testCases := []TestCase{
|
||||
{
|
||||
Domain: "163.com",
|
||||
Output: true,
|
||||
},
|
||||
{
|
||||
Domain: "163.com",
|
||||
Output: true,
|
||||
},
|
||||
{
|
||||
Domain: "164.com",
|
||||
Output: false,
|
||||
},
|
||||
{
|
||||
Domain: "164.com",
|
||||
Output: false,
|
||||
},
|
||||
}
|
||||
|
||||
for i := 0; i < 1024; i++ {
|
||||
testCases = append(testCases, TestCase{Domain: strconv.Itoa(i) + ".not-exists.com", Output: false})
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
r := matcher.ApplyDomain(testCase.Domain)
|
||||
if r != testCase.Output {
|
||||
t.Error("expected output ", testCase.Output, " for domain ", testCase.Domain, " but got ", r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMultiGeoIPMatcher(b *testing.B) {
|
||||
var geoips []*GeoIP
|
||||
|
||||
{
|
||||
ips, err := loadGeoIP("CN")
|
||||
common.Must(err)
|
||||
geoips = append(geoips, &GeoIP{
|
||||
CountryCode: "CN",
|
||||
Cidr: ips,
|
||||
})
|
||||
}
|
||||
|
||||
{
|
||||
ips, err := loadGeoIP("JP")
|
||||
common.Must(err)
|
||||
geoips = append(geoips, &GeoIP{
|
||||
CountryCode: "JP",
|
||||
Cidr: ips,
|
||||
})
|
||||
}
|
||||
|
||||
{
|
||||
ips, err := loadGeoIP("CA")
|
||||
common.Must(err)
|
||||
geoips = append(geoips, &GeoIP{
|
||||
CountryCode: "CA",
|
||||
Cidr: ips,
|
||||
})
|
||||
}
|
||||
|
||||
{
|
||||
ips, err := loadGeoIP("US")
|
||||
common.Must(err)
|
||||
geoips = append(geoips, &GeoIP{
|
||||
CountryCode: "US",
|
||||
Cidr: ips,
|
||||
})
|
||||
}
|
||||
|
||||
matcher, err := NewMultiGeoIPMatcher(geoips, false)
|
||||
common.Must(err)
|
||||
|
||||
ctx := withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("8.8.8.8"), 80)})
|
||||
|
||||
b.ResetTimer()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = matcher.Apply(ctx)
|
||||
}
|
||||
}
|
156
app/router/config.go
Normal file
156
app/router/config.go
Normal file
|
@ -0,0 +1,156 @@
|
|||
// +build !confonly
|
||||
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/v1/common/net"
|
||||
"github.com/xtls/xray-core/v1/features/outbound"
|
||||
"github.com/xtls/xray-core/v1/features/routing"
|
||||
)
|
||||
|
||||
// CIDRList is an alias of []*CIDR to provide sort.Interface.
|
||||
type CIDRList []*CIDR
|
||||
|
||||
// Len implements sort.Interface.
|
||||
func (l *CIDRList) Len() int {
|
||||
return len(*l)
|
||||
}
|
||||
|
||||
// Less implements sort.Interface.
|
||||
func (l *CIDRList) Less(i int, j int) bool {
|
||||
ci := (*l)[i]
|
||||
cj := (*l)[j]
|
||||
|
||||
if len(ci.Ip) < len(cj.Ip) {
|
||||
return true
|
||||
}
|
||||
|
||||
if len(ci.Ip) > len(cj.Ip) {
|
||||
return false
|
||||
}
|
||||
|
||||
for k := 0; k < len(ci.Ip); k++ {
|
||||
if ci.Ip[k] < cj.Ip[k] {
|
||||
return true
|
||||
}
|
||||
|
||||
if ci.Ip[k] > cj.Ip[k] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return ci.Prefix < cj.Prefix
|
||||
}
|
||||
|
||||
// Swap implements sort.Interface.
|
||||
func (l *CIDRList) Swap(i int, j int) {
|
||||
(*l)[i], (*l)[j] = (*l)[j], (*l)[i]
|
||||
}
|
||||
|
||||
type Rule struct {
|
||||
Tag string
|
||||
Balancer *Balancer
|
||||
Condition Condition
|
||||
}
|
||||
|
||||
func (r *Rule) GetTag() (string, error) {
|
||||
if r.Balancer != nil {
|
||||
return r.Balancer.PickOutbound()
|
||||
}
|
||||
return r.Tag, nil
|
||||
}
|
||||
|
||||
// Apply checks rule matching of current routing context.
|
||||
func (r *Rule) Apply(ctx routing.Context) bool {
|
||||
return r.Condition.Apply(ctx)
|
||||
}
|
||||
|
||||
func (rr *RoutingRule) BuildCondition() (Condition, error) {
|
||||
conds := NewConditionChan()
|
||||
|
||||
if len(rr.Domain) > 0 {
|
||||
matcher, err := NewDomainMatcher(rr.Domain)
|
||||
if err != nil {
|
||||
return nil, newError("failed to build domain condition").Base(err)
|
||||
}
|
||||
conds.Add(matcher)
|
||||
}
|
||||
|
||||
if len(rr.UserEmail) > 0 {
|
||||
conds.Add(NewUserMatcher(rr.UserEmail))
|
||||
}
|
||||
|
||||
if len(rr.InboundTag) > 0 {
|
||||
conds.Add(NewInboundTagMatcher(rr.InboundTag))
|
||||
}
|
||||
|
||||
if rr.PortList != nil {
|
||||
conds.Add(NewPortMatcher(rr.PortList, false))
|
||||
} else if rr.PortRange != nil {
|
||||
conds.Add(NewPortMatcher(&net.PortList{Range: []*net.PortRange{rr.PortRange}}, false))
|
||||
}
|
||||
|
||||
if rr.SourcePortList != nil {
|
||||
conds.Add(NewPortMatcher(rr.SourcePortList, true))
|
||||
}
|
||||
|
||||
if len(rr.Networks) > 0 {
|
||||
conds.Add(NewNetworkMatcher(rr.Networks))
|
||||
} else if rr.NetworkList != nil {
|
||||
conds.Add(NewNetworkMatcher(rr.NetworkList.Network))
|
||||
}
|
||||
|
||||
if len(rr.Geoip) > 0 {
|
||||
cond, err := NewMultiGeoIPMatcher(rr.Geoip, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conds.Add(cond)
|
||||
} else if len(rr.Cidr) > 0 {
|
||||
cond, err := NewMultiGeoIPMatcher([]*GeoIP{{Cidr: rr.Cidr}}, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conds.Add(cond)
|
||||
}
|
||||
|
||||
if len(rr.SourceGeoip) > 0 {
|
||||
cond, err := NewMultiGeoIPMatcher(rr.SourceGeoip, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conds.Add(cond)
|
||||
} else if len(rr.SourceCidr) > 0 {
|
||||
cond, err := NewMultiGeoIPMatcher([]*GeoIP{{Cidr: rr.SourceCidr}}, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conds.Add(cond)
|
||||
}
|
||||
|
||||
if len(rr.Protocol) > 0 {
|
||||
conds.Add(NewProtocolMatcher(rr.Protocol))
|
||||
}
|
||||
|
||||
if len(rr.Attributes) > 0 {
|
||||
cond, err := NewAttributeMatcher(rr.Attributes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conds.Add(cond)
|
||||
}
|
||||
|
||||
if conds.Len() == 0 {
|
||||
return nil, newError("this rule has no effective fields").AtWarning()
|
||||
}
|
||||
|
||||
return conds, nil
|
||||
}
|
||||
|
||||
func (br *BalancingRule) Build(ohm outbound.Manager) (*Balancer, error) {
|
||||
return &Balancer{
|
||||
selectors: br.OutboundSelector,
|
||||
strategy: &RandomStrategy{},
|
||||
ohm: ohm,
|
||||
}, nil
|
||||
}
|
1242
app/router/config.pb.go
Normal file
1242
app/router/config.pb.go
Normal file
File diff suppressed because it is too large
Load diff
146
app/router/config.proto
Normal file
146
app/router/config.proto
Normal file
|
@ -0,0 +1,146 @@
|
|||
syntax = "proto3";
|
||||
|
||||
package xray.app.router;
|
||||
option csharp_namespace = "Xray.App.Router";
|
||||
option go_package = "github.com/xtls/xray-core/v1/app/router";
|
||||
option java_package = "com.xray.app.router";
|
||||
option java_multiple_files = true;
|
||||
|
||||
import "common/net/port.proto";
|
||||
import "common/net/network.proto";
|
||||
|
||||
// Domain for routing decision.
|
||||
message Domain {
|
||||
// Type of domain value.
|
||||
enum Type {
|
||||
// The value is used as is.
|
||||
Plain = 0;
|
||||
// The value is used as a regular expression.
|
||||
Regex = 1;
|
||||
// The value is a root domain.
|
||||
Domain = 2;
|
||||
// The value is a domain.
|
||||
Full = 3;
|
||||
}
|
||||
|
||||
// Domain matching type.
|
||||
Type type = 1;
|
||||
|
||||
// Domain value.
|
||||
string value = 2;
|
||||
|
||||
message Attribute {
|
||||
string key = 1;
|
||||
|
||||
oneof typed_value {
|
||||
bool bool_value = 2;
|
||||
int64 int_value = 3;
|
||||
}
|
||||
}
|
||||
|
||||
// Attributes of this domain. May be used for filtering.
|
||||
repeated Attribute attribute = 3;
|
||||
}
|
||||
|
||||
// IP for routing decision, in CIDR form.
|
||||
message CIDR {
|
||||
// IP address, should be either 4 or 16 bytes.
|
||||
bytes ip = 1;
|
||||
|
||||
// Number of leading ones in the network mask.
|
||||
uint32 prefix = 2;
|
||||
}
|
||||
|
||||
message GeoIP {
|
||||
string country_code = 1;
|
||||
repeated CIDR cidr = 2;
|
||||
}
|
||||
|
||||
message GeoIPList {
|
||||
repeated GeoIP entry = 1;
|
||||
}
|
||||
|
||||
message GeoSite {
|
||||
string country_code = 1;
|
||||
repeated Domain domain = 2;
|
||||
}
|
||||
|
||||
message GeoSiteList {
|
||||
repeated GeoSite entry = 1;
|
||||
}
|
||||
|
||||
message RoutingRule {
|
||||
oneof target_tag {
|
||||
// Tag of outbound that this rule is pointing to.
|
||||
string tag = 1;
|
||||
|
||||
// Tag of routing balancer.
|
||||
string balancing_tag = 12;
|
||||
}
|
||||
|
||||
// List of domains for target domain matching.
|
||||
repeated Domain domain = 2;
|
||||
|
||||
// List of CIDRs for target IP address matching.
|
||||
// Deprecated. Use geoip below.
|
||||
repeated CIDR cidr = 3 [deprecated = true];
|
||||
|
||||
// List of GeoIPs for target IP address matching. If this entry exists, the
|
||||
// cidr above will have no effect. GeoIP fields with the same country code are
|
||||
// supposed to contain exactly same content. They will be merged during
|
||||
// runtime. For customized GeoIPs, please leave country code empty.
|
||||
repeated GeoIP geoip = 10;
|
||||
|
||||
// A range of port [from, to]. If the destination port is in this range, this
|
||||
// rule takes effect. Deprecated. Use port_list.
|
||||
xray.common.net.PortRange port_range = 4 [deprecated = true];
|
||||
|
||||
// List of ports.
|
||||
xray.common.net.PortList port_list = 14;
|
||||
|
||||
// List of networks. Deprecated. Use networks.
|
||||
xray.common.net.NetworkList network_list = 5 [deprecated = true];
|
||||
|
||||
// List of networks for matching.
|
||||
repeated xray.common.net.Network networks = 13;
|
||||
|
||||
// List of CIDRs for source IP address matching.
|
||||
repeated CIDR source_cidr = 6 [deprecated = true];
|
||||
|
||||
// List of GeoIPs for source IP address matching. If this entry exists, the
|
||||
// source_cidr above will have no effect.
|
||||
repeated GeoIP source_geoip = 11;
|
||||
|
||||
// List of ports for source port matching.
|
||||
xray.common.net.PortList source_port_list = 16;
|
||||
|
||||
repeated string user_email = 7;
|
||||
repeated string inbound_tag = 8;
|
||||
repeated string protocol = 9;
|
||||
|
||||
string attributes = 15;
|
||||
}
|
||||
|
||||
message BalancingRule {
|
||||
string tag = 1;
|
||||
repeated string outbound_selector = 2;
|
||||
}
|
||||
|
||||
message Config {
|
||||
enum DomainStrategy {
|
||||
// Use domain as is.
|
||||
AsIs = 0;
|
||||
|
||||
// Always resolve IP for domains.
|
||||
UseIp = 1;
|
||||
|
||||
// Resolve to IP if the domain doesn't match any rules.
|
||||
IpIfNonMatch = 2;
|
||||
|
||||
// Resolve to IP if any rule requires IP matching.
|
||||
IpOnDemand = 3;
|
||||
}
|
||||
DomainStrategy domain_strategy = 1;
|
||||
repeated RoutingRule rule = 2;
|
||||
repeated BalancingRule balancing_rule = 3;
|
||||
}
|
9
app/router/errors.generated.go
Normal file
9
app/router/errors.generated.go
Normal file
|
@ -0,0 +1,9 @@
|
|||
package router
|
||||
|
||||
import "github.com/xtls/xray-core/v1/common/errors"
|
||||
|
||||
type errPathObjHolder struct{}
|
||||
|
||||
func newError(values ...interface{}) *errors.Error {
|
||||
return errors.New(values...).WithPathObj(errPathObjHolder{})
|
||||
}
|
146
app/router/router.go
Normal file
146
app/router/router.go
Normal file
|
@ -0,0 +1,146 @@
|
|||
// +build !confonly
|
||||
|
||||
package router
|
||||
|
||||
//go:generate go run github.com/xtls/xray-core/v1/common/errors/errorgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/xtls/xray-core/v1/common"
|
||||
"github.com/xtls/xray-core/v1/core"
|
||||
"github.com/xtls/xray-core/v1/features/dns"
|
||||
"github.com/xtls/xray-core/v1/features/outbound"
|
||||
"github.com/xtls/xray-core/v1/features/routing"
|
||||
routing_dns "github.com/xtls/xray-core/v1/features/routing/dns"
|
||||
)
|
||||
|
||||
// Router is an implementation of routing.Router.
|
||||
type Router struct {
|
||||
domainStrategy Config_DomainStrategy
|
||||
rules []*Rule
|
||||
balancers map[string]*Balancer
|
||||
dns dns.Client
|
||||
}
|
||||
|
||||
// Route is an implementation of routing.Route.
|
||||
type Route struct {
|
||||
routing.Context
|
||||
outboundGroupTags []string
|
||||
outboundTag string
|
||||
}
|
||||
|
||||
// Init initializes the Router.
|
||||
func (r *Router) Init(config *Config, d dns.Client, ohm outbound.Manager) error {
|
||||
r.domainStrategy = config.DomainStrategy
|
||||
r.dns = d
|
||||
|
||||
r.balancers = make(map[string]*Balancer, len(config.BalancingRule))
|
||||
for _, rule := range config.BalancingRule {
|
||||
balancer, err := rule.Build(ohm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.balancers[rule.Tag] = balancer
|
||||
}
|
||||
|
||||
r.rules = make([]*Rule, 0, len(config.Rule))
|
||||
for _, rule := range config.Rule {
|
||||
cond, err := rule.BuildCondition()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rr := &Rule{
|
||||
Condition: cond,
|
||||
Tag: rule.GetTag(),
|
||||
}
|
||||
btag := rule.GetBalancingTag()
|
||||
if len(btag) > 0 {
|
||||
brule, found := r.balancers[btag]
|
||||
if !found {
|
||||
return newError("balancer ", btag, " not found")
|
||||
}
|
||||
rr.Balancer = brule
|
||||
}
|
||||
r.rules = append(r.rules, rr)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// PickRoute implements routing.Router.
|
||||
func (r *Router) PickRoute(ctx routing.Context) (routing.Route, error) {
|
||||
rule, ctx, err := r.pickRouteInternal(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tag, err := rule.GetTag()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Route{Context: ctx, outboundTag: tag}, nil
|
||||
}
|
||||
|
||||
func (r *Router) pickRouteInternal(ctx routing.Context) (*Rule, routing.Context, error) {
|
||||
if r.domainStrategy == Config_IpOnDemand {
|
||||
ctx = routing_dns.ContextWithDNSClient(ctx, r.dns)
|
||||
}
|
||||
|
||||
for _, rule := range r.rules {
|
||||
if rule.Apply(ctx) {
|
||||
return rule, ctx, nil
|
||||
}
|
||||
}
|
||||
|
||||
if r.domainStrategy != Config_IpIfNonMatch || len(ctx.GetTargetDomain()) == 0 {
|
||||
return nil, ctx, common.ErrNoClue
|
||||
}
|
||||
|
||||
ctx = routing_dns.ContextWithDNSClient(ctx, r.dns)
|
||||
|
||||
// Try applying rules again if we have IPs.
|
||||
for _, rule := range r.rules {
|
||||
if rule.Apply(ctx) {
|
||||
return rule, ctx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, ctx, common.ErrNoClue
|
||||
}
|
||||
|
||||
// Start implements common.Runnable.
|
||||
func (*Router) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close implements common.Closable.
|
||||
func (*Router) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Type implement common.HasType.
|
||||
func (*Router) Type() interface{} {
|
||||
return routing.RouterType()
|
||||
}
|
||||
|
||||
// GetOutboundGroupTags implements routing.Route.
|
||||
func (r *Route) GetOutboundGroupTags() []string {
|
||||
return r.outboundGroupTags
|
||||
}
|
||||
|
||||
// GetOutboundTag implements routing.Route.
|
||||
func (r *Route) GetOutboundTag() string {
|
||||
return r.outboundTag
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
|
||||
r := new(Router)
|
||||
if err := core.RequireFeatures(ctx, func(d dns.Client, ohm outbound.Manager) error {
|
||||
return r.Init(config.(*Config), d, ohm)
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}))
|
||||
}
|
198
app/router/router_test.go
Normal file
198
app/router/router_test.go
Normal file
|
@ -0,0 +1,198 @@
|
|||
package router_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/golang/mock/gomock"
|
||||
. "github.com/xtls/xray-core/v1/app/router"
|
||||
"github.com/xtls/xray-core/v1/common"
|
||||
"github.com/xtls/xray-core/v1/common/net"
|
||||
"github.com/xtls/xray-core/v1/common/session"
|
||||
"github.com/xtls/xray-core/v1/features/outbound"
|
||||
routing_session "github.com/xtls/xray-core/v1/features/routing/session"
|
||||
"github.com/xtls/xray-core/v1/testing/mocks"
|
||||
)
|
||||
|
||||
type mockOutboundManager struct {
|
||||
outbound.Manager
|
||||
outbound.HandlerSelector
|
||||
}
|
||||
|
||||
func TestSimpleRouter(t *testing.T) {
|
||||
config := &Config{
|
||||
Rule: []*RoutingRule{
|
||||
{
|
||||
TargetTag: &RoutingRule_Tag{
|
||||
Tag: "test",
|
||||
},
|
||||
Networks: []net.Network{net.Network_TCP},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
mockCtl := gomock.NewController(t)
|
||||
defer mockCtl.Finish()
|
||||
|
||||
mockDNS := mocks.NewDNSClient(mockCtl)
|
||||
mockOhm := mocks.NewOutboundManager(mockCtl)
|
||||
mockHs := mocks.NewOutboundHandlerSelector(mockCtl)
|
||||
|
||||
r := new(Router)
|
||||
common.Must(r.Init(config, mockDNS, &mockOutboundManager{
|
||||
Manager: mockOhm,
|
||||
HandlerSelector: mockHs,
|
||||
}))
|
||||
|
||||
ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.DomainAddress("example.com"), 80)})
|
||||
route, err := r.PickRoute(routing_session.AsRoutingContext(ctx))
|
||||
common.Must(err)
|
||||
if tag := route.GetOutboundTag(); tag != "test" {
|
||||
t.Error("expect tag 'test', bug actually ", tag)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimpleBalancer(t *testing.T) {
|
||||
config := &Config{
|
||||
Rule: []*RoutingRule{
|
||||
{
|
||||
TargetTag: &RoutingRule_BalancingTag{
|
||||
BalancingTag: "balance",
|
||||
},
|
||||
Networks: []net.Network{net.Network_TCP},
|
||||
},
|
||||
},
|
||||
BalancingRule: []*BalancingRule{
|
||||
{
|
||||
Tag: "balance",
|
||||
OutboundSelector: []string{"test-"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
mockCtl := gomock.NewController(t)
|
||||
defer mockCtl.Finish()
|
||||
|
||||
mockDNS := mocks.NewDNSClient(mockCtl)
|
||||
mockOhm := mocks.NewOutboundManager(mockCtl)
|
||||
mockHs := mocks.NewOutboundHandlerSelector(mockCtl)
|
||||
|
||||
mockHs.EXPECT().Select(gomock.Eq([]string{"test-"})).Return([]string{"test"})
|
||||
|
||||
r := new(Router)
|
||||
common.Must(r.Init(config, mockDNS, &mockOutboundManager{
|
||||
Manager: mockOhm,
|
||||
HandlerSelector: mockHs,
|
||||
}))
|
||||
|
||||
ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.DomainAddress("example.com"), 80)})
|
||||
route, err := r.PickRoute(routing_session.AsRoutingContext(ctx))
|
||||
common.Must(err)
|
||||
if tag := route.GetOutboundTag(); tag != "test" {
|
||||
t.Error("expect tag 'test', bug actually ", tag)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPOnDemand(t *testing.T) {
|
||||
config := &Config{
|
||||
DomainStrategy: Config_IpOnDemand,
|
||||
Rule: []*RoutingRule{
|
||||
{
|
||||
TargetTag: &RoutingRule_Tag{
|
||||
Tag: "test",
|
||||
},
|
||||
Cidr: []*CIDR{
|
||||
{
|
||||
Ip: []byte{192, 168, 0, 0},
|
||||
Prefix: 16,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
mockCtl := gomock.NewController(t)
|
||||
defer mockCtl.Finish()
|
||||
|
||||
mockDNS := mocks.NewDNSClient(mockCtl)
|
||||
mockDNS.EXPECT().LookupIP(gomock.Eq("example.com")).Return([]net.IP{{192, 168, 0, 1}}, nil).AnyTimes()
|
||||
|
||||
r := new(Router)
|
||||
common.Must(r.Init(config, mockDNS, nil))
|
||||
|
||||
ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.DomainAddress("example.com"), 80)})
|
||||
route, err := r.PickRoute(routing_session.AsRoutingContext(ctx))
|
||||
common.Must(err)
|
||||
if tag := route.GetOutboundTag(); tag != "test" {
|
||||
t.Error("expect tag 'test', bug actually ", tag)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPIfNonMatchDomain(t *testing.T) {
|
||||
config := &Config{
|
||||
DomainStrategy: Config_IpIfNonMatch,
|
||||
Rule: []*RoutingRule{
|
||||
{
|
||||
TargetTag: &RoutingRule_Tag{
|
||||
Tag: "test",
|
||||
},
|
||||
Cidr: []*CIDR{
|
||||
{
|
||||
Ip: []byte{192, 168, 0, 0},
|
||||
Prefix: 16,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
mockCtl := gomock.NewController(t)
|
||||
defer mockCtl.Finish()
|
||||
|
||||
mockDNS := mocks.NewDNSClient(mockCtl)
|
||||
mockDNS.EXPECT().LookupIP(gomock.Eq("example.com")).Return([]net.IP{{192, 168, 0, 1}}, nil).AnyTimes()
|
||||
|
||||
r := new(Router)
|
||||
common.Must(r.Init(config, mockDNS, nil))
|
||||
|
||||
ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.DomainAddress("example.com"), 80)})
|
||||
route, err := r.PickRoute(routing_session.AsRoutingContext(ctx))
|
||||
common.Must(err)
|
||||
if tag := route.GetOutboundTag(); tag != "test" {
|
||||
t.Error("expect tag 'test', bug actually ", tag)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPIfNonMatchIP(t *testing.T) {
|
||||
config := &Config{
|
||||
DomainStrategy: Config_IpIfNonMatch,
|
||||
Rule: []*RoutingRule{
|
||||
{
|
||||
TargetTag: &RoutingRule_Tag{
|
||||
Tag: "test",
|
||||
},
|
||||
Cidr: []*CIDR{
|
||||
{
|
||||
Ip: []byte{127, 0, 0, 0},
|
||||
Prefix: 8,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
mockCtl := gomock.NewController(t)
|
||||
defer mockCtl.Finish()
|
||||
|
||||
mockDNS := mocks.NewDNSClient(mockCtl)
|
||||
|
||||
r := new(Router)
|
||||
common.Must(r.Init(config, mockDNS, nil))
|
||||
|
||||
ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.LocalHostIP, 80)})
|
||||
route, err := r.PickRoute(routing_session.AsRoutingContext(ctx))
|
||||
common.Must(err)
|
||||
if tag := route.GetOutboundTag(); tag != "test" {
|
||||
t.Error("expect tag 'test', bug actually ", tag)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue