github.com/xmplusdev/xray-core@v1.8.10/app/proxyman/outbound/handler.go (about)

     1  package outbound
     2  
     3  import (
     4  	"context"
     5  	"crypto/rand"
     6  	"errors"
     7  	"github.com/xmplusdev/xray-core/app/proxyman"
     8  	"github.com/xmplusdev/xray-core/common"
     9  	"github.com/xmplusdev/xray-core/common/buf"
    10  	"github.com/xmplusdev/xray-core/common/mux"
    11  	"github.com/xmplusdev/xray-core/common/net"
    12  	"github.com/xmplusdev/xray-core/common/net/cnc"
    13  	"github.com/xmplusdev/xray-core/common/session"
    14  	"github.com/xmplusdev/xray-core/core"
    15  	"github.com/xmplusdev/xray-core/features/outbound"
    16  	"github.com/xmplusdev/xray-core/features/policy"
    17  	"github.com/xmplusdev/xray-core/features/stats"
    18  	"github.com/xmplusdev/xray-core/proxy"
    19  	"github.com/xmplusdev/xray-core/transport"
    20  	"github.com/xmplusdev/xray-core/transport/internet"
    21  	"github.com/xmplusdev/xray-core/transport/internet/stat"
    22  	"github.com/xmplusdev/xray-core/transport/internet/tls"
    23  	"github.com/xmplusdev/xray-core/transport/pipe"
    24  	"io"
    25  	"math/big"
    26  	gonet "net"
    27  	"os"
    28  )
    29  
    30  func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter) {
    31  	var uplinkCounter stats.Counter
    32  	var downlinkCounter stats.Counter
    33  
    34  	policy := v.GetFeature(policy.ManagerType()).(policy.Manager)
    35  	if len(tag) > 0 && policy.ForSystem().Stats.OutboundUplink {
    36  		statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
    37  		name := "outbound>>>" + tag + ">>>traffic>>>uplink"
    38  		c, _ := stats.GetOrRegisterCounter(statsManager, name)
    39  		if c != nil {
    40  			uplinkCounter = c
    41  		}
    42  	}
    43  	if len(tag) > 0 && policy.ForSystem().Stats.OutboundDownlink {
    44  		statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
    45  		name := "outbound>>>" + tag + ">>>traffic>>>downlink"
    46  		c, _ := stats.GetOrRegisterCounter(statsManager, name)
    47  		if c != nil {
    48  			downlinkCounter = c
    49  		}
    50  	}
    51  
    52  	return uplinkCounter, downlinkCounter
    53  }
    54  
    55  // Handler is an implements of outbound.Handler.
    56  type Handler struct {
    57  	tag             string
    58  	senderSettings  *proxyman.SenderConfig
    59  	streamSettings  *internet.MemoryStreamConfig
    60  	proxy           proxy.Outbound
    61  	outboundManager outbound.Manager
    62  	mux             *mux.ClientManager
    63  	xudp            *mux.ClientManager
    64  	udp443          string
    65  	uplinkCounter   stats.Counter
    66  	downlinkCounter stats.Counter
    67  }
    68  
    69  // NewHandler creates a new Handler based on the given configuration.
    70  func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbound.Handler, error) {
    71  	v := core.MustFromContext(ctx)
    72  	uplinkCounter, downlinkCounter := getStatCounter(v, config.Tag)
    73  	h := &Handler{
    74  		tag:             config.Tag,
    75  		outboundManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager),
    76  		uplinkCounter:   uplinkCounter,
    77  		downlinkCounter: downlinkCounter,
    78  	}
    79  
    80  	if config.SenderSettings != nil {
    81  		senderSettings, err := config.SenderSettings.GetInstance()
    82  		if err != nil {
    83  			return nil, err
    84  		}
    85  		switch s := senderSettings.(type) {
    86  		case *proxyman.SenderConfig:
    87  			h.senderSettings = s
    88  			mss, err := internet.ToMemoryStreamConfig(s.StreamSettings)
    89  			if err != nil {
    90  				return nil, newError("failed to parse stream settings").Base(err).AtWarning()
    91  			}
    92  			h.streamSettings = mss
    93  		default:
    94  			return nil, newError("settings is not SenderConfig")
    95  		}
    96  	}
    97  
    98  	proxyConfig, err := config.ProxySettings.GetInstance()
    99  	if err != nil {
   100  		return nil, err
   101  	}
   102  
   103  	rawProxyHandler, err := common.CreateObject(ctx, proxyConfig)
   104  	if err != nil {
   105  		return nil, err
   106  	}
   107  
   108  	proxyHandler, ok := rawProxyHandler.(proxy.Outbound)
   109  	if !ok {
   110  		return nil, newError("not an outbound handler")
   111  	}
   112  
   113  	if h.senderSettings != nil && h.senderSettings.MultiplexSettings != nil {
   114  		if config := h.senderSettings.MultiplexSettings; config.Enabled {
   115  			if config.Concurrency < 0 {
   116  				h.mux = &mux.ClientManager{Enabled: false}
   117  			}
   118  			if config.Concurrency == 0 {
   119  				config.Concurrency = 8 // same as before
   120  			}
   121  			if config.Concurrency > 0 {
   122  				h.mux = &mux.ClientManager{
   123  					Enabled: true,
   124  					Picker: &mux.IncrementalWorkerPicker{
   125  						Factory: &mux.DialingWorkerFactory{
   126  							Proxy:  proxyHandler,
   127  							Dialer: h,
   128  							Strategy: mux.ClientStrategy{
   129  								MaxConcurrency: uint32(config.Concurrency),
   130  								MaxConnection:  128,
   131  							},
   132  						},
   133  					},
   134  				}
   135  			}
   136  			if config.XudpConcurrency < 0 {
   137  				h.xudp = &mux.ClientManager{Enabled: false}
   138  			}
   139  			if config.XudpConcurrency == 0 {
   140  				h.xudp = nil // same as before
   141  			}
   142  			if config.XudpConcurrency > 0 {
   143  				h.xudp = &mux.ClientManager{
   144  					Enabled: true,
   145  					Picker: &mux.IncrementalWorkerPicker{
   146  						Factory: &mux.DialingWorkerFactory{
   147  							Proxy:  proxyHandler,
   148  							Dialer: h,
   149  							Strategy: mux.ClientStrategy{
   150  								MaxConcurrency: uint32(config.XudpConcurrency),
   151  								MaxConnection:  128,
   152  							},
   153  						},
   154  					},
   155  				}
   156  			}
   157  			h.udp443 = config.XudpProxyUDP443
   158  		}
   159  	}
   160  
   161  	h.proxy = proxyHandler
   162  	return h, nil
   163  }
   164  
   165  // Tag implements outbound.Handler.
   166  func (h *Handler) Tag() string {
   167  	return h.tag
   168  }
   169  
   170  // Dispatch implements proxy.Outbound.Dispatch.
   171  func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
   172  	outbound := session.OutboundFromContext(ctx)
   173  	if outbound.Target.Network == net.Network_UDP && outbound.OriginalTarget.Address != nil && outbound.OriginalTarget.Address != outbound.Target.Address {
   174  		link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: outbound.Target.Address, OriginalDest: outbound.OriginalTarget.Address}
   175  		link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: outbound.Target.Address, OriginalDest: outbound.OriginalTarget.Address}
   176  	}
   177  	if h.mux != nil {
   178  		test := func(err error) {
   179  			if err != nil {
   180  				err := newError("failed to process mux outbound traffic").Base(err)
   181  				session.SubmitOutboundErrorToOriginator(ctx, err)
   182  				err.WriteToLog(session.ExportIDToError(ctx))
   183  				common.Interrupt(link.Writer)
   184  			}
   185  		}
   186  		if outbound.Target.Network == net.Network_UDP && outbound.Target.Port == 443 {
   187  			switch h.udp443 {
   188  			case "reject":
   189  				test(newError("XUDP rejected UDP/443 traffic").AtInfo())
   190  				return
   191  			case "skip":
   192  				goto out
   193  			}
   194  		}
   195  		if h.xudp != nil && outbound.Target.Network == net.Network_UDP {
   196  			if !h.xudp.Enabled {
   197  				goto out
   198  			}
   199  			test(h.xudp.Dispatch(ctx, link))
   200  			return
   201  		}
   202  		if h.mux.Enabled {
   203  			test(h.mux.Dispatch(ctx, link))
   204  			return
   205  		}
   206  	}
   207  out:
   208  	err := h.proxy.Process(ctx, link, h)
   209  	if err != nil {
   210  		if errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe) || errors.Is(err, context.Canceled) {
   211  			err = nil
   212  		}
   213  	}
   214  	if err != nil {
   215  		// Ensure outbound ray is properly closed.
   216  		err := newError("failed to process outbound traffic").Base(err)
   217  		session.SubmitOutboundErrorToOriginator(ctx, err)
   218  		err.WriteToLog(session.ExportIDToError(ctx))
   219  		common.Interrupt(link.Writer)
   220  	} else {
   221  		common.Close(link.Writer)
   222  	}
   223  	common.Interrupt(link.Reader)
   224  }
   225  
   226  // Address implements internet.Dialer.
   227  func (h *Handler) Address() net.Address {
   228  	if h.senderSettings == nil || h.senderSettings.Via == nil {
   229  		return nil
   230  	}
   231  	return h.senderSettings.Via.AsAddress()
   232  }
   233  
   234  func (h *Handler) DestIpAddress() net.IP {
   235  	return internet.DestIpAddress()
   236  }
   237  
   238  // Dial implements internet.Dialer.
   239  func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connection, error) {
   240  	if h.senderSettings != nil {
   241  		if h.senderSettings.ProxySettings.HasTag() {
   242  			tag := h.senderSettings.ProxySettings.Tag
   243  			handler := h.outboundManager.GetHandler(tag)
   244  			if handler != nil {
   245  				newError("proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog(session.ExportIDToError(ctx))
   246  				ctx = session.ContextWithOutbound(ctx, &session.Outbound{
   247  					Target: dest,
   248  				})
   249  
   250  				opts := pipe.OptionsFromContext(ctx)
   251  				uplinkReader, uplinkWriter := pipe.New(opts...)
   252  				downlinkReader, downlinkWriter := pipe.New(opts...)
   253  
   254  				go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter})
   255  				conn := cnc.NewConnection(cnc.ConnectionInputMulti(uplinkWriter), cnc.ConnectionOutputMulti(downlinkReader))
   256  
   257  				if config := tls.ConfigFromStreamSettings(h.streamSettings); config != nil {
   258  					tlsConfig := config.GetTLSConfig(tls.WithDestination(dest))
   259  					conn = tls.Client(conn, tlsConfig)
   260  				}
   261  
   262  				return h.getStatCouterConnection(conn), nil
   263  			}
   264  
   265  			newError("failed to get outbound handler with tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
   266  		}
   267  
   268  		if h.senderSettings.Via != nil {
   269  			outbound := session.OutboundFromContext(ctx)
   270  			if outbound == nil {
   271  				outbound = new(session.Outbound)
   272  				ctx = session.ContextWithOutbound(ctx, outbound)
   273  			}
   274  			if h.senderSettings.ViaCidr == "" {
   275  				outbound.Gateway = h.senderSettings.Via.AsAddress()
   276  			} else { //Get a random address.
   277  				outbound.Gateway = ParseRandomIPv6(h.senderSettings.Via.AsAddress(), h.senderSettings.ViaCidr)
   278  			}
   279  		}
   280  	}
   281  
   282  	if conn, err := h.getUoTConnection(ctx, dest); err != os.ErrInvalid {
   283  		return conn, err
   284  	}
   285  
   286  	conn, err := internet.Dial(ctx, dest, h.streamSettings)
   287  	conn = h.getStatCouterConnection(conn)
   288  	outbound := session.OutboundFromContext(ctx)
   289  	if outbound != nil {
   290  		outbound.Conn = conn
   291  	}
   292  	return conn, err
   293  }
   294  
   295  func (h *Handler) getStatCouterConnection(conn stat.Connection) stat.Connection {
   296  	if h.uplinkCounter != nil || h.downlinkCounter != nil {
   297  		return &stat.CounterConnection{
   298  			Connection:   conn,
   299  			ReadCounter:  h.downlinkCounter,
   300  			WriteCounter: h.uplinkCounter,
   301  		}
   302  	}
   303  	return conn
   304  }
   305  
   306  // GetOutbound implements proxy.GetOutbound.
   307  func (h *Handler) GetOutbound() proxy.Outbound {
   308  	return h.proxy
   309  }
   310  
   311  // Start implements common.Runnable.
   312  func (h *Handler) Start() error {
   313  	return nil
   314  }
   315  
   316  // Close implements common.Closable.
   317  func (h *Handler) Close() error {
   318  	common.Close(h.mux)
   319  	return nil
   320  }
   321  
   322  
   323  func ParseRandomIPv6(address net.Address, prefix string) net.Address {
   324  	_, network, _ := gonet.ParseCIDR(address.IP().String() + "/" + prefix)
   325  
   326  	maskSize, totalBits := network.Mask.Size()
   327  	subnetSize := big.NewInt(1).Lsh(big.NewInt(1), uint(totalBits-maskSize))
   328  
   329  	// random
   330  	randomBigInt, _ := rand.Int(rand.Reader, subnetSize)
   331  
   332  	startIPBigInt := big.NewInt(0).SetBytes(network.IP.To16())
   333  	randomIPBigInt := big.NewInt(0).Add(startIPBigInt, randomBigInt)
   334  
   335  	randomIPBytes := randomIPBigInt.Bytes()
   336  	randomIPBytes = append(make([]byte, 16-len(randomIPBytes)), randomIPBytes...)
   337  
   338  	return net.ParseAddress(gonet.IP(randomIPBytes).String())
   339  }