unix.go 2.3 KB

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