handler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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.senderSettings != nil && h.senderSettings.DomainStrategy != proxyman.SenderConfig_AS_IS {
  139. outbound := session.OutboundFromContext(ctx)
  140. if outbound == nil {
  141. outbound = new(session.Outbound)
  142. ctx = session.ContextWithOutbound(ctx, outbound)
  143. }
  144. if outbound.Target.Address != nil && outbound.Target.Address.Family().IsDomain() {
  145. if addr := h.resolveIP(ctx, outbound.Target.Address.Domain(), h.Address()); addr != nil {
  146. outbound.Target.Address = addr
  147. }
  148. }
  149. }
  150. if h.mux != nil && (h.mux.Enabled || session.MuxPreferedFromContext(ctx)) {
  151. if err := h.mux.Dispatch(ctx, link); err != nil {
  152. err := newError("failed to process mux outbound traffic").Base(err)
  153. session.SubmitOutboundErrorToOriginator(ctx, err)
  154. err.WriteToLog(session.ExportIDToError(ctx))
  155. common.Interrupt(link.Writer)
  156. }
  157. } else {
  158. if err := h.proxy.Process(ctx, link, h); err != nil {
  159. // Ensure outbound ray is properly closed.
  160. err := newError("failed to process outbound traffic").Base(err)
  161. session.SubmitOutboundErrorToOriginator(ctx, err)
  162. err.WriteToLog(session.ExportIDToError(ctx))
  163. common.Interrupt(link.Writer)
  164. } else {
  165. common.Must(common.Close(link.Writer))
  166. }
  167. common.Interrupt(link.Reader)
  168. }
  169. }
  170. // Address implements internet.Dialer.
  171. func (h *Handler) Address() net.Address {
  172. if h.senderSettings == nil || h.senderSettings.Via == nil {
  173. return nil
  174. }
  175. return h.senderSettings.Via.AsAddress()
  176. }
  177. // Dial implements internet.Dialer.
  178. func (h *Handler) Dial(ctx context.Context, dest net.Destination) (internet.Connection, error) {
  179. if h.senderSettings != nil {
  180. if h.senderSettings.ProxySettings.HasTag() && !h.senderSettings.ProxySettings.TransportLayerProxy {
  181. tag := h.senderSettings.ProxySettings.Tag
  182. handler := h.outboundManager.GetHandler(tag)
  183. if handler != nil {
  184. newError("proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog(session.ExportIDToError(ctx))
  185. ctx = session.ContextWithOutbound(ctx, &session.Outbound{
  186. Target: dest,
  187. })
  188. opts := pipe.OptionsFromContext(ctx)
  189. uplinkReader, uplinkWriter := pipe.New(opts...)
  190. downlinkReader, downlinkWriter := pipe.New(opts...)
  191. go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter})
  192. conn := net.NewConnection(net.ConnectionInputMulti(uplinkWriter), net.ConnectionOutputMulti(downlinkReader))
  193. securityEngine, err := security.CreateSecurityEngineFromSettings(ctx, h.streamSettings)
  194. if err != nil {
  195. return nil, newError("unable to create security engine").Base(err)
  196. }
  197. if securityEngine != nil {
  198. conn, err = securityEngine.Client(conn, security.OptionWithDestination{Dest: dest})
  199. if err != nil {
  200. return nil, newError("unable to create security protocol client from security engine").Base(err)
  201. }
  202. }
  203. return h.getStatCouterConnection(conn), nil
  204. }
  205. newError("failed to get outbound handler with tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  206. }
  207. if h.senderSettings.Via != nil {
  208. outbound := session.OutboundFromContext(ctx)
  209. if outbound == nil {
  210. outbound = new(session.Outbound)
  211. ctx = session.ContextWithOutbound(ctx, outbound)
  212. }
  213. outbound.Gateway = h.senderSettings.Via.AsAddress()
  214. }
  215. if h.senderSettings.DomainStrategy != proxyman.SenderConfig_AS_IS {
  216. outbound := session.OutboundFromContext(ctx)
  217. if outbound == nil {
  218. outbound = new(session.Outbound)
  219. ctx = session.ContextWithOutbound(ctx, outbound)
  220. }
  221. outbound.Resolver = func(ctx context.Context, domain string) net.Address {
  222. return h.resolveIP(ctx, domain, h.Address())
  223. }
  224. }
  225. }
  226. enablePacketAddrCapture := true
  227. if h.senderSettings != nil && h.senderSettings.ProxySettings != nil && h.senderSettings.ProxySettings.HasTag() && h.senderSettings.ProxySettings.TransportLayerProxy {
  228. tag := h.senderSettings.ProxySettings.Tag
  229. newError("transport layer proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog(session.ExportIDToError(ctx))
  230. ctx = session.SetTransportLayerProxyTagToContext(ctx, tag)
  231. enablePacketAddrCapture = false
  232. }
  233. if isStream, err := packetaddr.GetDestinationSubsetOf(dest); err == nil && enablePacketAddrCapture {
  234. packetConn, err := internet.ListenSystemPacket(ctx, &net.UDPAddr{IP: net.AnyIP.IP(), Port: 0}, h.streamSettings.SocketSettings)
  235. if err != nil {
  236. return nil, newError("unable to listen socket").Base(err)
  237. }
  238. conn := packetaddr.ToPacketAddrConnWrapper(packetConn, isStream)
  239. return h.getStatCouterConnection(conn), nil
  240. }
  241. proxyEnvironment := envctx.EnvironmentFromContext(h.ctx).(environment.ProxyEnvironment)
  242. transportEnvironment, err := proxyEnvironment.NarrowScopeToTransport("transport")
  243. if err != nil {
  244. return nil, newError("unable to narrow environment to transport").Base(err)
  245. }
  246. ctx = envctx.ContextWithEnvironment(ctx, transportEnvironment)
  247. conn, err := internet.Dial(ctx, dest, h.streamSettings)
  248. return h.getStatCouterConnection(conn), err
  249. }
  250. func (h *Handler) resolveIP(ctx context.Context, domain string, localAddr net.Address) net.Address {
  251. strategy := h.senderSettings.DomainStrategy
  252. ips, err := dns.LookupIPWithOption(h.dns, domain, dns.IPOption{
  253. IPv4Enable: strategy == proxyman.SenderConfig_USE_IP || strategy == proxyman.SenderConfig_USE_IP4 || (localAddr != nil && localAddr.Family().IsIPv4()),
  254. IPv6Enable: strategy == proxyman.SenderConfig_USE_IP || strategy == proxyman.SenderConfig_USE_IP6 || (localAddr != nil && localAddr.Family().IsIPv6()),
  255. FakeEnable: false,
  256. })
  257. if err != nil {
  258. newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx))
  259. }
  260. if len(ips) == 0 {
  261. return nil
  262. }
  263. return net.IPAddress(ips[dice.Roll(len(ips))])
  264. }
  265. func (h *Handler) getStatCouterConnection(conn internet.Connection) internet.Connection {
  266. if h.uplinkCounter != nil || h.downlinkCounter != nil {
  267. return &internet.StatCouterConnection{
  268. Connection: conn,
  269. ReadCounter: h.downlinkCounter,
  270. WriteCounter: h.uplinkCounter,
  271. }
  272. }
  273. return conn
  274. }
  275. // GetOutbound implements proxy.GetOutbound.
  276. func (h *Handler) GetOutbound() proxy.Outbound {
  277. return h.proxy
  278. }
  279. // Start implements common.Runnable.
  280. func (h *Handler) Start() error {
  281. return nil
  282. }
  283. // Close implements common.Closable.
  284. func (h *Handler) Close() error {
  285. common.Close(h.mux)
  286. if closableProxy, ok := h.proxy.(common.Closable); ok {
  287. if err := closableProxy.Close(); err != nil {
  288. return newError("unable to close proxy").Base(err)
  289. }
  290. }
  291. return nil
  292. }