handler.go 7.5 KB

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