handler.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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/mux"
  8. "github.com/v2fly/v2ray-core/v5/common/net"
  9. "github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
  10. "github.com/v2fly/v2ray-core/v5/common/serial"
  11. "github.com/v2fly/v2ray-core/v5/common/session"
  12. "github.com/v2fly/v2ray-core/v5/features/outbound"
  13. "github.com/v2fly/v2ray-core/v5/features/policy"
  14. "github.com/v2fly/v2ray-core/v5/features/stats"
  15. "github.com/v2fly/v2ray-core/v5/proxy"
  16. "github.com/v2fly/v2ray-core/v5/transport"
  17. "github.com/v2fly/v2ray-core/v5/transport/internet"
  18. "github.com/v2fly/v2ray-core/v5/transport/internet/tls"
  19. "github.com/v2fly/v2ray-core/v5/transport/pipe"
  20. )
  21. func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter) {
  22. var uplinkCounter stats.Counter
  23. var downlinkCounter stats.Counter
  24. policy := v.GetFeature(policy.ManagerType()).(policy.Manager)
  25. if len(tag) > 0 && policy.ForSystem().Stats.OutboundUplink {
  26. statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
  27. name := "outbound>>>" + tag + ">>>traffic>>>uplink"
  28. c, _ := stats.GetOrRegisterCounter(statsManager, name)
  29. if c != nil {
  30. uplinkCounter = c
  31. }
  32. }
  33. if len(tag) > 0 && policy.ForSystem().Stats.OutboundDownlink {
  34. statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
  35. name := "outbound>>>" + tag + ">>>traffic>>>downlink"
  36. c, _ := stats.GetOrRegisterCounter(statsManager, name)
  37. if c != nil {
  38. downlinkCounter = c
  39. }
  40. }
  41. return uplinkCounter, downlinkCounter
  42. }
  43. // Handler is an implements of outbound.Handler.
  44. type Handler struct {
  45. tag string
  46. senderSettings *proxyman.SenderConfig
  47. streamSettings *internet.MemoryStreamConfig
  48. proxy proxy.Outbound
  49. outboundManager outbound.Manager
  50. mux *mux.ClientManager
  51. uplinkCounter stats.Counter
  52. downlinkCounter stats.Counter
  53. }
  54. // NewHandler create a new Handler based on the given configuration.
  55. func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbound.Handler, error) {
  56. v := core.MustFromContext(ctx)
  57. uplinkCounter, downlinkCounter := getStatCounter(v, config.Tag)
  58. h := &Handler{
  59. tag: config.Tag,
  60. outboundManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager),
  61. uplinkCounter: uplinkCounter,
  62. downlinkCounter: downlinkCounter,
  63. }
  64. if config.SenderSettings != nil {
  65. senderSettings, err := serial.GetInstanceOf(config.SenderSettings)
  66. if err != nil {
  67. return nil, err
  68. }
  69. switch s := senderSettings.(type) {
  70. case *proxyman.SenderConfig:
  71. h.senderSettings = s
  72. mss, err := internet.ToMemoryStreamConfig(s.StreamSettings)
  73. if err != nil {
  74. return nil, newError("failed to parse stream settings").Base(err).AtWarning()
  75. }
  76. h.streamSettings = mss
  77. default:
  78. return nil, newError("settings is not SenderConfig")
  79. }
  80. }
  81. proxyConfig, err := serial.GetInstanceOf(config.ProxySettings)
  82. if err != nil {
  83. return nil, err
  84. }
  85. rawProxyHandler, err := common.CreateObject(ctx, proxyConfig)
  86. if err != nil {
  87. return nil, err
  88. }
  89. proxyHandler, ok := rawProxyHandler.(proxy.Outbound)
  90. if !ok {
  91. return nil, newError("not an outbound handler")
  92. }
  93. if h.senderSettings != nil && h.senderSettings.MultiplexSettings != nil {
  94. config := h.senderSettings.MultiplexSettings
  95. if config.Concurrency < 1 || config.Concurrency > 1024 {
  96. return nil, newError("invalid mux concurrency: ", config.Concurrency).AtWarning()
  97. }
  98. h.mux = &mux.ClientManager{
  99. Enabled: h.senderSettings.MultiplexSettings.Enabled,
  100. Picker: &mux.IncrementalWorkerPicker{
  101. Factory: mux.NewDialingWorkerFactory(
  102. ctx,
  103. proxyHandler,
  104. h,
  105. mux.ClientStrategy{
  106. MaxConcurrency: config.Concurrency,
  107. MaxConnection: 128,
  108. },
  109. ),
  110. },
  111. }
  112. }
  113. h.proxy = proxyHandler
  114. return h, nil
  115. }
  116. // Tag implements outbound.Handler.
  117. func (h *Handler) Tag() string {
  118. return h.tag
  119. }
  120. // Dispatch implements proxy.Outbound.Dispatch.
  121. func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
  122. if h.mux != nil && (h.mux.Enabled || session.MuxPreferedFromContext(ctx)) {
  123. if err := h.mux.Dispatch(ctx, link); err != nil {
  124. err := newError("failed to process mux outbound traffic").Base(err)
  125. session.SubmitOutboundErrorToOriginator(ctx, err)
  126. err.WriteToLog(session.ExportIDToError(ctx))
  127. common.Interrupt(link.Writer)
  128. }
  129. } else {
  130. if err := h.proxy.Process(ctx, link, h); err != nil {
  131. // Ensure outbound ray is properly closed.
  132. err := newError("failed to process outbound traffic").Base(err)
  133. session.SubmitOutboundErrorToOriginator(ctx, err)
  134. err.WriteToLog(session.ExportIDToError(ctx))
  135. common.Interrupt(link.Writer)
  136. } else {
  137. common.Must(common.Close(link.Writer))
  138. }
  139. common.Interrupt(link.Reader)
  140. }
  141. }
  142. // Address implements internet.Dialer.
  143. func (h *Handler) Address() net.Address {
  144. if h.senderSettings == nil || h.senderSettings.Via == nil {
  145. return nil
  146. }
  147. return h.senderSettings.Via.AsAddress()
  148. }
  149. // Dial implements internet.Dialer.
  150. func (h *Handler) Dial(ctx context.Context, dest net.Destination) (internet.Connection, error) {
  151. if h.senderSettings != nil {
  152. if h.senderSettings.ProxySettings.HasTag() && !h.senderSettings.ProxySettings.TransportLayerProxy {
  153. tag := h.senderSettings.ProxySettings.Tag
  154. handler := h.outboundManager.GetHandler(tag)
  155. if handler != nil {
  156. newError("proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog(session.ExportIDToError(ctx))
  157. ctx = session.ContextWithOutbound(ctx, &session.Outbound{
  158. Target: dest,
  159. })
  160. opts := pipe.OptionsFromContext(ctx)
  161. uplinkReader, uplinkWriter := pipe.New(opts...)
  162. downlinkReader, downlinkWriter := pipe.New(opts...)
  163. go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter})
  164. conn := net.NewConnection(net.ConnectionInputMulti(uplinkWriter), net.ConnectionOutputMulti(downlinkReader))
  165. if config := tls.ConfigFromStreamSettings(h.streamSettings); config != nil {
  166. tlsConfig := config.GetTLSConfig(tls.WithDestination(dest))
  167. conn = tls.Client(conn, tlsConfig)
  168. }
  169. return h.getStatCouterConnection(conn), nil
  170. }
  171. newError("failed to get outbound handler with tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  172. }
  173. if h.senderSettings.Via != nil {
  174. outbound := session.OutboundFromContext(ctx)
  175. if outbound == nil {
  176. outbound = new(session.Outbound)
  177. ctx = session.ContextWithOutbound(ctx, outbound)
  178. }
  179. outbound.Gateway = h.senderSettings.Via.AsAddress()
  180. }
  181. }
  182. var enablePacketAddrCapture = true
  183. if h.senderSettings != nil && h.senderSettings.ProxySettings != nil && h.senderSettings.ProxySettings.HasTag() && h.senderSettings.ProxySettings.TransportLayerProxy {
  184. tag := h.senderSettings.ProxySettings.Tag
  185. newError("transport layer proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog(session.ExportIDToError(ctx))
  186. ctx = session.SetTransportLayerProxyTagToContext(ctx, tag)
  187. enablePacketAddrCapture = false
  188. }
  189. if isStream, err := packetaddr.GetDestinationSubsetOf(dest); err == nil && enablePacketAddrCapture {
  190. packetConn, err := internet.ListenSystemPacket(ctx, &net.UDPAddr{IP: net.AnyIP.IP(), Port: 0}, h.streamSettings.SocketSettings)
  191. if err != nil {
  192. return nil, newError("unable to listen socket").Base(err)
  193. }
  194. conn := packetaddr.ToPacketAddrConnWrapper(packetConn, isStream)
  195. return h.getStatCouterConnection(conn), nil
  196. }
  197. conn, err := internet.Dial(ctx, dest, h.streamSettings)
  198. return h.getStatCouterConnection(conn), err
  199. }
  200. func (h *Handler) getStatCouterConnection(conn internet.Connection) internet.Connection {
  201. if h.uplinkCounter != nil || h.downlinkCounter != nil {
  202. return &internet.StatCouterConnection{
  203. Connection: conn,
  204. ReadCounter: h.downlinkCounter,
  205. WriteCounter: h.uplinkCounter,
  206. }
  207. }
  208. return conn
  209. }
  210. // GetOutbound implements proxy.GetOutbound.
  211. func (h *Handler) GetOutbound() proxy.Outbound {
  212. return h.proxy
  213. }
  214. // Start implements common.Runnable.
  215. func (h *Handler) Start() error {
  216. return nil
  217. }
  218. // Close implements common.Closable.
  219. func (h *Handler) Close() error {
  220. common.Close(h.mux)
  221. return nil
  222. }