handler.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. package outbound
  2. import (
  3. "context"
  4. core "github.com/v2fly/v2ray-core/v5"
  5. "github.com/v2fly/v2ray-core/v5/app/proxyman"
  6. "github.com/v2fly/v2ray-core/v5/common"
  7. "github.com/v2fly/v2ray-core/v5/common/dice"
  8. "github.com/v2fly/v2ray-core/v5/common/environment"
  9. "github.com/v2fly/v2ray-core/v5/common/environment/envctx"
  10. "github.com/v2fly/v2ray-core/v5/common/mux"
  11. "github.com/v2fly/v2ray-core/v5/common/net"
  12. "github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
  13. "github.com/v2fly/v2ray-core/v5/common/serial"
  14. "github.com/v2fly/v2ray-core/v5/common/session"
  15. "github.com/v2fly/v2ray-core/v5/features/dns"
  16. "github.com/v2fly/v2ray-core/v5/features/outbound"
  17. "github.com/v2fly/v2ray-core/v5/features/policy"
  18. "github.com/v2fly/v2ray-core/v5/features/stats"
  19. "github.com/v2fly/v2ray-core/v5/proxy"
  20. "github.com/v2fly/v2ray-core/v5/transport"
  21. "github.com/v2fly/v2ray-core/v5/transport/internet"
  22. "github.com/v2fly/v2ray-core/v5/transport/internet/security"
  23. "github.com/v2fly/v2ray-core/v5/transport/pipe"
  24. )
  25. func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter) {
  26. var uplinkCounter stats.Counter
  27. var downlinkCounter stats.Counter
  28. policy := v.GetFeature(policy.ManagerType()).(policy.Manager)
  29. if len(tag) > 0 && policy.ForSystem().Stats.OutboundUplink {
  30. statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
  31. name := "outbound>>>" + tag + ">>>traffic>>>uplink"
  32. c, _ := stats.GetOrRegisterCounter(statsManager, name)
  33. if c != nil {
  34. uplinkCounter = c
  35. }
  36. }
  37. if len(tag) > 0 && policy.ForSystem().Stats.OutboundDownlink {
  38. statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
  39. name := "outbound>>>" + tag + ">>>traffic>>>downlink"
  40. c, _ := stats.GetOrRegisterCounter(statsManager, name)
  41. if c != nil {
  42. downlinkCounter = c
  43. }
  44. }
  45. return uplinkCounter, downlinkCounter
  46. }
  47. // Handler is an implements of outbound.Handler.
  48. type Handler struct {
  49. ctx context.Context
  50. tag string
  51. senderSettings *proxyman.SenderConfig
  52. streamSettings *internet.MemoryStreamConfig
  53. proxy proxy.Outbound
  54. outboundManager outbound.Manager
  55. mux *mux.ClientManager
  56. uplinkCounter stats.Counter
  57. downlinkCounter stats.Counter
  58. dns dns.Client
  59. }
  60. // NewHandler create a new Handler based on the given configuration.
  61. func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbound.Handler, error) {
  62. v := core.MustFromContext(ctx)
  63. uplinkCounter, downlinkCounter := getStatCounter(v, config.Tag)
  64. h := &Handler{
  65. ctx: ctx,
  66. tag: config.Tag,
  67. outboundManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager),
  68. uplinkCounter: uplinkCounter,
  69. downlinkCounter: downlinkCounter,
  70. }
  71. if config.SenderSettings != nil {
  72. senderSettings, err := serial.GetInstanceOf(config.SenderSettings)
  73. if err != nil {
  74. return nil, err
  75. }
  76. switch s := senderSettings.(type) {
  77. case *proxyman.SenderConfig:
  78. h.senderSettings = s
  79. mss, err := internet.ToMemoryStreamConfig(s.StreamSettings)
  80. if err != nil {
  81. return nil, newError("failed to parse stream settings").Base(err).AtWarning()
  82. }
  83. h.streamSettings = mss
  84. default:
  85. return nil, newError("settings is not SenderConfig")
  86. }
  87. }
  88. proxyConfig, err := serial.GetInstanceOf(config.ProxySettings)
  89. if err != nil {
  90. return nil, err
  91. }
  92. rawProxyHandler, err := common.CreateObject(ctx, proxyConfig)
  93. if err != nil {
  94. return nil, err
  95. }
  96. proxyHandler, ok := rawProxyHandler.(proxy.Outbound)
  97. if !ok {
  98. return nil, newError("not an outbound handler")
  99. }
  100. if h.senderSettings != nil && h.senderSettings.MultiplexSettings != nil {
  101. config := h.senderSettings.MultiplexSettings
  102. if config.Concurrency < 1 || config.Concurrency > 1024 {
  103. return nil, newError("invalid mux concurrency: ", config.Concurrency).AtWarning()
  104. }
  105. h.mux = &mux.ClientManager{
  106. Enabled: h.senderSettings.MultiplexSettings.Enabled,
  107. Picker: &mux.IncrementalWorkerPicker{
  108. Factory: mux.NewDialingWorkerFactory(
  109. ctx,
  110. proxyHandler,
  111. h,
  112. mux.ClientStrategy{
  113. MaxConcurrency: config.Concurrency,
  114. MaxConnection: 128,
  115. },
  116. ),
  117. },
  118. }
  119. }
  120. if h.senderSettings != nil && h.senderSettings.DomainStrategy != proxyman.SenderConfig_AS_IS {
  121. err := core.RequireFeatures(ctx, func(d dns.Client) error {
  122. h.dns = d
  123. return nil
  124. })
  125. if err != nil {
  126. return nil, err
  127. }
  128. }
  129. h.proxy = proxyHandler
  130. return h, nil
  131. }
  132. // Tag implements outbound.Handler.
  133. func (h *Handler) Tag() string {
  134. return h.tag
  135. }
  136. // Dispatch implements proxy.Outbound.Dispatch.
  137. func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
  138. if h.mux != nil && (h.mux.Enabled || session.MuxPreferedFromContext(ctx)) {
  139. if err := h.mux.Dispatch(ctx, link); err != nil {
  140. err := newError("failed to process mux outbound traffic").Base(err)
  141. session.SubmitOutboundErrorToOriginator(ctx, err)
  142. err.WriteToLog(session.ExportIDToError(ctx))
  143. common.Interrupt(link.Writer)
  144. }
  145. } else {
  146. if err := h.proxy.Process(ctx, link, h); err != nil {
  147. // Ensure outbound ray is properly closed.
  148. err := newError("failed to process outbound traffic").Base(err)
  149. session.SubmitOutboundErrorToOriginator(ctx, err)
  150. err.WriteToLog(session.ExportIDToError(ctx))
  151. common.Interrupt(link.Writer)
  152. } else {
  153. common.Must(common.Close(link.Writer))
  154. }
  155. common.Interrupt(link.Reader)
  156. }
  157. }
  158. // Address implements internet.Dialer.
  159. func (h *Handler) Address() net.Address {
  160. if h.senderSettings == nil || h.senderSettings.Via == nil {
  161. return nil
  162. }
  163. return h.senderSettings.Via.AsAddress()
  164. }
  165. // Dial implements internet.Dialer.
  166. func (h *Handler) Dial(ctx context.Context, dest net.Destination) (internet.Connection, error) {
  167. if h.senderSettings != nil {
  168. if h.senderSettings.ProxySettings.HasTag() && !h.senderSettings.ProxySettings.TransportLayerProxy {
  169. tag := h.senderSettings.ProxySettings.Tag
  170. handler := h.outboundManager.GetHandler(tag)
  171. if handler != nil {
  172. newError("proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog(session.ExportIDToError(ctx))
  173. ctx = session.ContextWithOutbound(ctx, &session.Outbound{
  174. Target: dest,
  175. })
  176. opts := pipe.OptionsFromContext(ctx)
  177. uplinkReader, uplinkWriter := pipe.New(opts...)
  178. downlinkReader, downlinkWriter := pipe.New(opts...)
  179. go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter})
  180. conn := net.NewConnection(net.ConnectionInputMulti(uplinkWriter), net.ConnectionOutputMulti(downlinkReader))
  181. securityEngine, err := security.CreateSecurityEngineFromSettings(ctx, h.streamSettings)
  182. if err != nil {
  183. return nil, newError("unable to create security engine").Base(err)
  184. }
  185. if securityEngine != nil {
  186. conn, err = securityEngine.Client(conn, security.OptionWithDestination{Dest: dest})
  187. if err != nil {
  188. return nil, newError("unable to create security protocol client from security engine").Base(err)
  189. }
  190. }
  191. return h.getStatCouterConnection(conn), nil
  192. }
  193. newError("failed to get outbound handler with tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  194. }
  195. if h.senderSettings.Via != nil {
  196. outbound := session.OutboundFromContext(ctx)
  197. if outbound == nil {
  198. outbound = new(session.Outbound)
  199. ctx = session.ContextWithOutbound(ctx, outbound)
  200. }
  201. outbound.Gateway = h.senderSettings.Via.AsAddress()
  202. }
  203. if h.senderSettings.DomainStrategy != proxyman.SenderConfig_AS_IS {
  204. outbound := session.OutboundFromContext(ctx)
  205. if outbound == nil {
  206. outbound = new(session.Outbound)
  207. ctx = session.ContextWithOutbound(ctx, outbound)
  208. }
  209. outbound.Resolver = func(ctx context.Context, domain string) net.Address {
  210. return h.resolveIP(ctx, domain, h.Address())
  211. }
  212. }
  213. }
  214. enablePacketAddrCapture := true
  215. if h.senderSettings != nil && h.senderSettings.ProxySettings != nil && h.senderSettings.ProxySettings.HasTag() && h.senderSettings.ProxySettings.TransportLayerProxy {
  216. tag := h.senderSettings.ProxySettings.Tag
  217. newError("transport layer proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog(session.ExportIDToError(ctx))
  218. ctx = session.SetTransportLayerProxyTagToContext(ctx, tag)
  219. enablePacketAddrCapture = false
  220. }
  221. if isStream, err := packetaddr.GetDestinationSubsetOf(dest); err == nil && enablePacketAddrCapture {
  222. packetConn, err := internet.ListenSystemPacket(ctx, &net.UDPAddr{IP: net.AnyIP.IP(), Port: 0}, h.streamSettings.SocketSettings)
  223. if err != nil {
  224. return nil, newError("unable to listen socket").Base(err)
  225. }
  226. conn := packetaddr.ToPacketAddrConnWrapper(packetConn, isStream)
  227. return h.getStatCouterConnection(conn), nil
  228. }
  229. proxyEnvironment := envctx.EnvironmentFromContext(h.ctx).(environment.ProxyEnvironment)
  230. transportEnvironment, err := proxyEnvironment.NarrowScopeToTransport("transport")
  231. if err != nil {
  232. return nil, newError("unable to narrow environment to transport").Base(err)
  233. }
  234. ctx = envctx.ContextWithEnvironment(ctx, transportEnvironment)
  235. conn, err := internet.Dial(ctx, dest, h.streamSettings)
  236. return h.getStatCouterConnection(conn), err
  237. }
  238. func (h *Handler) resolveIP(ctx context.Context, domain string, localAddr net.Address) net.Address {
  239. strategy := h.senderSettings.DomainStrategy
  240. ips, err := dns.LookupIPWithOption(h.dns, domain, dns.IPOption{
  241. IPv4Enable: strategy == proxyman.SenderConfig_USE_IP || strategy == proxyman.SenderConfig_USE_IP4 || (localAddr != nil && localAddr.Family().IsIPv4()),
  242. IPv6Enable: strategy == proxyman.SenderConfig_USE_IP || strategy == proxyman.SenderConfig_USE_IP6 || (localAddr != nil && localAddr.Family().IsIPv6()),
  243. FakeEnable: false,
  244. })
  245. if err != nil {
  246. newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx))
  247. }
  248. if len(ips) == 0 {
  249. return nil
  250. }
  251. return net.IPAddress(ips[dice.Roll(len(ips))])
  252. }
  253. func (h *Handler) getStatCouterConnection(conn internet.Connection) internet.Connection {
  254. if h.uplinkCounter != nil || h.downlinkCounter != nil {
  255. return &internet.StatCouterConnection{
  256. Connection: conn,
  257. ReadCounter: h.downlinkCounter,
  258. WriteCounter: h.uplinkCounter,
  259. }
  260. }
  261. return conn
  262. }
  263. // GetOutbound implements proxy.GetOutbound.
  264. func (h *Handler) GetOutbound() proxy.Outbound {
  265. return h.proxy
  266. }
  267. // Start implements common.Runnable.
  268. func (h *Handler) Start() error {
  269. return nil
  270. }
  271. // Close implements common.Closable.
  272. func (h *Handler) Close() error {
  273. common.Close(h.mux)
  274. return nil
  275. }