unix.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package inbound
  2. import (
  3. "context"
  4. "v2ray.com/core/app/proxyman"
  5. "v2ray.com/core/app/proxyman/mux"
  6. "v2ray.com/core/common"
  7. "v2ray.com/core/common/net"
  8. "v2ray.com/core/proxy"
  9. "v2ray.com/core/transport/internet/domainsocket"
  10. )
  11. type UnixInboundHandler struct {
  12. tag string
  13. listenerHolder *domainsocket.Listener
  14. ctx context.Context
  15. path string
  16. proxy proxy.Inbound
  17. mux *mux.Server
  18. additional *proxyman.UnixReceiverConfig
  19. }
  20. func (uih *UnixInboundHandler) Start() error {
  21. var err error
  22. uih.listenerHolder, err = domainsocket.ListenDS(uih.ctx, uih.path)
  23. if err != nil {
  24. return newError(err).AtError()
  25. }
  26. err = uih.listenerHolder.LowerUP()
  27. if err != nil {
  28. return newError(err).AtError()
  29. }
  30. nchan := make(chan net.Conn, 2)
  31. err = uih.listenerHolder.UP(nchan, false)
  32. if err != nil {
  33. return newError(err).AtError()
  34. }
  35. go uih.progressTraffic(nchan)
  36. return nil
  37. }
  38. func (uih *UnixInboundHandler) progressTraffic(rece <-chan net.Conn) {
  39. for {
  40. conn, notclosed := <-rece
  41. if !notclosed {
  42. return
  43. }
  44. go func(conn net.Conn) {
  45. ctx, cancel := context.WithCancel(uih.ctx)
  46. if len(uih.tag) > 0 {
  47. ctx = proxy.ContextWithInboundTag(ctx, uih.tag)
  48. }
  49. if err := uih.proxy.Process(ctx, net.Network_TCP, conn, uih.mux); err != nil {
  50. newError("connection ends").Base(err).WriteToLog()
  51. }
  52. cancel()
  53. conn.Close()
  54. }(conn)
  55. }
  56. }
  57. func (uih *UnixInboundHandler) Close() error {
  58. if uih.listenerHolder != nil {
  59. uih.listenerHolder.Down()
  60. return nil
  61. }
  62. return newError("Called UnixInboundHandler.Close while listenerHolder is nil")
  63. }
  64. func (uih *UnixInboundHandler) Tag() string {
  65. return uih.tag
  66. }
  67. func (uih *UnixInboundHandler) GetRandomInboundProxy() (interface{}, net.Port, int) {
  68. //It makes bo sense to support it
  69. return nil, 0, 0
  70. }
  71. func NewUnixInboundHandler(ctx context.Context, tag string, receiverConfig *proxyman.UnixReceiverConfig, proxyConfig interface{}) (*UnixInboundHandler, error) {
  72. rawProxy, err := common.CreateObject(ctx, proxyConfig)
  73. if err != nil {
  74. return nil, err
  75. }
  76. p, ok := rawProxy.(proxy.Inbound)
  77. if !ok {
  78. return nil, newError("not an inbound proxy.")
  79. }
  80. h := &UnixInboundHandler{
  81. proxy: p,
  82. mux: mux.NewServer(ctx),
  83. tag: tag,
  84. ctx: ctx,
  85. path: receiverConfig.DomainSockSettings.GetPath(),
  86. additional: receiverConfig,
  87. }
  88. return h, nil
  89. }